<?php
// 1. REVEAL ERRORS IF COMPILATION CRASHES
error_reporting(E_ALL);
ini_set('display_errors', 1);

session_start();
require_once 'db.php';

$message = "";
$student_history = [];
$search_matric = isset($_POST['search_matric']) ? trim($_POST['search_matric']) : (isset($_GET['ref_matric']) ? trim($_GET['ref_matric']) : '');

// 2. ACTION: SEARCH FOR STUDENT EXAM HISTORY LOGS
if (!empty($search_matric)) {
    try {
        $stmt = $pdo->prepare("SELECT r.*, s.full_name as name_db, c.course_title 
                             FROM results r 
                             JOIN students s ON r.student_id = s.id
                             JOIN courses c ON r.course_id = c.id
                             WHERE UPPER(r.matric_number) = UPPER(?)
                             ORDER BY r.created_at DESC");
        $stmt->execute([$search_matric]);
        $student_history = $stmt->fetchAll();
        
        if (empty($student_history) && isset($_POST['search_btn'])) {
            $message = "<div class='alert alert-warning'>⚠️ No active exam result records found for Matric Number: '" . htmlspecialchars($search_matric) . "'</div>";
        }
    } catch (\PDOException $e) {
        $message = "<div class='alert alert-danger'>❌ Search Fault: " . htmlspecialchars($e->getMessage()) . "</div>";
    }
}

// 3. ACTION: EXECUTE SECURITY PROFILE RESET (AUTHORISE RETAKE)
if (isset($_POST['reset_exam_attempt'])) {
    $student_id = intval($_POST['res_student_id']);
    $course_id  = intval($_POST['res_course_id']);
    $matric_num = trim($_POST['res_matric']);

    try {
        // Start a safe SQL transaction block to ensure both tables drop data together
        $pdo->beginTransaction();

        // Task A: Delete active grades record log entry parameters
        $delResult = $pdo->prepare("DELETE FROM results WHERE student_id = ? AND course_id = ?");
        $delResult->execute([$student_id, $course_id]);

        // Task B: Delete saved randomized question order mappings and auto-saved mid-exam choices
        $delQuestions = $pdo->prepare("DELETE FROM student_exam_questions WHERE student_id = ? AND course_id = ?");
        $delQuestions->execute([$student_id, $course_id]);

        // Commit transaction records safely
        $pdo->commit();
        
        $message = "<div class='alert alert-success'>✅ Authorization Granted! All previous attempts and grading tracks for <strong>" . htmlspecialchars($matric_num) . "</strong> have been cleared. They can now log in to retake this course exam.</div>";
        
        // Refresh the local history container array mapping values
        $student_history = [];
        $search_matric = "";
    } catch (\PDOException $e) {
        // Rollback change matrix vectors if either delete command encounters errors
        $pdo->rollBack();
        $message = "<div class='alert alert-danger'>❌ Reset Failure Exception: " . htmlspecialchars($e->getMessage()) . "</div>";
    }
}
 
 // bulk wipe of department
 // 1. REVEAL ERRORS IF COMPILATION CRASHES
error_reporting(E_ALL);
ini_set('display_errors', 1);

session_start();
require_once 'db.php';

$message = "";
$departments = [];
$courses = [];

// Fetch unique text-based departments and courses
try {
    // Selects unique department string names directly from your students table
    $deptStmt = $pdo->query("SELECT DISTINCT department FROM students WHERE department IS NOT NULL AND department != '' ORDER BY department ASC");
    $departments = $deptStmt->fetchAll(PDO::FETCH_COLUMN);

    $courseStmt = $pdo->query("SELECT id, course_code, course_title FROM courses ORDER BY course_code ASC");
    $courses = $courseStmt->fetchAll();
} catch (\PDOException $e) {
    $message = "<div class='alert alert-danger'>❌ Initialization Error: " . htmlspecialchars($e->getMessage()) . "</div>";
}

// 2. ACTION: EXECUTE DEPARTMENT-WIDE EXAM RE-AUTHORIZATION BY TEXT STRING
if (isset($_POST['authorize_dept_reset'])) {
    $target_dept = trim($_POST['target_department']);
    $course_id = intval($_POST['target_course_id']);

    if (empty($target_dept) || $course_id <= 0) {
        $message = "<div class='alert alert-warning'>⚠️ Please select both a valid department and a course.</div>";
    } else {
        try {
            $pdo->beginTransaction();

            // Task A: Delete results entries for all students matching the department text string for this course
            $delResults = $pdo->prepare("DELETE r FROM results r 
                                         JOIN students s ON r.student_id = s.id 
                                         WHERE s.department = ? AND r.course_id = ?");
            $delResults->execute([$target_dept, $course_id]);
            $resultsDeleted = $delResults->rowCount();

            // Task B: Delete saved exam progress/question order mappings for those same students
            $delQuestions = $pdo->prepare("DELETE seq FROM student_exam_questions seq 
                                           JOIN students s ON seq.student_id = s.id 
                                           WHERE s.department = ? AND seq.course_id = ?");
            $delQuestions->execute([$target_dept, $course_id]);

            $pdo->commit();

            if ($resultsDeleted > 0) {
                $message = "<div class='alert alert-success'>✅ Department Authorization Granted! Successfully cleared exam locks and records for <strong>$resultsDeleted student(s)</strong> in the <strong>" . htmlspecialchars($target_dept) . "</strong> department.</div>";
            } else {
                $message = "<div class='alert alert-warning'>⚠️ No active exam records were found matching that department name and course combination.</div>";
            }
        } catch (\PDOException $e) {
            $pdo->rollBack();
            $message = "<div class='alert alert-danger'>❌ Bulk Reset Failed: " . htmlspecialchars($e->getMessage()) . "</div>";
        }
    }
}
 
 
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Authorise Student Retake</title>
    <style>
        body { font-family: Arial, sans-serif; background: #fff; padding: 15px; color: #333; margin: 0; }
        .card { background: #fdfdfd; padding: 22px; border: 1px solid #dee2e6; border-radius: 6px; margin-bottom: 20px; border-top: 4px solid #ffc107; }
        .card-red { border-top-color: #dc3545; }
        input { width: 100%; padding: 11px; margin: 8px 0; box-sizing: border-box; border: 1px solid #ccc; border-radius: 4px; font-size: 14px; }
        table { width: 100%; border-collapse: collapse; margin-top: 15px; background: white; }
        th, td { border: 1px solid #dee2e6; padding: 11px; text-align: left; font-size: 13px; } th { background: #e9ecef; }
        .btn { padding: 11px 20px; background: #007bff; color: white; border: none; cursor: pointer; border-radius: 4px; font-weight: bold; font-size: 14px; }
        .btn-search { background: #17a2b8; display: inline-block; width: auto; margin-top: 5px; }
        .btn-reset { background: #dc3545; color: white; border: none; padding: 6px 12px; font-weight: bold; border-radius: 4px; cursor: pointer; font-size: 12px; }
        .btn-reset:hover { background: #bd2130; }
        .alert { padding: 12px; border-radius: 4px; margin-bottom: 18px; font-weight: bold; font-size: 14px; text-align: left; }
        .alert-success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .alert-danger { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
        .alert-warning { background: #fff3cd; color: #856404; border: 1px solid #ffeeba; }
        
        
        
        body { font-family: Arial, sans-serif; background: #fff; padding: 15px; color: #333; margin: 0; }
        .card { background: #fdfdfd; padding: 22px; border: 1px solid #dee2e6; border-radius: 6px; margin-bottom: 20px; border-top: 4px solid #007bff; }
        .card-danger { border-top-color: #dc3545; }
        select { width: 100%; padding: 11px; margin: 8px 0; box-sizing: border-box; border: 1px solid #ccc; border-radius: 4px; font-size: 14px; background: #fff; }
        .btn { padding: 11px 20px; background: #dc3545; color: white; border: none; cursor: pointer; border-radius: 4px; font-weight: bold; font-size: 14px; width: 100%; margin-top: 10px; }
        .btn:hover { background: #bd2130; }
        .alert { padding: 12px; border-radius: 4px; margin-bottom: 18px; font-weight: bold; font-size: 14px; text-align: left; }
        .alert-success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .alert-danger { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
        .alert-warning { background: #fff3cd; color: #856404; border: 1px solid #ffeeba; }
    </style>
</head>
<body>

    <h2 style="color: #333; border-bottom: 1px solid #eee; padding-bottom: 8px; font-size: 20px;">Student Re-Authorization Dashboard Portal</h2>
    
    <!-- Render feedback messages loops -->
    <?php echo $message; ?>

    <!-- STEP A: SEARCH SECTION CONTAINER -->
    <div class="card">
        <h4 style="margin-top:0; color:#e0a800; font-size: 15px;">Search Student Profile to Reset Attempt Locks</h4>
        <form method="POST" action="authorise.php">
            <label style="font-size: 12px; font-weight: bold; color: #555;">Enter Target Candidate Matric Number:</label>
            <input type="text" name="search_matric" value="<?php echo htmlspecialchars($search_matric); ?>" placeholder="e.g., CSC/2026/001" required autocomplete="off">
            <button type="submit" name="search_btn" class="btn btn-search">Lookup Exam History</button>
        </form>
    </div>

    <!-- STEP B: OUTPUT COMPLETED EXAMS TRANSCRIPTS RESULT TABLE -->
    <?php if (!empty($student_history)) { ?>
        <div class="card card-red">
            <h4 style="margin-top:0; color:#dc3545; font-size: 15px;">Active Exam Logs for Candidate: <u><?php echo htmlspecialchars($student_history[0]['student_name']); ?></u></h4>
            <p style="font-size: 12px; color: #666; margin: -10px 0 15px 0;">Clicking the reset authorize button will completely destroy the tracked grading logs for that course row parameters.</p>
            <table>
                <thead>
                    <tr>
                        <th>Course Code</th>
                        <th>Course Title</th>
                        <th>Session</th>
                        <th>Program</th>
                        <th>Score Obtained</th>
                        <th>Status</th>
                        <th>Security Operations</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($student_history as $row) { ?>
                    <tr>
                        <td><span style="background:#eef2f7; padding:2px 5px; font-weight:bold; border-radius:3px; color:#0056b3;"><?php echo htmlspecialchars($row['course_code']); ?></span></td>
                        <td><?php echo htmlspecialchars($row['course_title']); ?></td>
                        <td><?php echo htmlspecialchars($row['session']); ?></td>
                        <td><?php echo htmlspecialchars($row['program']); ?></td>
                        <td><strong><?php echo $row['score']; ?> / <?php echo $row['total_questions']; ?> (<?php echo $row['percentage']; ?>%)</strong></td>
                        <td>
                            <span style="color:white; padding:3px 8px; border-radius:10px; font-size:11px; font-weight:bold; background:<?php echo ($row['exam_status'] === 'Passed') ? '#28a745' : '#dc3545'; ?>;">
                                <?php echo $row['exam_status']; ?>
                            </span>
                        </td>
                        <td>
                            <!-- The reset payload authorization execution trigger -->
                            <form method="POST" action="authorise.php" onsubmit="return confirm('⚠️ CRITICAL RE-AUTHORIZATION SECURITY ACTION:\n\nAre you completely sure you want to delete this result entry and reset the exam session? This action is permanent and cannot be undone!')">
                                <input type="hidden" name="res_student_id" value="<?php echo $row['student_id']; ?>">
                                <input type="hidden" name="res_course_id" value="<?php echo $row['course_id']; ?>">
                                <input type="hidden" name="res_matric" value="<?php echo $row['matric_number']; ?>">
                                <button type="submit" name="reset_exam_attempt" class="btn-reset">🔓 Clear & Authorise Retake</button>
                            </form>
                        </td>
                    </tr>
                    <?php } ?>
                </tbody>
            </table>
        </div>
    <?php } ?>
    
    
   <!-- Stage two of t -->
   
    <h2 style="color: #333; border-bottom: 1px solid #eee; padding-bottom: 8px; font-size: 20px;">Bulk Departmental Re-Authorization Dashboard</h2>
    
    <?php echo $message; ?>

    <!-- STEP A: DEPARTMENT AND COURSE SELECTION CRITERIA -->
    <div class="card card-danger">
        <h4 style="margin-top:0; color:#dc3545; font-size: 15px;">Authorize Department-Wide Exam Retake</h4>
        <p style="font-size: 12px; color: #666; margin: -10px 0 15px 0;">Warning: Executing this command will instantly delete the exam progress and grading entries for EVERY student registered under the selected department name for that specific course.</p>
        
        <form method="POST" action="" onsubmit="return confirm('⚠️ CRITICAL GLOBAL SECURITY RESET:\n\nYou are about to wipe exam records for an ENTIRE department. Are you absolutely certain you want to proceed?')">
            
            <label style="font-size: 12px; font-weight: bold; color: #555;">Select Target Department:</label>
            <select name="target_department" required>
                <option value="">-- Choose Department --</option>
                <?php foreach ($departments as $dept_name) { ?>
                    <option value="<?php echo htmlspecialchars($dept_name); ?>"><?php echo htmlspecialchars($dept_name); ?></option>
                <?php } ?>
            </select>

            <label style="font-size: 12px; font-weight: bold; color: #555; margin-top: 10px; display: block;">Select Target Exam Course:</label>
            <select name="target_course_id" required>
                <option value="">-- Choose Course Exam --</option>
                <?php foreach ($courses as $course) { ?>
                    <option value="<?php echo $course['id']; ?>"><?php echo htmlspecialchars($course['course_code'] . ' - ' . $course['course_title']); ?></option>
                <?php } ?>
            </select>

            <button type="submit" name="authorize_dept_reset" class="btn">Wipe Department Exam Locks & Authorize Retake</button>
        </form>
    </div>

</body>
</html>
