<?php
require_once '../includes/init.php';

$user = new User($pdo);
if (!$user->isLoggedIn() || !$user->isTeacher()) {
    header("Location: ../index.php");
    exit;
}

if (!isset($_GET['exam_id'])) {
    header("Location: exams.php");
    exit;
}

$exam_id = $_GET['exam_id'];
$exam = $pdo->prepare("SELECT * FROM exams WHERE exam_id = ?");
$exam->execute([$exam_id]);
$exam_data = $exam->fetch();

if (!$exam_data) {
    die("Exam not found.");
}

$message = '';

// Handle Assignment
if (isset($_POST['assign_students'])) {
    // Clear existing assignments for this exam
    $pdo->prepare("DELETE FROM exam_assignments WHERE exam_id = ?")->execute([$exam_id]);
    
    if (isset($_POST['students']) && is_array($_POST['students'])) {
        $stmt = $pdo->prepare("INSERT INTO exam_assignments (exam_id, user_id) VALUES (?, ?)");
        $count = 0;
        foreach ($_POST['students'] as $student_id) {
            $stmt->execute([$exam_id, $student_id]);
            $count++;
        }
        $message = "Assigned $count students to the exam.";
    } else {
        $message = "No students assigned (Assignments cleared).";
    }
}

// Fetch Students in the Exam's Class
$class_id = $exam_data['class_id'];
if ($class_id) {
    $students = $pdo->prepare("SELECT * FROM users WHERE role = 'student' AND class_id = ? ORDER BY username ASC");
    $students->execute([$class_id]);
    $student_list = $students->fetchAll();
} else {
    $student_list = []; // Should ideally not happen if class is required
}

// Fetch Currently Assigned Students
$assigned = $pdo->prepare("SELECT user_id FROM exam_assignments WHERE exam_id = ?");
$assigned->execute([$exam_id]);
$assigned_ids = $assigned->fetchAll(PDO::FETCH_COLUMN);

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Assign Students</title>
    <style>
        body { font-family: sans-serif; padding: 20px; background: #f4f4f4; }
        .container { max-width: 800px; margin: 0 auto; background: white; padding: 20px; border-radius: 5px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }
        .student-list { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 10px; margin-top: 20px; }
        .student-item { padding: 10px; border: 1px solid #ddd; border-radius: 4px; }
        .btn { padding: 10px 20px; background: #007bff; color: white; border: none; cursor: pointer; font-size: 16px; }
        .back-link { display: inline-block; margin-bottom: 20px; color: #333; text-decoration: none; }
    </style>
    <script>
        function toggleAll(source) {
            checkboxes = document.getElementsByName('students[]');
            for(var i=0, n=checkboxes.length;i<n;i++) {
                checkboxes[i].checked = source.checked;
            }
        }
    </script>
</head>
<body>
    <div class="container">
        <a href="exams.php" class="back-link">← Back to Exams</a>
        <h1>Assign Students to: <?php echo htmlspecialchars($exam_data['title']); ?></h1>
        
        <?php if ($message): ?> <div style="color: green; margin-bottom: 10px;"><?php echo $message; ?></div> <?php endif; ?>

        <form method="POST">
            <div style="margin-bottom: 10px;">
                <input type="checkbox" onClick="toggleAll(this)"> Select All
            </div>
            
            <div class="student-list">
                <?php if (count($student_list) > 0): ?>
                    <?php foreach ($student_list as $s): ?>
                    <div class="student-item">
                        <label>
                            <input type="checkbox" name="students[]" value="<?php echo $s['user_id']; ?>"
                                <?php echo in_array($s['user_id'], $assigned_ids) ? 'checked' : ''; ?>>
                            <?php echo htmlspecialchars($s['username']); ?>
                        </label>
                    </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <p>No students found in this class.</p>
                <?php endif; ?>
            </div>

            <br>
            <button type="submit" name="assign_students" class="btn">Save Assignments</button>
        </form>
        
        <div style="margin-top: 30px; text-align: center; color: #777;">
            Designed by ferakeys
        </div>
    </div>
</body>
</html>
