<?php
session_start();
require_once('../config.php');

if (!isset($_SESSION['user_id']) || $_SESSION['role'] != 'lecturer') {
    header("Location: dashboard.php");
    exit();
}

include('../header/header.php');

$assignment_id = $_GET['id'] ?? null;
if (!$assignment_id) {
    header("Location: manage_assignments.php");
    exit();
}

$success = '';
$error = '';

// Handle grading
if (isset($_POST['grade_submission'])) {
    $submission_id = $_POST['submission_id'];
    $grade = $_POST['grade'];
    $feedback = $_POST['feedback'];
    $student_id = $_POST['student_id'];
    $course_id = $_POST['course_id'];

    try {
        $pdo->beginTransaction();
        
        // Update submission status and grade
        $stmt = $pdo->prepare("UPDATE submissions SET grade = ?, feedback = ?, status = 'graded' WHERE id = ?");
        $stmt->execute([$grade, $feedback, $submission_id]);

        // Recalculate and update student progress for this course
        // Progress = (Number of graded assignments / Total assignments) * 100
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM assignments WHERE course_id = ?");
        $stmt->execute([$course_id]);
        $total_assignments = $stmt->fetchColumn();

        $stmt = $pdo->prepare("
            SELECT COUNT(*) 
            FROM submissions s 
            JOIN assignments a ON s.assignment_id = a.id 
            WHERE a.course_id = ? AND s.student_id = ? AND s.status = 'graded'
        ");
        $stmt->execute([$course_id, $student_id]);
        $graded_count = $stmt->fetchColumn();

        $progress = ($total_assignments > 0) ? round(($graded_count / $total_assignments) * 100) : 0;

        $stmt = $pdo->prepare("UPDATE enrollments SET progress = ? WHERE student_id = ? AND course_id = ?");
        $stmt->execute([$progress, $student_id, $course_id]);

        $pdo->commit();
        $success = "Submission graded successfully and student progress updated!";
    } catch (PDOException $e) {
        $pdo->rollBack();
        $error = "Error during grading: " . $e->getMessage();
    }
}

// Fetch assignment details
$stmt = $pdo->prepare("SELECT a.*, c.course_name FROM assignments a JOIN courses c ON a.course_id = c.id WHERE a.id = ?");
$stmt->execute([$assignment_id]);
$assignment = $stmt->fetch();

// Fetch all submissions for this assignment
$stmt = $pdo->prepare("
    SELECT s.*, u.username, u.email 
    FROM submissions s 
    JOIN users u ON s.student_id = u.id 
    WHERE s.assignment_id = ? AND s.status IN ('submitted', 'graded')
    ORDER BY s.submitted_at DESC
");
$stmt->execute([$assignment_id]);
$submissions = $stmt->fetchAll();
?>

<div class="container-fluid py-4">
    <div class="mb-4">
        <a href="manage_assignments.php" class="text-decoration-none small"><i class="fas fa-arrow-left me-1"></i> Back to Assignments</a>
    </div>

    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h2 class="fw-bold mb-1">Grade Submissions</h2>
            <p class="text-muted mb-0"><?php echo htmlspecialchars($assignment['course_name']); ?>: <strong><?php echo htmlspecialchars($assignment['title']); ?></strong></p>
        </div>
    </div>

    <?php if($success): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <i class="fas fa-check-circle me-2"></i><?php echo $success; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <div class="card shadow-sm border-0">
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover align-middle mb-0">
                    <thead class="bg-light">
                        <tr>
                            <th class="ps-4">Student</th>
                            <th>Submitted Date</th>
                            <th>Status</th>
                            <th>Current Grade</th>
                            <th class="text-end pe-4">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($submissions)): ?>
                            <tr><td colspan="5" class="text-center py-5 text-muted">No submissions yet.</td></tr>
                        <?php endif; ?>
                        <?php foreach($submissions as $s): ?>
                            <tr>
                                <td class="ps-4">
                                    <div class="fw-bold"><?php echo htmlspecialchars($s['username']); ?></div>
                                    <small class="text-muted"><?php echo htmlspecialchars($s['email']); ?></small>
                                </td>
                                <td><?php echo date('M d, Y H:i', strtotime($s['submitted_at'])); ?></td>
                                <td>
                                    <span class="badge <?php echo $s['status'] == 'graded' ? 'bg-success' : 'bg-danger'; ?> text-capitalize">
                                        <?php echo $s['status']; ?>
                                    </span>
                                </td>
                                <td><?php echo $s['grade'] !== null ? $s['grade'] . '%' : 'Not Graded'; ?></td>
                                <td class="text-end pe-4">
                                    <a href="../uploads/submissions/<?php echo $s['file_path']; ?>" class="btn btn-sm btn-outline-info me-2" target="_blank">
                                        <i class="fas fa-download me-1"></i> View Work
                                    </a>
                                    <button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#gradeModal<?php echo $s['id']; ?>">
                                        <i class="fas fa-pen me-1"></i> Grade
                                    </button>

                                    <!-- Grade Modal -->
                                    <div class="modal fade text-start" id="gradeModal<?php echo $s['id']; ?>" tabindex="-1">
                                        <div class="modal-dialog">
                                            <div class="modal-content">
                                                <div class="modal-header">
                                                    <h5 class="modal-title fw-bold">Grade Submission: <?php echo htmlspecialchars($s['username']); ?></h5>
                                                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                                </div>
                                                <form method="POST">
                                                    <div class="modal-body">
                                                        <input type="hidden" name="submission_id" value="<?php echo $s['id']; ?>">
                                                        <input type="hidden" name="student_id" value="<?php echo $s['student_id']; ?>">
                                                        <input type="hidden" name="course_id" value="<?php echo $assignment['course_id']; ?>">
                                                        <div class="mb-3">
                                                            <label class="form-label small fw-bold">Grade (%)</label>
                                                            <input type="number" name="grade" class="form-control" value="<?php echo $s['grade']; ?>" min="0" max="100" required>
                                                        </div>
                                                        <div class="mb-3">
                                                            <label class="form-label small fw-bold">Feedback</label>
                                                            <textarea name="feedback" class="form-control" rows="4"><?php echo htmlspecialchars($s['feedback']); ?></textarea>
                                                        </div>
                                                    </div>
                                                    <div class="modal-footer">
                                                        <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                                                        <button type="submit" name="grade_submission" class="btn btn-primary px-4">Submit Grade</button>
                                                    </div>
                                                </form>
                                            </div>
                                        </div>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<?php include('../footer/footer.php'); ?>