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

// Security: Admin Only
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    die("Unauthorized access.");
}

try {
    $pdo->beginTransaction();

    /** * 1. DELETE GHOST EXAMS
     * Any exam that has 0 questions is usually a 'failed start' or a deleted 
     * remnant that is clogging up the Admin Queue.
     */
    $sql1 = "DELETE FROM exams 
             WHERE id NOT IN (SELECT DISTINCT exam_id FROM questions)";
    $stmt1 = $pdo->prepare($sql1);
    $stmt1->execute();
    $deleted_ghosts = $stmt1->rowCount();

    /**
     * 2. SYNC REJECTED STATUS
     * If an exam was marked 'rejected' (string) or 0 (int), 
     * let's move them all to 0 for consistency.
     */
    $sql2 = "UPDATE exams SET status = 0 WHERE status = 'rejected' OR status IS NULL";
    $stmt2 = $pdo->prepare($sql2);
    $stmt2->execute();

    /**
     * 3. RESET PENDING STATUS
     * If an exam was 'draft' (string), move it to 2 (Integer Pending).
     */
    $sql3 = "UPDATE exams SET status = 2 WHERE status = 'draft' OR status = 'pending'";
    $stmt3 = $pdo->prepare($sql3);
    $stmt3->execute();

    $pdo->commit();

    echo "<div style='font-family:sans-serif; padding:20px; border:2px solid #38a169; border-radius:10px;'>";
    echo "<h2 style='color:#38a169;'>Cleanup Successful!</h2>";
    echo "<ul>";
    echo "<li>Orphaned exams (0 questions) removed: <b>$deleted_ghosts</b></li>";
    echo "<li>All statuses synchronized to Integer Logic (0, 1, 2).</li>";
    echo "</ul>";
    echo "<a href='cbt_approval.php'>Go to Approval Queue</a>";
    echo "</div>";

} catch (Exception $e) {
    $pdo->rollBack();
    die("Cleanup Failed: " . $e->getMessage());
}
?>