<?php
session_start();
if(isset($_SESSION['teacher'])){
    $username = $_SESSION['teacher'];

    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <?php include '../admin/includes/styles.php'; ?>
        <?php
        require_once 'Classes/Assignment.php';
        $assignment_mgr = new Assignment();

        if (!isset($_GET['id'])) {
            header('Location: assignments');
            exit();
        }

        $submission_id = (int)$_GET['id'];
        $submission = $assignment_mgr->getSubmissionDetails($submission_id);

        if (!$submission) {
            header('Location: assignments');
            exit();
        }
        ?>
        <title>Grade Submission | <?php echo $school_name; ?></title>

        <style>
            .submission-header {
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: white;
                padding: 25px;
                border-radius: 10px;
                margin-bottom: 30px;
            }
            .student-info {
                padding: 15px;
                background: #f8f9fa;
                border-left: 4px solid #007bff;
                margin-bottom: 20px;
                border-radius: 4px;
            }
            .submission-info {
                padding: 15px;
                background: #e7f3ff;
                border-left: 4px solid #17a2b8;
                margin-bottom: 20px;
                border-radius: 4px;
            }
            .file-preview {
                padding: 15px;
                background: #f8f9fa;
                border: 1px solid #dee2e6;
                border-radius: 4px;
                margin: 10px 0;
            }
            .file-link {
                display: block;
                padding: 10px;
                background: #fff;
                border-left: 3px solid #28a745;
                margin: 5px 0;
                border-radius: 3px;
            }
            .grading-form {
                background: #f8f9fa;
                padding: 20px;
                border-radius: 5px;
            }
            .form-section {
                margin-bottom: 25px;
            }
            .form-section-title {
                font-size: 16px;
                font-weight: 600;
                margin-bottom: 15px;
                padding-bottom: 10px;
                border-bottom: 2px solid #007bff;
            }
            .marks-input-group {
                display: grid;
                grid-template-columns: 1fr 100px;
                gap: 10px;
                align-items: center;
            }
            .feedback-box {
                padding: 15px;
                background: #fff;
                border-left: 3px solid #ffc107;
                border-radius: 4px;
                min-height: 100px;
            }
            .submission-text {
                padding: 15px;
                background: #fff;
                border: 1px solid #dee2e6;
                border-radius: 4px;
                margin: 10px 0;
                max-height: 300px;
                overflow-y: auto;
            }
            .status-indicator {
                display: inline-block;
                padding: 5px 10px;
                border-radius: 4px;
                font-size: 12px;
                font-weight: 600;
            }
            .status-submitted {
                background: #d4edda;
                color: #155724;
            }
            .status-late {
                background: #fff3cd;
                color: #856404;
            }

            .fa-eye, .fa-edit, .fa-trash {
                background-color: transparent;
            }
        </style>
    </head>
    <body class="hold-transition sidebar-mini layout-fixed">
    <div class="wrapper">
        <?php include 'includes/notifications.php'; ?>
        <?php include "includes/sidebar.php"; ?>

        <div class="content-wrapper">
            <div class="content-header">
                <div class="container-fluid">
                    <div class="row mb-2">
                        <div class="col-sm-6">
                            <h1 class="m-0">Grade Submission</h1>
                        </div>
                        <div class="col-sm-6">
                            <ol class="breadcrumb float-sm-right">
                                <li class="breadcrumb-item"><a href="<?php echo $conn->teacher_url();?>">Home</a></li>
                                <li class="breadcrumb-item"><a href="<?php echo $conn->teacher_url();?>assignments">Assignments</a></li>
                                <li class="breadcrumb-item"><a href="<?php echo $conn->teacher_url();?>submissions?id=<?php echo $submission->assignment_id ?? 0; ?>">Submissions</a></li>
                                <li class="breadcrumb-item active">Grade</li>
                            </ol>
                        </div>
                    </div>
                </div>
            </div>

            <section class="content">
                <div class="container-fluid">

                    <!-- Header -->
                    <div class="submission-header">
                        <h2><?php echo htmlspecialchars($submission->assignment_title); ?></h2>
                        <p class="mb-0"><strong>Student:</strong> <?php echo htmlspecialchars($submission->student_name); ?> (<?php echo htmlspecialchars($submission->registerNO); ?>)</p>
                    </div>

                    <div class="row">
                        <div class="col-lg-8">

                            <!-- Student Info -->
                            <div class="student-info">
                                <div class="row">
                                    <div class="col-md-6">
                                        <strong>Student Name:</strong> <?php echo htmlspecialchars($submission->student_name); ?><br>
                                        <strong>Registration No:</strong> <?php echo htmlspecialchars($submission->registerNO); ?>
                                    </div>
                                    <div class="col-md-6">
                                    <span class="status-indicator status-<?php echo $submission->submission_status; ?>">
                                        <?php echo $submission->submission_status == 'late_submitted' ? 'Late Submitted' : 'Submitted'; ?>
                                    </span><br>
                                        <strong>Submitted:</strong> <?php echo date('M d, Y H:i', strtotime($submission->submitted_at)); ?>
                                    </div>
                                </div>
                            </div>

                            <!-- Submission Content -->
                            <div class="card">
                                <div class="card-header">
                                    <h3 class="card-title">Submission Content</h3>
                                </div>
                                <div class="card-body">

                                    <?php if ($submission->submission_text): ?>
                                        <div class="form-section">
                                            <h5 class="form-section-title">Submitted Text</h5>
                                            <div class="submission-text">
                                                <?php echo nl2br(htmlspecialchars($submission->submission_text)); ?>
                                            </div>
                                        </div>
                                    <?php endif; ?>

                                    <?php if ($submission->file_count > 0): ?>
                                        <div class="form-section">
                                            <h5 class="form-section-title">Submitted Files (<?php echo $submission->file_count; ?>)</h5>
                                            <?php
                                            $files = $assignment_mgr->getSubmissionFiles($submission_id);
                                            foreach ($files as $file) {
                                                ?>
                                                <a href="<?php echo $conn->main_url() . $file->file_path; ?>" target="_blank" class="file-link">
                                                    <i class="fas fa-download"></i> <?php echo htmlspecialchars($file->file_name); ?>
                                                    <small class="text-muted">(<?php echo htmlspecialchars($file->file_size); ?>)</small>
                                                </a>
                                                <?php
                                            }
                                            ?>
                                        </div>
                                    <?php endif; ?>

                                </div>
                            </div>

                            <!-- Grading Form -->
                            <div class="card mt-3">
                                <div class="card-header">
                                    <h3 class="card-title">Grade Submission</h3>
                                </div>
                                <div class="card-body">
                                    <form id="grading-form" method="POST">
                                        <input type="hidden" name="submission_id" value="<?php echo $submission_id; ?>">

                                        <!-- Marks -->
                                        <div class="form-section">
                                            <h5 class="form-section-title">Marks</h5>

                                            <div class="form-group">
                                                <label for="marks" class="col-form-label">Marks Obtained <span class="text-danger">*</span></label>
                                                <div class="marks-input-group">
                                                    <input type="number" class="form-control" id="marks" name="marks"
                                                           value="<?php echo $submission->marks_obtained ?? ''; ?>"
                                                           required min="0" max="<?php echo $submission->total_marks; ?>"
                                                           placeholder="Enter marks">
                                                    <span class="text-muted">/ <?php echo $submission->total_marks; ?></span>
                                                </div>
                                                <small class="form-text text-muted">Maximum <?php echo $submission->total_marks; ?> marks</small>
                                            </div>

                                            <div class="form-group" id="percentage-display" style="display: none;">
                                                <label class="col-form-label">Percentage</label>
                                                <div class="input-group">
                                                    <input type="text" class="form-control" id="percentage" readonly>
                                                    <div class="input-group-append">
                                                        <span class="input-group-text">%</span>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Feedback -->
                                        <div class="form-section">
                                            <h5 class="form-section-title">Feedback</h5>

                                            <div class="form-group">
                                                <label for="feedback" class="col-form-label">Teacher Feedback <span class="text-danger">*</span></label>
                                                <textarea class="form-control" id="feedback" name="feedback" rows="5" required
                                                          placeholder="Provide feedback to the student..."><?php echo htmlspecialchars($submission->teacher_feedback ?? ''); ?></textarea>
                                                <small class="form-text text-muted">Be constructive and specific. Explain what the student did well and what needs improvement.</small>
                                            </div>
                                        </div>

                                        <!-- Submit Button -->
                                        <div class="form-section">
                                            <button type="submit" name="grade_submission" class="btn btn-primary" id="submit-btn">
                                                <i class="fas fa-save"></i> Submit Grade
                                            </button>
                                            <a href="<?php echo $conn->teacher_url();?>submissions?id=<?php echo $submission->assignment_id; ?>" class="btn btn-secondary">
                                                <i class="fas fa-arrow-left"></i> Back to Submissions
                                            </a>
                                        </div>

                                    </form>
                                    <div id="success-msg"></div>
                                </div>
                            </div>

                        </div>

                        <!-- Sidebar -->
                        <div class="col-lg-4">

                            <!-- Submission Details -->
                            <div class="card">
                                <div class="card-header">
                                    <h3 class="card-title">Submission Details</h3>
                                </div>
                                <div class="card-body">
                                    <div class="mb-3">
                                        <strong>Status:</strong><br>
                                        <span class="status-indicator status-<?php echo $submission->submission_status; ?>">
                                        <?php echo ucfirst(str_replace('_', ' ', $submission->submission_status)); ?>
                                    </span>
                                    </div>

                                    <div class="mb-3">
                                        <strong>Submitted Date:</strong><br>
                                        <?php echo date('F d, Y \a\t h:i A', strtotime($submission->submitted_at)); ?>
                                    </div>

                                    <div class="mb-3">
                                        <strong>Total Files:</strong><br>
                                        <?php echo $submission->file_count ?? 0; ?> file(s)
                                    </div>

                                    <?php if ($submission->is_graded): ?>
                                        <hr>
                                        <div class="mb-3">
                                            <strong>Previously Graded:</strong><br>
                                            <?php echo $submission->marks_obtained; ?> / <?php echo $submission->total_marks; ?>
                                            (<?php echo number_format($submission->percentage, 1); ?>%)
                                        </div>

                                        <div class="mb-3">
                                            <strong>Grade:</strong><br>
                                            <span class="badge badge-<?php echo $submission->grade == 'A' || $submission->grade == 'B' ? 'success' : 'warning'; ?>">
                                        <?php echo $submission->grade; ?>
                                    </span>
                                        </div>

                                        <div class="mb-3">
                                            <strong>Graded By:</strong><br>
                                            <?php echo htmlspecialchars($submission->graded_by); ?>
                                        </div>

                                        <div class="mb-3">
                                            <strong>Graded Date:</strong><br>
                                            <?php echo date('M d, Y H:i', strtotime($submission->graded_at)); ?>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>

                            <!-- Grading Guidelines -->
                            <div class="card mt-3">
                                <div class="card-header">
                                    <h3 class="card-title">Grading Guidelines</h3>
                                </div>
                                <div class="card-body">
                                    <table class="table table-sm">
                                        <thead>
                                        <tr>
                                            <th>Percentage</th>
                                            <th>Grade</th>
                                        </tr>
                                        </thead>
                                        <tbody>
                                        <tr>
                                            <td>90% - 100%</td>
                                            <td><span class="badge badge-success">A</span></td>
                                        </tr>
                                        <tr>
                                            <td>80% - 89%</td>
                                            <td><span class="badge badge-success">B</span></td>
                                        </tr>
                                        <tr>
                                            <td>70% - 79%</td>
                                            <td><span class="badge badge-info">C</span></td>
                                        </tr>
                                        <tr>
                                            <td>60% - 69%</td>
                                            <td><span class="badge badge-warning">D</span></td>
                                        </tr>
                                        <tr>
                                            <td>Below 60%</td>
                                            <td><span class="badge badge-danger">F</span></td>
                                        </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>

                        </div>
                    </div>

                </div>
            </section>
        </div>

        <?php include "../admin/includes/footer.php"; ?>
    </div>


    <script>
        $(function() {
            var totalMarks = <?php echo $submission->total_marks; ?>;

            // Calculate percentage dynamically
            $('#marks').on('keyup change', function() {
                var marks = parseFloat($(this).val());
                if (marks >= 0 && marks <= totalMarks) {
                    var percentage = (marks / totalMarks) * 100;
                    $('#percentage').val(percentage.toFixed(2));
                    $('#percentage-display').show();
                } else {
                    $('#percentage-display').hide();
                }
            });

            // Trigger calculation on page load if marks exist
            if ($('#marks').val()) {
                $('#marks').trigger('change');
            }

            // Form submission
            $('#grading-form').on('submit', function(e) {
                e.preventDefault();

                var marks = parseFloat($('#marks').val());
                var feedback = $('#feedback').val().trim();

                // Validation
                if (marks < 0 || marks > totalMarks) {
                    alert('Please enter marks between 0 and ' + totalMarks);
                    return false;
                }

                if (feedback.length < 10) {
                    alert('Please provide meaningful feedback (at least 10 characters)');
                    return false;
                }

                var formData = new FormData(this);
                formData.append('grade_submission', '1');

                $.ajax({
                    url: 'process-grade-submission.php',
                    method: 'POST',
                    data: formData,
                    contentType: false,
                    cache: false,
                    processData: false,
                    beforeSend: function() {
                        $('#submit-btn').attr('disabled', 'disabled');
                        $('#submit-btn').html('<i class="fas fa-spinner fa-spin"></i> Submitting grade...');
                    },
                    success: function(data) {
                        $('#submit-btn').attr('disabled', false);
                        $('#submit-btn').html('<i class="fas fa-save"></i> Submit Grade');
                        $('#success-msg').html(data);

                        if (data.includes('success')) {
                            setTimeout(function() {
                                window.location.href = '<?php echo $conn->teacher_url();?>submissions?id=<?php echo $submission->assignment_id; ?>';
                            }, 2000);
                        }
                    },
                    error: function() {
                        $('#submit-btn').attr('disabled', false);
                        $('#submit-btn').html('<i class="fas fa-save"></i> Submit Grade');
                        alert('An error occurred. Please try again.');
                    }
                });
            });
        });
    </script>
    </body>
    </html>
    <?php
} else {
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Login to continue | <?php echo $school_name; ?></title>
        <?php include '../admin/includes/styles.php'; ?>
    </head>
    <body>
    <div class="container" style="margin-top: 20%;">
        <div class="row">
            <div class="col-lg-12 col-md-12">
                <div class="section-title text-center">
                    <h6>You need to login to continue</h6>
                    <div class="spinner-border text-info" role="status">
                        <span class="sr-only">Loading...</span>
                        <meta http-equiv='refresh' content='3; <?php echo $teacher_login_link; ?>'>
                    </div>
                    <p>Redirecting to the login page...</p>
                </div>
            </div>
        </div>
    </div>
    </body>
    </html>
    <?php
}
?>