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

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

$action = $_GET['action'] ?? '';
$exam_id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);
$user_id = $_SESSION['user_id'];

if (!$exam_id) { 
    header("Location: manage_exams.php"); 
    exit(); 
}

/**
 * --- SMART DELETE / FORCE CLEANUP ---
 * Handles: 
 * 1. Soft Delete (Archiving) for Active exams to preserve scores.
 * 2. Hard Delete (Force Cleanup) for Drafts/Rejected to fix Integrity Constraint errors.
 */
if ($action == 'delete') {
    try {
        // 1. Verify ownership and check current status
        $stmt = $pdo->prepare("SELECT status FROM exams WHERE id = ? AND teacher_id = ?");
        $stmt->execute([$exam_id, $user_id]);
        $exam = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($exam) {
            $currentStatus = (int)$exam['status'];

            if ($currentStatus === 1) {
                // CASE A: ACTIVE EXAM
                // We don't delete from DB to protect 'exam_results'. 
                // We just hide it from the teacher's 'Manage' list.
                $hide = $pdo->prepare("UPDATE exams SET is_deleted = 1 WHERE id = ? AND teacher_id = ?");
                $hide->execute([$exam_id, $user_id]);
                header("Location: manage_exams.php?msg=archived");
                exit();
            } else {
                // CASE B: DRAFT (2) OR REJECTED (0)
                // We perform a Force Cleanup to avoid "Integrity Constraint Violation"
                $pdo->beginTransaction();

                // Step 1: Clear "Ghost" results that might be blocking the delete
                $clearResults = $pdo->prepare("DELETE FROM exam_results WHERE exam_id = ?");
                $clearResults->execute([$exam_id]);

                // Step 2: Delete questions
                $clearQuestions = $pdo->prepare("DELETE FROM questions WHERE exam_id = ?");
                $clearQuestions->execute([$exam_id]);

                // Step 3: Delete the exam record
                $delExam = $pdo->prepare("DELETE FROM exams WHERE id = ? AND teacher_id = ?");
                $delExam->execute([$exam_id, $user_id]);

                $pdo->commit();
                header("Location: manage_exams.php?msg=deleted");
                exit();
            }
        } else {
            header("Location: manage_exams.php?error=not_found");
            exit();
        }
    } catch (Exception $e) {
        if ($pdo->inTransaction()) { $pdo->rollBack(); }
        error_log("CBT Delete Error: " . $e->getMessage());
        die("System Error: Could not delete exam. Detail: " . $e->getMessage());
    }
}

/**
 * --- DUPLICATE LOGIC ---
 * Copies an existing exam into a new Pending (2) entry.
 */
if ($action == 'duplicate') {
    try {
        $pdo->beginTransaction();

        $stmt = $pdo->prepare("SELECT * FROM exams WHERE id = ? AND teacher_id = ?");
        $stmt->execute([$exam_id, $user_id]);
        $oldExam = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($oldExam) {
            $newTitle = $oldExam['exam_title'] . " (Copy)";
            
            // Insert as Status 2 (Pending/Draft) and is_deleted 0
            $sqlExam = "INSERT INTO exams (teacher_id, class_id, subject_id, exam_title, duration, mark_per_question, status, is_deleted, created_at) 
                        VALUES (:tid, :cid, :sid, :title, :dur, :mpq, 2, 0, NOW())";
            
            $stmtExam = $pdo->prepare($sqlExam);
            $stmtExam->execute([
                ':tid'   => $user_id,
                ':cid'   => $oldExam['class_id'],
                ':sid'   => $oldExam['subject_id'] ?? null,
                ':title' => $newTitle,
                ':dur'   => $oldExam['duration'],
                ':mpq'   => $oldExam['mark_per_question'] ?? 1
            ]);
            
            $newExamId = $pdo->lastInsertId();

            // Duplicate questions
            $sqlQ = "INSERT INTO questions (exam_id, question_text, option_a, option_b, option_c, option_d, correct_option) 
                     SELECT ?, question_text, option_a, option_b, option_c, option_d, correct_option 
                     FROM questions WHERE exam_id = ?";
            $stmtInsertQ = $pdo->prepare($sqlQ);
            $stmtInsertQ->execute([$newExamId, $exam_id]);
            
            $pdo->commit();
            header("Location: manage_exams.php?msg=duplicated");
            exit();
        }
    } catch (Exception $e) {
        if ($pdo->inTransaction()) { $pdo->rollBack(); }
        die("Duplicate Error: " . $e->getMessage());
    }
}

// Default redirect if no valid action is found
header("Location: manage_exams.php");
exit();