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

// 1. SECURITY
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') { 
    die("Access Denied: Admin login required."); 
}

// 2. FETCH CLASSES
$classes = $pdo->query("SELECT * FROM classes ORDER BY class_name ASC")->fetchAll();

$students = [];
$exams = [];
$selected_class = $_GET['class_id'] ?? null;
$selected_student_id = $_GET['student_id'] ?? null;

// 3. FETCH STUDENTS (Using reg_number)
if ($selected_class) {
    $stmt = $pdo->prepare("SELECT id, fullname, reg_number FROM students WHERE class_id = ? ORDER BY fullname ASC");
    $stmt->execute([$selected_class]);
    $students = $stmt->fetchAll();
}

// 4. FETCH EXAMS
if ($selected_student_id) {
    $stmt = $pdo->prepare("SELECT e.*, 
        (SELECT status FROM exam_results WHERE exam_id = e.id AND student_id = ?) as attempt_status 
        FROM exams e WHERE e.class_id = ?");
    $stmt->execute([$selected_student_id, $selected_class]);
    $exams = $stmt->fetchAll();
}

// 5. HANDLE RESCHEDULE ACTION
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['do_reschedule'])) {
    $sid = $_POST['sid'];
    $eid = $_POST['eid'];
    try {
        $pdo->beginTransaction();
        
        // Remove previous attempt
        $pdo->prepare("DELETE FROM exam_results WHERE student_id = ? AND exam_id = ?")->execute([$sid, $eid]);
        
        // Grant new permission
        $pdo->prepare("INSERT INTO exam_permissions (student_id, exam_id, granted_by, status) 
                       VALUES (?, ?, ?, 'active') 
                       ON DUPLICATE KEY UPDATE status='active'")->execute([$sid, $eid, $_SESSION['user_id']]);
        
        $pdo->commit();
        header("Location: reschedule.php?class_id=$selected_class&student_id=$sid&msg=success");
        exit();
    } catch (Exception $e) { 
        if ($pdo->inTransaction()) $pdo->rollBack();
        die("System Error: " . $e->getMessage()); 
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Reschedule Exams</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        body { font-family: 'Segoe UI', Tahoma, sans-serif; background: #f0f2f5; padding: 20px; margin: 0; }
        .container { max-width: 650px; margin: 20px auto; background: white; padding: 25px; border-radius: 12px; box-shadow: 0 4px 20px rgba(0,0,0,0.08); }
        
        .top-nav { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
        .btn-back { text-decoration: none; color: #5f6368; font-weight: 600; font-size: 14px; display: flex; align-items: center; gap: 5px; }
        .btn-back:hover { color: #1a73e8; }

        h2 { color: #1a73e8; margin: 10px 0 25px 0; border-bottom: 2px solid #f0f2f5; padding-bottom: 10px; font-size: 1.5rem; }
        label { font-weight: bold; display: block; margin-bottom: 8px; color: #555; }
        
        select { width: 100%; padding: 12px; margin-bottom: 20px; border: 1px solid #ddd; border-radius: 8px; font-size: 16px; background: #fafafa; box-sizing: border-box; }
        
        .exam-card { background: #fff; border: 1px solid #eee; padding: 15px; border-radius: 10px; display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; gap: 10px; }
        .exam-info { flex: 1; }
        
        .btn-enable { background: #34a853; color: white; border: none; padding: 10px 15px; border-radius: 6px; cursor: pointer; font-weight: bold; white-space: nowrap; }
        .btn-enable:hover { background: #2d8e47; }
        
        .msg { background: #d4edda; color: #155724; padding: 15px; border-radius: 8px; margin-bottom: 20px; text-align: center; font-weight: bold; font-size: 14px; }
        .no-data { text-align: center; color: #999; padding: 20px; border: 2px dashed #eee; border-radius: 10px; }

        /* MOBILE RESPONSIVE STYLES */
        @media (max-width: 480px) {
            body { padding: 10px; }
            .container { padding: 15px; }
            .exam-card { flex-direction: column; align-items: flex-start; }
            .btn-enable { width: 100%; margin-top: 10px; padding: 12px; }
            h2 { font-size: 1.2rem; }
        }
    </style>
</head>
<body>

<div class="container">
    <div class="top-nav">
        <a href="dashboard.php" class="btn-back">
            <i class="fa fa-arrow-left"></i> Dashboard
        </a>
    </div>

    <h2><i class="fa fa-user-clock"></i> Reschedule Exam</h2>

    <?php if(isset($_GET['msg'])): ?>
        <div class="msg"><i class="fa fa-check-circle"></i> Student cleared to retake the exam!</div>
    <?php endif; ?>

    <form method="GET">
        <label>Step 1: Select Class</label>
        <select name="class_id" onchange="this.form.submit()">
            <option value="">-- Choose Class --</option>
            <?php foreach($classes as $c): ?>
                <option value="<?= $c['id'] ?>" <?= $selected_class == $c['id'] ? 'selected' : '' ?>>
                    <?= htmlspecialchars($c['class_name']) ?>
                </option>
            <?php endforeach; ?>
        </select>
    </form>

    <?php if ($selected_class): ?>
    <form method="GET">
        <input type="hidden" name="class_id" value="<?= $selected_class ?>">
        <label>Step 2: Select Student</label>
        <select name="student_id" onchange="this.form.submit()">
            <option value="">-- Choose Student --</option>
            <?php foreach($students as $s): ?>
                <option value="<?= $s['id'] ?>" <?= $selected_student_id == $s['id'] ? 'selected' : '' ?>>
                    <?= htmlspecialchars($s['fullname']) ?> (<?= htmlspecialchars($s['reg_number']) ?>)
                </option>
            <?php endforeach; ?>
        </select>
    </form>
    <?php endif; ?>

    <?php if ($selected_student_id): ?>
        <hr style="margin: 25px 0; border: 0; border-top: 1px solid #eee;">
        <label>Step 3: Enable Retake</label>
        
        <?php if (empty($exams)): ?>
            <div class="no-data">No exams assigned to this class.</div>
        <?php else: ?>
            <?php foreach($exams as $ex): ?>
                <div class="exam-card">
                    <div class="exam-info">
                        <strong><?= htmlspecialchars($ex['exam_title']) ?></strong><br>
                        <small style="color: <?= $ex['attempt_status'] ? '#d93025' : '#188038' ?>">
                            <?= $ex['attempt_status'] ? '<i class="fa fa-exclamation-triangle"></i> Attempted' : '<i class="fa fa-circle-check"></i> Ready' ?>
                        </small>
                    </div>
                    <form method="POST" onsubmit="return confirm('Clearing score will allow the student to start fresh. Continue?')">
                        <input type="hidden" name="sid" value="<?= $selected_student_id ?>">
                        <input type="hidden" name="eid" value="<?= $ex['id'] ?>">
                        <button type="submit" name="do_reschedule" class="btn-enable">
                            Enable Retake
                        </button>
                    </form>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    <?php endif; ?>
</div>

</body>
</html>