<?php
require_once('../source/session.php');
require_once('../source/error.php');
require_once('../source/dbconfig.php');
require_once('../source/function.php');
require_once('../source/restrict_admin.php');

// Get admin name from session
$adminName = $_SESSION['SESS_FULLNAME_ADMIN'] ?? 'Administrator';

// School information
$schoolName = "Henzy Royal International School";
$schoolAddress = "No 17 Amadi Street, Amakohia, Uratta Owerri Imo State Nigeria";
$supportPhone = "+234 803 292 9756";
$supportEmail = "support@hris.com.ng";

// Session timeout settings (in minutes)
define('WARNING_TIME', 15);
define('TIMEOUT_TIME', 10);

// Update session last activity time
if (!isset($_SESSION['last_activity'])) {
    $_SESSION['last_activity'] = time();
    $_SESSION['warning_shown'] = false;
    $_SESSION['timeout_triggered'] = false;
}

// Fetch available data for dropdowns
$stmt_classes = $DBH->query("SELECT DISTINCT class FROM tbl_cbt_results ORDER BY class");
$classes = $stmt_classes->fetchAll(PDO::FETCH_COLUMN);

$stmt_subjects = $DBH->query("SELECT DISTINCT subject FROM tbl_cbt_results ORDER BY subject");
$subjects = $stmt_subjects->fetchAll(PDO::FETCH_COLUMN);

$stmt_sessions = $DBH->query("SELECT DISTINCT session FROM tbl_cbt_results ORDER BY session DESC");
$sessions = $stmt_sessions->fetchAll(PDO::FETCH_COLUMN);

$terms = ['1st Term', '2nd Term', '3rd Term'];

// Handle search form submission
$search_results = [];
$search_type = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['keep_session_alive'])) {
        $_SESSION['last_activity'] = time();
        $_SESSION['warning_shown'] = false;
        $_SESSION['timeout_triggered'] = false;
        echo json_encode(['success' => true]);
        exit();
    }
    
    $search_type = $_POST['search_type'] ?? '';
    
    try {
        // Function to calculate Actual 2nd SUM Score based on class type
        function calculateSecondSumScore($cbtScore, $class) {
            if (stripos($class, 'GRADE') !== false) {
                return round($cbtScore * 0.3, 2);
            } elseif (stripos($class, 'JSS') !== false || stripos($class, 'SSS') !== false) {
                return round($cbtScore * 0.25, 2);
            } else {
                return round($cbtScore * 0.25, 2);
            }
        }
        
        // Function to get grade based on total score
        function getGrade($score) {
            if ($score >= 80) return ['A', 'Excellent'];
            if ($score >= 70) return ['B', 'Very Good'];
            if ($score >= 60) return ['C', 'Good'];
            if ($score >= 50) return ['D', 'Fair'];
            if ($score >= 40) return ['E', 'Pass'];
            return ['F', 'Fail'];
        }
        
        if ($search_type === 'student') {
            $registration_no = $_POST['registration_no'] ?? '';
            $class = $_POST['class'] ?? '';
            $subject = $_POST['subject'] ?? '';
            $term = $_POST['term'] ?? '';
            $session = $_POST['session'] ?? '';
            
            $sql = "SELECT c.*, u.fullname 
                    FROM tbl_cbt_results c 
                    LEFT JOIN tbl_user u ON c.registration_no = u.registration_no 
                    WHERE 1=1";
            $params = [];
            
            if (!empty($registration_no)) {
                $sql .= " AND c.registration_no LIKE :registration_no";
                $params[':registration_no'] = "%$registration_no%";
            }
            if (!empty($class)) {
                $sql .= " AND c.class = :class";
                $params[':class'] = $class;
            }
            if (!empty($subject)) {
                $sql .= " AND c.subject = :subject";
                $params[':subject'] = $subject;
            }
            if (!empty($term)) {
                $sql .= " AND c.term = :term";
                $params[':term'] = $term;
            }
            if (!empty($session)) {
                $sql .= " AND c.session = :session";
                $params[':session'] = $session;
            }
            
            $sql .= " ORDER BY c.date_taken DESC";
            
            $stmt = $DBH->prepare($sql);
            $stmt->execute($params);
            $search_results = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            foreach ($search_results as &$result) {
                $result['second_sum_score'] = calculateSecondSumScore($result['score'], $result['class']);
            }
            
        } elseif ($search_type === 'class') {
            $class = $_POST['class'] ?? '';
            $subject = $_POST['subject'] ?? '';
            $term = $_POST['term'] ?? '';
            $session = $_POST['session'] ?? '';
            
            $sql = "SELECT c.*, u.fullname 
                    FROM tbl_cbt_results c 
                    LEFT JOIN tbl_user u ON c.registration_no = u.registration_no 
                    WHERE 1=1";
            $params = [];
            
            if (!empty($class)) {
                $sql .= " AND c.class = :class";
                $params[':class'] = $class;
            }
            if (!empty($subject)) {
                $sql .= " AND c.subject = :subject";
                $params[':subject'] = $subject;
            }
            if (!empty($term)) {
                $sql .= " AND c.term = :term";
                $params[':term'] = $term;
            }
            if (!empty($session)) {
                $sql .= " AND c.session = :session";
                $params[':session'] = $session;
            }
            
            $sql .= " ORDER BY c.subject, c.registration_no";
            
            $stmt = $DBH->prepare($sql);
            $stmt->execute($params);
            $search_results = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            foreach ($search_results as &$result) {
                $result['second_sum_score'] = calculateSecondSumScore($result['score'], $result['class']);
            }
            
        } elseif ($search_type === 'subject') {
            $subject = $_POST['subject'] ?? '';
            $class = $_POST['class'] ?? '';
            $term = $_POST['term'] ?? '';
            $session = $_POST['session'] ?? '';
            
            $sql = "SELECT c.*, u.fullname 
                    FROM tbl_cbt_results c 
                    LEFT JOIN tbl_user u ON c.registration_no = u.registration_no 
                    WHERE 1=1";
            $params = [];
            
            if (!empty($subject)) {
                $sql .= " AND c.subject = :subject";
                $params[':subject'] = $subject;
            }
            if (!empty($class)) {
                $sql .= " AND c.class = :class";
                $params[':class'] = $class;
            }
            if (!empty($term)) {
                $sql .= " AND c.term = :term";
                $params[':term'] = $term;
            }
            if (!empty($session)) {
                $sql .= " AND c.session = :session";
                $params[':session'] = $session;
            }
            
            $sql .= " ORDER BY c.class, c.registration_no";
            
            $stmt = $DBH->prepare($sql);
            $stmt->execute($params);
            $search_results = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            foreach ($search_results as &$result) {
                $result['second_sum_score'] = calculateSecondSumScore($result['score'], $result['class']);
            }
        }
    } catch (PDOException $e) {
        $_SESSION['error'] = "Database error: " . $e->getMessage();
    }
}

// Calculate statistics for class/subject searches
$statistics = [];
if (!empty($search_results) && in_array($search_type, ['class', 'subject'])) {
    $total_students = count(array_unique(array_column($search_results, 'registration_no')));
    
    $scores = array_filter(array_column($search_results, 'total_score'));
    if (empty($scores)) {
        $scores = array_column($search_results, 'score');
    }
    $average_score = array_sum($scores) / count($scores);
    $highest_score = max($scores);
    $lowest_score = min($scores);
    
    $statistics = [
        'total_students' => $total_students,
        'average_score' => round($average_score, 2),
        'highest_score' => $highest_score,
        'lowest_score' => $lowest_score,
        'total_records' => count($search_results)
    ];
}

// Check session timeout status
$time_elapsed = time() - $_SESSION['last_activity'];
$warning_time_seconds = WARNING_TIME * 60;
$timeout_time_seconds = TIMEOUT_TIME * 60;

$show_warning = false;
$time_until_timeout = 0;

if ($time_elapsed >= $warning_time_seconds && !$_SESSION['warning_shown'] && !$_SESSION['timeout_triggered']) {
    $show_warning = true;
    $_SESSION['warning_shown'] = true;
    $time_until_timeout = $timeout_time_seconds - ($time_elapsed - $warning_time_seconds);
} elseif ($time_elapsed >= ($warning_time_seconds + $timeout_time_seconds) && !$_SESSION['timeout_triggered']) {
    $_SESSION['timeout_triggered'] = true;
    session_destroy();
    header("Location: ../logout.php?timeout=1");
    exit();
}

// Get error/success messages
$error_message = $_SESSION['error'] ?? '';
$success_message = $_SESSION['success'] ?? '';
unset($_SESSION['error'], $_SESSION['success']);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>View CBT Results - Henzy Royal International School CBT</title>
    <link rel="icon" type="image/png" href="../coll_logo.png">
    
    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <!-- Google Fonts - Poppins -->
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    
    <!-- Select2 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <link href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" rel="stylesheet" />
    
    <!-- DataTables CSS -->
    <link href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/buttons/2.3.6/css/buttons.bootstrap5.min.css" rel="stylesheet">
    
    <!-- Custom CSS -->
    <style>
        :root {
            --primary-blue: #1a4b8c;
            --secondary-gold: #FFD700;
            --dark-blue: #0f2b4f;
            --light-blue: #4a7db5;
            --light-gold: #FFF1B8;
            --bg-light: #f5f9ff;
            --success-green: #28a745;
            --warning-orange: #fd7e14;
            --danger-red: #dc3545;
            --info-teal: #17a2b8;
        }
        
        body {
            font-family: 'Poppins', sans-serif;
            background-color: var(--bg-light);
            color: #333;
            padding-bottom: 60px;
        }
        
        /* Header Styles */
        .admin-header {
            background: linear-gradient(135deg, var(--primary-blue), var(--dark-blue));
            box-shadow: 0 2px 15px rgba(26, 75, 140, 0.3);
            border-bottom: 3px solid var(--secondary-gold);
            color: white;
            margin-bottom: 2rem;
        }
        
        .logo-container {
            background: white;
            border-radius: 10px;
            padding: 5px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.2);
        }
        
        .img-fluid {
            width: 60px;
            height: 60px;
            object-fit: cover;
            border-radius: 8px;
        }
        
        .header-title h1 {
            font-weight: 700;
            margin-bottom: 0;
            font-size: 1.5rem;
            color: white;
        }
        
        .header-title small {
            color: var(--secondary-gold);
            font-weight: 500;
        }
        
        /* Dropdown Styles */
        .admin-dropdown {
            background: rgba(255, 255, 255, 0.1);
            border: 1px solid rgba(255, 215, 0, 0.3);
            color: white;
            padding: 0.5rem 1rem;
            border-radius: 50px;
            transition: all 0.3s ease;
        }
        
        .admin-dropdown:hover {
            background: rgba(255, 215, 0, 0.2);
            border-color: var(--secondary-gold);
        }
        
        .dropdown-menu {
            border: 1px solid var(--secondary-gold);
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }
        
        .dropdown-item:hover {
            background-color: var(--light-gold);
            color: var(--dark-blue);
        }
        
        .dropdown-item i {
            color: var(--primary-blue);
        }
        
        /* Card Styles */
        .action-card {
            border: none;
            border-radius: 15px;
            box-shadow: 0 4px 20px rgba(26, 75, 140, 0.1);
            transition: all 0.3s ease;
            background: white;
            border: 1px solid rgba(255, 215, 0, 0.2);
            overflow: hidden;
            width: 100%;
        }
        
        .action-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 25px rgba(26, 75, 140, 0.2);
            border-color: var(--secondary-gold);
        }
        
        .card-header {
            background: linear-gradient(135deg, var(--light-gold), #ffffff);
            border-bottom: 2px solid var(--secondary-gold);
            padding: 1.5rem;
        }
        
        .card-header h3 {
            color: var(--dark-blue);
            font-weight: 700;
            margin: 0;
        }
        
        .card-header i {
            color: var(--secondary-gold);
        }
        
        .card-body {
            padding: 2rem;
        }
        
        /* Form Styles */
        .form-label {
            font-weight: 600;
            color: var(--dark-blue);
            margin-bottom: 0.5rem;
        }
        
        .form-label i {
            color: var(--secondary-gold);
            margin-right: 0.5rem;
        }
        
        .form-control, .form-select {
            border: 1px solid #ced4da;
            border-radius: 10px;
            padding: 0.75rem 1rem;
            font-size: 0.95rem;
            transition: all 0.3s ease;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: var(--secondary-gold);
            box-shadow: 0 0 0 0.25rem rgba(255, 215, 0, 0.25);
            outline: none;
        }
        
        /* Buttons */
        .btn-primary {
            background: linear-gradient(135deg, var(--primary-blue), var(--dark-blue));
            border: none;
            color: white;
            padding: 0.75rem 1.5rem;
            border-radius: 50px;
            font-weight: 500;
            transition: all 0.3s ease;
        }
        
        .btn-primary:hover {
            background: linear-gradient(135deg, var(--dark-blue), #0a1f3a);
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(26, 75, 140, 0.3);
        }
        
        .btn-success {
            background: linear-gradient(135deg, #28a745, #218838);
            border: none;
            color: white;
            padding: 0.75rem 1.5rem;
            border-radius: 50px;
            font-weight: 500;
        }
        
        .btn-success:hover {
            background: linear-gradient(135deg, #218838, #1e7e34);
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(40, 167, 69, 0.3);
        }
        
        .btn-warning {
            background: linear-gradient(135deg, #ffc107, #e0a800);
            border: none;
            color: var(--dark-blue);
            padding: 0.75rem 1.5rem;
            border-radius: 50px;
            font-weight: 500;
        }
        
        .btn-warning:hover {
            background: linear-gradient(135deg, #e0a800, #c69500);
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(255, 193, 7, 0.3);
        }
        
        .btn-info {
            background: linear-gradient(135deg, #17a2b8, #138496);
            border: none;
            color: white;
            padding: 0.75rem 1.5rem;
            border-radius: 50px;
            font-weight: 500;
        }
        
        .btn-info:hover {
            background: linear-gradient(135deg, #138496, #117a8b);
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(23, 162, 184, 0.3);
        }
        
        .btn-outline-secondary {
            border: 2px solid #6c757d;
            color: #6c757d;
            background: transparent;
            padding: 0.75rem 1.5rem;
            border-radius: 50px;
            font-weight: 500;
            transition: all 0.3s ease;
        }
        
        .btn-outline-secondary:hover {
            background: #6c757d;
            color: white;
            transform: translateY(-2px);
        }
        
        .btn-outline-primary {
            border: 2px solid var(--primary-blue);
            color: var(--primary-blue);
            background: transparent;
            padding: 0.4rem 0.8rem;
            border-radius: 50px;
            font-weight: 500;
            transition: all 0.3s ease;
        }
        
        .btn-outline-primary:hover {
            background: linear-gradient(135deg, var(--primary-blue), var(--dark-blue));
            color: white;
            transform: translateY(-2px);
        }
        
        .btn-sm {
            padding: 0.4rem 0.8rem;
            font-size: 0.85rem;
        }
        
        /* Modal Styles */
        .modal-content {
            border: none;
            border-radius: 15px;
            overflow: hidden;
            border: 2px solid var(--secondary-gold);
        }
        
        .modal-header {
            background: linear-gradient(135deg, var(--primary-blue), var(--dark-blue));
            color: white;
            border-bottom: 2px solid var(--secondary-gold);
        }
        
        .modal-header .btn-close {
            filter: brightness(0) invert(1);
        }
        
        .modal-footer {
            border-top: 1px solid var(--light-gold);
            padding: 1.5rem;
        }
        
        .modal-body {
            padding: 2rem;
        }
        
        /* Nav Pills */
        .nav-pills .nav-link {
            color: var(--primary-blue);
            border-radius: 50px;
            padding: 0.75rem 1.5rem;
            margin-right: 0.5rem;
            font-weight: 500;
            transition: all 0.3s ease;
        }
        
        .nav-pills .nav-link:hover {
            background: var(--light-gold);
            transform: translateY(-2px);
        }
        
        .nav-pills .nav-link.active {
            background: linear-gradient(135deg, var(--primary-blue), var(--dark-blue));
            color: white;
        }
        
        .nav-pills .nav-link i {
            margin-right: 0.5rem;
        }
        
        /* Search Section */
        .search-section {
            background: linear-gradient(135deg, #f8f9fa, #ffffff);
            border-radius: 15px;
            padding: 2rem;
            margin-bottom: 2rem;
            border-left: 4px solid var(--secondary-gold);
        }
        
        .search-section h5 {
            color: var(--dark-blue);
            font-weight: 600;
            margin-bottom: 1.5rem;
        }
        
        .search-section h5 i {
            color: var(--secondary-gold);
        }
        
        /* Stat Cards */
        .stat-card {
            background: linear-gradient(135deg, var(--primary-blue), var(--dark-blue));
            color: white;
            border-radius: 10px;
            padding: 1.5rem;
            margin-bottom: 1rem;
            transition: all 0.3s ease;
            border-left: 3px solid var(--secondary-gold);
        }
        
        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 25px rgba(26, 75, 140, 0.3);
        }
        
        .stat-card h6 {
            font-size: 0.9rem;
            text-transform: uppercase;
            letter-spacing: 1px;
            margin-bottom: 0.5rem;
            color: var(--secondary-gold);
        }
        
        .stat-card h3 {
            font-size: 2rem;
            font-weight: 700;
            margin: 0;
        }
        
        /* Score Badges */
        .badge {
            padding: 0.5rem 1rem;
            font-size: 0.85rem;
            font-weight: 500;
            border-radius: 50px;
        }
        
        .cbt-score {
            background: linear-gradient(135deg, #28a745, #218838);
            color: white;
        }
        
        .second-sum-score {
            background: linear-gradient(135deg, #17a2b8, #138496);
            color: white;
        }
        
        .subjective-score {
            background: linear-gradient(135deg, #6610f2, #520dc2);
            color: white;
        }
        
        .theory-score {
            background: linear-gradient(135deg, #fd7e14, #e56b08);
            color: white;
        }
        
        .practical-score {
            background: linear-gradient(135deg, #6c757d, #545b62);
            color: white;
        }
        
        .total-score {
            background: linear-gradient(135deg, #ffc107, #e0a800);
            color: var(--dark-blue);
            font-weight: 600;
        }
        
        /* Grade Badges */
        .grade-A { background: linear-gradient(135deg, #28a745, #218838); color: white; }
        .grade-B { background: linear-gradient(135deg, #17a2b8, #138496); color: white; }
        .grade-C { background: linear-gradient(135deg, #ffc107, #e0a800); color: var(--dark-blue); }
        .grade-D { background: linear-gradient(135deg, #fd7e14, #e56b08); color: white; }
        .grade-E { background: linear-gradient(135deg, #dc3545, #c82333); color: white; }
        .grade-F { background: linear-gradient(135deg, #6c757d, #545b62); color: white; }
        
        /* Table Styles */
        .table {
            border-radius: 10px;
            overflow: hidden;
        }
        
        .table thead th {
            background: linear-gradient(135deg, var(--primary-blue), var(--dark-blue));
            color: white;
            font-weight: 500;
            border: none;
            padding: 1rem;
            font-size: 0.85rem;
            white-space: nowrap;
        }
        
        .table tbody tr {
            transition: all 0.3s ease;
        }
        
        .table tbody tr:hover {
            background-color: var(--light-gold);
            transform: scale(1.01);
            box-shadow: 0 2px 10px rgba(255, 215, 0, 0.2);
        }
        
        .table td {
            padding: 1rem;
            vertical-align: middle;
            border-bottom: 1px solid rgba(255, 215, 0, 0.1);
            font-size: 0.85rem;
            white-space: nowrap;
        }
        
        .badge.bg-info {
            background: linear-gradient(135deg, #17a2b8, #138496) !important;
            color: white;
        }
        
        .badge.bg-warning {
            background: linear-gradient(135deg, #ffc107, #e0a800) !important;
            color: var(--dark-blue);
        }
        
        .badge.bg-secondary {
            background: linear-gradient(135deg, #6c757d, #545b62) !important;
            color: white;
        }
        
        /* Alert Styles */
        .alert {
            border-radius: 10px;
            border: none;
            padding: 1rem;
            margin-bottom: 1.5rem;
            border-left: 4px solid transparent;
        }
        
        .alert-success {
            background: linear-gradient(135deg, #d4edda, #c3e6cb);
            color: #155724;
            border-left-color: #28a745;
        }
        
        .alert-danger {
            background: linear-gradient(135deg, #f8d7da, #f5c6cb);
            color: #721c24;
            border-left-color: #dc3545;
        }
        
        .alert-warning {
            background: linear-gradient(135deg, #fff3cd, #ffeaa7);
            color: #856404;
            border-left-color: #ffc107;
        }
        
        .alert-info {
            background: linear-gradient(135deg, #d1ecf1, #bee5eb);
            color: #0c5460;
            border-left-color: #17a2b8;
        }
        
        .alert i {
            margin-right: 0.5rem;
        }
        
        /* Empty State */
        .empty-state {
            background: linear-gradient(135deg, #f8f9fa, #ffffff);
            border-radius: 15px;
            padding: 3rem;
            border: 2px dashed var(--secondary-gold);
        }
        
        .empty-state i {
            color: var(--secondary-gold);
            opacity: 0.5;
        }
        
        .empty-state h4 {
            color: var(--dark-blue);
        }
        
        /* Footer */
        .footer {
            background: linear-gradient(135deg, var(--dark-blue), var(--primary-blue));
            color: white;
            padding: 1.5rem 0;
            margin-top: 3rem;
            border-top: 3px solid var(--secondary-gold);
        }
        
        .footer a {
            color: var(--secondary-gold);
            text-decoration: none;
            font-weight: 500;
        }
        
        .footer a:hover {
            text-decoration: underline;
        }
        
        .footer img {
            height: 25px;
            margin-left: 5px;
            filter: brightness(0) invert(1);
        }
        
        /* DataTables Customization */
        .dataTables_wrapper .dataTables_length select,
        .dataTables_wrapper .dataTables_filter input {
            border-radius: 50px;
            padding: 0.5rem 1rem;
            border: 1px solid #ced4da;
        }
        
        .dataTables_wrapper .dataTables_length select:focus,
        .dataTables_wrapper .dataTables_filter input:focus {
            border-color: var(--secondary-gold);
            box-shadow: 0 0 0 0.25rem rgba(255, 215, 0, 0.25);
            outline: none;
        }
        
        .dataTables_wrapper .dataTables_paginate .paginate_button {
            border-radius: 50px !important;
            margin: 0 2px;
        }
        
        .dataTables_wrapper .dataTables_paginate .paginate_button.current {
            background: linear-gradient(135deg, var(--primary-blue), var(--dark-blue)) !important;
            color: white !important;
            border: none;
        }
        
        /* Responsive */
        @media (max-width: 768px) {
            .header-title h1 {
                font-size: 1.2rem;
            }
            
            .admin-dropdown {
                padding: 0.4rem 0.8rem;
                font-size: 0.9rem;
            }
            
            .card-header h3 {
                font-size: 1.3rem;
            }
            
            .card-body {
                padding: 1.5rem;
            }
            
            .btn {
                width: 100%;
                margin-bottom: 0.5rem;
            }
            
            .nav-pills .nav-link {
                width: 100%;
                margin-bottom: 0.5rem;
            }
            
            .stat-card {
                margin-bottom: 1rem;
            }
        }
    </style>
</head>
<body>
    <!-- Session Timeout Modal -->
    <div class="modal fade" id="sessionTimeoutModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-clock me-2" style="color: var(--secondary-gold);"></i>
                        Session Timeout Warning
                    </h5>
                </div>
                <div class="modal-body text-center py-4">
                    <i class="fas fa-exclamation-triangle fa-3x mb-3" style="color: var(--secondary-gold);"></i>
                    <h4 class="mb-3">Your session is about to expire!</h4>
                    <p class="mb-2">You have been inactive for <strong><?= WARNING_TIME ?> minutes</strong>.</p>
                    <p class="mb-4">Your session will expire in <strong><span id="timeoutTimer"><?= TIMEOUT_TIME ?>:00</span> minutes</strong> if you don't respond.</p>
                    <div class="progress mb-3" style="height: 10px;">
                        <div id="timeoutProgress" class="progress-bar progress-bar-striped progress-bar-animated" 
                             style="width: 100%; background: linear-gradient(135deg, var(--primary-blue), var(--dark-blue));"></div>
                    </div>
                </div>
                <div class="modal-footer justify-content-center">
                    <button type="button" class="btn btn-primary" onclick="keepSessionAlive()" id="keepAliveBtn">
                        <i class="fas fa-check-circle me-2"></i> I'm Still Here - Don't Time Out
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Session Expired Modal -->
    <div class="modal fade" id="sessionExpiredModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header bg-danger text-white">
                    <h5 class="modal-title">
                        <i class="fas fa-exclamation-circle me-2"></i>
                        Session Expired
                    </h5>
                </div>
                <div class="modal-body text-center py-4">
                    <i class="fas fa-hourglass-end fa-3x mb-3 text-danger"></i>
                    <h4 class="mb-3">Your session has expired!</h4>
                    <p class="mb-4">You have been logged out due to inactivity.</p>
                </div>
                <div class="modal-footer justify-content-center">
                    <a href="../login.php" class="btn btn-primary">
                        <i class="fas fa-sign-in-alt me-2"></i> Login Again
                    </a>
                </div>
            </div>
        </div>
    </div>

    <!-- Result Details Modal -->
    <div class="modal fade" id="resultModal" tabindex="-1" aria-labelledby="resultModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="resultModalLabel">
                        <i class="fas fa-file-alt me-2" style="color: var(--secondary-gold);"></i>
                        Result Details
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body" id="resultDetails">
                    <div class="text-center py-5">
                        <div class="spinner-border text-primary" style="width: 3rem; height: 3rem;" role="status">
                            <span class="visually-hidden">Loading...</span>
                        </div>
                        <p class="mt-3 text-muted">Loading result details...</p>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">
                        <i class="fas fa-times me-2"></i> Close
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Header -->
    <header class="admin-header py-3">
        <div class="container">
            <div class="d-flex justify-content-between align-items-center">
                <div class="d-flex align-items-center">
                    <div class="logo-container me-3">
                        <img src="../coll_logo.png" alt="Henzy Royal International School Logo" class="img-fluid">
                    </div>
                    <div class="header-title">
                        <h1 class="h4 mb-0">HENZY ROYAL INT'L SCHOOL</h1>
                        <small>CBT - View Results</small>
                    </div>
                </div>
                <div class="dropdown">
                    <button class="btn admin-dropdown dropdown-toggle" type="button" id="adminDropdown" data-bs-toggle="dropdown" aria-expanded="false">
                        <i class="fas fa-user-circle me-1"></i> <?= htmlspecialchars($adminName) ?>
                    </button>
                    <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="adminDropdown">
                        <li><a class="dropdown-item" href="cbt_admin_home.php"><i class="fas fa-tachometer-alt me-2"></i> CBT Dashboard</a></li>
                        <li><a class="dropdown-item" href="upload_other_scores.php"><i class="fas fa-upload me-2"></i> Upload Other Scores</a></li>
                        <li><hr class="dropdown-divider"></li>
                        <li><a class="dropdown-item" href="../main.php"><i class="fas fa-home me-2"></i> Main Dashboard</a></li>
                        <li><hr class="dropdown-divider"></li>
                        <li><a class="dropdown-item" href="../logout.php"><i class="fas fa-sign-out-alt me-2"></i> Logout</a></li>
                    </ul>
                </div>
            </div>
        </div>
    </header>

    <!-- Main Content -->
    <div class="container-fluid py-4">
        <!-- Breadcrumb -->
        <nav aria-label="breadcrumb" class="mb-4">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="cbt_admin_home.php" class="text-decoration-none" style="color: var(--primary-blue);">CBT Dashboard</a></li>
                <li class="breadcrumb-item active" aria-current="page">View Results</li>
            </ol>
        </nav>

        <div class="row">
            <div class="col-12">
                <!-- Action Buttons -->
                <div class="row mb-4">
                    <div class="col-12">
                        <a href="cbt_admin_home.php" class="btn btn-outline-secondary">
                            <i class="fas fa-arrow-left me-2"></i> Back to Dashboard
                        </a>
                        <a href="upload_other_scores.php" class="btn btn-success ms-2">
                            <i class="fas fa-upload me-2"></i> Upload Other Scores
                        </a>
                    </div>
                </div>

                <div class="card action-card">
                    <div class="card-header">
                        <h3 class="mb-0"><i class="fas fa-chart-line me-2"></i> View CBT Results</h3>
                    </div>
                    <div class="card-body">
                        <?php if ($error_message): ?>
                            <div class="alert alert-danger alert-dismissible fade show">
                                <i class="fas fa-exclamation-circle me-2"></i> <?= $error_message ?>
                                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                            </div>
                        <?php endif; ?>
                        
                        <?php if ($success_message): ?>
                            <div class="alert alert-success alert-dismissible fade show">
                                <i class="fas fa-check-circle me-2"></i> <?= $success_message ?>
                                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                            </div>
                        <?php endif; ?>

                        <!-- Search Tabs -->
                        <ul class="nav nav-pills mb-4" id="searchTabs" role="tablist">
                            <li class="nav-item" role="presentation">
                                <button class="nav-link active" id="student-tab" data-bs-toggle="pill" data-bs-target="#student-search" type="button" role="tab">
                                    <i class="fas fa-user-graduate me-2"></i> Search by Student
                                </button>
                            </li>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link" id="class-tab" data-bs-toggle="pill" data-bs-target="#class-search" type="button" role="tab">
                                    <i class="fas fa-users me-2"></i> Search by Class
                                </button>
                            </li>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link" id="subject-tab" data-bs-toggle="pill" data-bs-target="#subject-search" type="button" role="tab">
                                    <i class="fas fa-book me-2"></i> Search by Subject
                                </button>
                            </li>
                        </ul>

                        <div class="tab-content" id="searchTabsContent">
                            <!-- Student Search -->
                            <div class="tab-pane fade show active" id="student-search" role="tabpanel">
                                <div class="search-section">
                                    <h5><i class="fas fa-user-graduate me-2"></i> Search Student Results</h5>
                                    <form method="POST" id="studentSearchForm">
                                        <input type="hidden" name="search_type" value="student">
                                        <div class="row g-3">
                                            <div class="col-md-4">
                                                <label for="registration_no" class="form-label">
                                                    <i class="fas fa-id-card me-1"></i> Student Admission Number
                                                </label>
                                                <input type="text" name="registration_no" id="registration_no" class="form-control" 
                                                       placeholder="Enter admission number" value="<?= $_POST['registration_no'] ?? '' ?>">
                                            </div>
                                            <div class="col-md-2">
                                                <label for="class_student" class="form-label">
                                                    <i class="fas fa-users me-1"></i> Class (Optional)
                                                </label>
                                                <select name="class" id="class_student" class="form-select select2">
                                                    <option value="">-- All Classes --</option>
                                                    <?php foreach ($classes as $class): ?>
                                                        <option value="<?= htmlspecialchars($class) ?>" <?= (isset($_POST['class']) && $_POST['class'] == $class) ? 'selected' : '' ?>>
                                                            <?= htmlspecialchars($class) ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                            <div class="col-md-2">
                                                <label for="subject_student" class="form-label">
                                                    <i class="fas fa-book me-1"></i> Subject (Optional)
                                                </label>
                                                <select name="subject" id="subject_student" class="form-select select2">
                                                    <option value="">-- All Subjects --</option>
                                                    <?php foreach ($subjects as $subject): ?>
                                                        <option value="<?= htmlspecialchars($subject) ?>" <?= (isset($_POST['subject']) && $_POST['subject'] == $subject) ? 'selected' : '' ?>>
                                                            <?= htmlspecialchars($subject) ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                            <div class="col-md-2">
                                                <label for="term_student" class="form-label">
                                                    <i class="fas fa-calendar-alt me-1"></i> Term (Optional)
                                                </label>
                                                <select name="term" id="term_student" class="form-select select2">
                                                    <option value="">-- All Terms --</option>
                                                    <?php foreach ($terms as $term): ?>
                                                        <option value="<?= $term ?>" <?= (isset($_POST['term']) && $_POST['term'] == $term) ? 'selected' : '' ?>>
                                                            <?= $term ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                            <div class="col-md-2">
                                                <label for="session_student" class="form-label">
                                                    <i class="fas fa-calendar me-1"></i> Session (Optional)
                                                </label>
                                                <select name="session" id="session_student" class="form-select select2">
                                                    <option value="">-- All Sessions --</option>
                                                    <?php foreach ($sessions as $session): ?>
                                                        <option value="<?= htmlspecialchars($session) ?>" <?= (isset($_POST['session']) && $_POST['session'] == $session) ? 'selected' : '' ?>>
                                                            <?= htmlspecialchars($session) ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                        </div>
                                        <div class="text-center mt-4">
                                            <button type="submit" class="btn btn-primary">
                                                <i class="fas fa-search me-2"></i> Search Student Results
                                            </button>
                                            <button type="button" class="btn btn-outline-secondary" onclick="resetForm('student')">
                                                <i class="fas fa-redo me-2"></i> Reset
                                            </button>
                                        </div>
                                    </form>
                                </div>
                            </div>

                            <!-- Class Search -->
                            <div class="tab-pane fade" id="class-search" role="tabpanel">
                                <div class="search-section">
                                    <h5><i class="fas fa-users me-2"></i> Search Class Results</h5>
                                    <form method="POST" id="classSearchForm">
                                        <input type="hidden" name="search_type" value="class">
                                        <div class="row g-3">
                                            <div class="col-md-3">
                                                <label for="class_class" class="form-label">
                                                    <i class="fas fa-users me-1"></i> Class
                                                </label>
                                                <select name="class" id="class_class" class="form-select select2" required>
                                                    <option value="">-- Select Class --</option>
                                                    <?php foreach ($classes as $class): ?>
                                                        <option value="<?= htmlspecialchars($class) ?>" <?= (isset($_POST['class']) && $_POST['class'] == $class) ? 'selected' : '' ?>>
                                                            <?= htmlspecialchars($class) ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                            <div class="col-md-3">
                                                <label for="subject_class" class="form-label">
                                                    <i class="fas fa-book me-1"></i> Subject (Optional)
                                                </label>
                                                <select name="subject" id="subject_class" class="form-select select2">
                                                    <option value="">-- All Subjects --</option>
                                                    <?php foreach ($subjects as $subject): ?>
                                                        <option value="<?= htmlspecialchars($subject) ?>" <?= (isset($_POST['subject']) && $_POST['subject'] == $subject) ? 'selected' : '' ?>>
                                                            <?= htmlspecialchars($subject) ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                            <div class="col-md-2">
                                                <label for="term_class" class="form-label">
                                                    <i class="fas fa-calendar-alt me-1"></i> Term
                                                </label>
                                                <select name="term" id="term_class" class="form-select select2" required>
                                                    <option value="">-- Select Term --</option>
                                                    <?php foreach ($terms as $term): ?>
                                                        <option value="<?= $term ?>" <?= (isset($_POST['term']) && $_POST['term'] == $term) ? 'selected' : '' ?>>
                                                            <?= $term ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                            <div class="col-md-2">
                                                <label for="session_class" class="form-label">
                                                    <i class="fas fa-calendar me-1"></i> Session
                                                </label>
                                                <select name="session" id="session_class" class="form-select select2" required>
                                                    <option value="">-- Select Session --</option>
                                                    <?php foreach ($sessions as $session): ?>
                                                        <option value="<?= htmlspecialchars($session) ?>" <?= (isset($_POST['session']) && $_POST['session'] == $session) ? 'selected' : '' ?>>
                                                            <?= htmlspecialchars($session) ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                            <div class="col-md-2 d-flex align-items-end">
                                                <button type="submit" class="btn btn-primary w-100">
                                                    <i class="fas fa-search me-2"></i> Search
                                                </button>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>

                            <!-- Subject Search -->
                            <div class="tab-pane fade" id="subject-search" role="tabpanel">
                                <div class="search-section">
                                    <h5><i class="fas fa-book me-2"></i> Search Subject Results</h5>
                                    <form method="POST" id="subjectSearchForm">
                                        <input type="hidden" name="search_type" value="subject">
                                        <div class="row g-3">
                                            <div class="col-md-3">
                                                <label for="subject_search" class="form-label">
                                                    <i class="fas fa-book me-1"></i> Subject
                                                </label>
                                                <select name="subject" id="subject_search" class="form-select select2" required>
                                                    <option value="">-- Select Subject --</option>
                                                    <?php foreach ($subjects as $subject): ?>
                                                        <option value="<?= htmlspecialchars($subject) ?>" <?= (isset($_POST['subject']) && $_POST['subject'] == $subject) ? 'selected' : '' ?>>
                                                            <?= htmlspecialchars($subject) ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                            <div class="col-md-3">
                                                <label for="class_subject" class="form-label">
                                                    <i class="fas fa-users me-1"></i> Class (Optional)
                                                </label>
                                                <select name="class" id="class_subject" class="form-select select2">
                                                    <option value="">-- All Classes --</option>
                                                    <?php foreach ($classes as $class): ?>
                                                        <option value="<?= htmlspecialchars($class) ?>" <?= (isset($_POST['class']) && $_POST['class'] == $class) ? 'selected' : '' ?>>
                                                            <?= htmlspecialchars($class) ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                            <div class="col-md-2">
                                                <label for="term_subject" class="form-label">
                                                    <i class="fas fa-calendar-alt me-1"></i> Term
                                                </label>
                                                <select name="term" id="term_subject" class="form-select select2" required>
                                                    <option value="">-- Select Term --</option>
                                                    <?php foreach ($terms as $term): ?>
                                                        <option value="<?= $term ?>" <?= (isset($_POST['term']) && $_POST['term'] == $term) ? 'selected' : '' ?>>
                                                            <?= $term ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                            <div class="col-md-2">
                                                <label for="session_subject" class="form-label">
                                                    <i class="fas fa-calendar me-1"></i> Session
                                                </label>
                                                <select name="session" id="session_subject" class="form-select select2" required>
                                                    <option value="">-- Select Session --</option>
                                                    <?php foreach ($sessions as $session): ?>
                                                        <option value="<?= htmlspecialchars($session) ?>" <?= (isset($_POST['session']) && $_POST['session'] == $session) ? 'selected' : '' ?>>
                                                            <?= htmlspecialchars($session) ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                            <div class="col-md-2 d-flex align-items-end">
                                                <button type="submit" class="btn btn-primary w-100">
                                                    <i class="fas fa-search me-2"></i> Search
                                                </button>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>

                        <!-- Results Section -->
                        <?php if (!empty($search_results)): ?>
                            <!-- Statistics for Class/Subject Searches -->
                            <?php if (!empty($statistics)): ?>
                                <div class="row mb-4">
                                    <div class="col-12">
                                        <h5 class="mb-3"><i class="fas fa-chart-bar me-2" style="color: var(--secondary-gold);"></i> Performance Statistics</h5>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="stat-card text-center">
                                            <h6><i class="fas fa-users me-1"></i> Total Students</h6>
                                            <h3><?= $statistics['total_students'] ?></h3>
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="stat-card text-center">
                                            <h6><i class="fas fa-chart-line me-1"></i> Average Score</h6>
                                            <h3><?= $statistics['average_score'] ?>%</h3>
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="stat-card text-center">
                                            <h6><i class="fas fa-arrow-up me-1"></i> Highest Score</h6>
                                            <h3><?= $statistics['highest_score'] ?>%</h3>
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="stat-card text-center">
                                            <h6><i class="fas fa-arrow-down me-1"></i> Lowest Score</h6>
                                            <h3><?= $statistics['lowest_score'] ?>%</h3>
                                        </div>
                                    </div>
                                </div>
                            <?php endif; ?>

                            <div class="table-responsive">
                                <table class="table table-hover" id="resultsTable">
                                    <thead>
                                        <tr>
                                            <th>S/N</th>
                                            <th>Student Name</th>
                                            <th>Admission No.</th>
                                            <th>Subject</th>
                                            <th>Class</th>
                                            <th>Term</th>
                                            <th>Session</th>
                                            <th>CBT Score</th>
                                            <th>2nd SUM Score</th>
                                            <th>Subjective</th>
                                            <th>Theory</th>
                                            <th>Practical</th>
                                            <th>Total</th>
                                            <th>Grade</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($search_results as $index => $result): 
                                            $subjective = $result['subjective_score'] ?? 0;
                                            $theory = $result['theory_score'] ?? 0;
                                            $practical = $result['practical_score'] ?? 0;
                                            $total_score = $result['total_score'] ?? ($result['second_sum_score'] + $subjective + $theory + $practical);
                                            $grade = $result['grade'] ?? (($gradeInfo = getGrade($total_score)) ? $gradeInfo[0] : 'F');
                                        ?>
                                            <tr>
                                                <td><strong><?= $index + 1 ?></strong></td>
                                                <td><?= htmlspecialchars($result['fullname'] ?? $result['name'] ?? 'N/A') ?></td>
                                                <td><span class="badge bg-secondary"><?= htmlspecialchars($result['registration_no']) ?></span></td>
                                                <td><?= htmlspecialchars($result['subject']) ?></td>
                                                <td><span class="badge bg-info"><?= htmlspecialchars($result['class']) ?></span></td>
                                                <td><span class="badge bg-warning text-dark"><?= htmlspecialchars($result['term']) ?></span></td>
                                                <td><span class="badge bg-secondary"><?= htmlspecialchars($result['session']) ?></span></td>
                                                <td><span class="badge cbt-score"><?= round($result['score'], 1) ?>%</span></td>
                                                <td><span class="badge second-sum-score" title="<?= 
                                                    stripos($result['class'], 'GRADE') !== false ? '30% of CBT Score' : '25% of CBT Score' ?>">
                                                    <?= round($result['second_sum_score'], 1) ?>%
                                                </span></td>
                                                <td><?= $subjective ? '<span class="badge subjective-score">' . round($subjective, 1) . '%</span>' : '<span class="text-muted">—</span>' ?></td>
                                                <td><?= $theory ? '<span class="badge theory-score">' . round($theory, 1) . '%</span>' : '<span class="text-muted">—</span>' ?></td>
                                                <td><?= $practical ? '<span class="badge practical-score">' . round($practical, 1) . '%</span>' : '<span class="text-muted">—</span>' ?></td>
                                                <td><span class="badge total-score"><?= round($total_score, 1) ?>%</span></td>
                                                <td><span class="badge grade-<?= $grade ?>"><?= $grade ?></span></td>
                                                <td>
                                                    <button class="btn btn-sm btn-outline-primary view-details" 
                                                            data-bs-toggle="modal" data-bs-target="#resultModal"
                                                            data-result='<?= htmlspecialchars(json_encode($result), ENT_QUOTES) ?>'>
                                                        <i class="fas fa-eye"></i>
                                                    </button>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>

                            <!-- Export Buttons -->
                            <div class="text-center mt-4">
                                <button class="btn btn-success" onclick="exportToExcel()">
                                    <i class="fas fa-file-excel me-2"></i> Export to Excel
                                </button>
                                <button class="btn btn-primary" onclick="window.print()">
                                    <i class="fas fa-print me-2"></i> Print
                                </button>
                            </div>

                        <?php elseif ($_SERVER['REQUEST_METHOD'] == 'POST'): ?>
                            <div class="empty-state text-center py-5">
                                <i class="fas fa-search fa-4x mb-3"></i>
                                <h4 class="text-muted">No results found</h4>
                                <p class="text-muted">Try adjusting your search criteria.</p>
                            </div>
                        <?php else: ?>
                            <div class="empty-state text-center py-5">
                                <i class="fas fa-chart-line fa-4x mb-3"></i>
                                <h4 class="text-muted">Search CBT Results</h4>
                                <p class="text-muted">Use the search tabs above to find student results.</p>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Footer -->
    <footer class="footer">
        <div class="container">
            <div class="row align-items-center">
                <div class="col-md-8">
                    <p class="mb-1"><i class="fas fa-crown me-2" style="color: var(--secondary-gold);"></i><strong>Henzy Royal International School</strong> - Computer Based Test System</p>
                    <p class="mb-0 small"><i class="fas fa-map-marker-alt me-1" style="color: var(--secondary-gold);"></i> <?= $schoolAddress ?></p>
                </div>
                <div class="col-md-4 text-md-end">
                    <p class="mb-0">Powered By <a href="https://dataswift.com.ng" target="_blank">DataSwift Coders</a> 
                    <img src="../datalogo.png" alt="DataSwift Logo"></p>
                    <small>&copy; <?= date('Y') ?> All Rights Reserved</small>
                </div>
            </div>
        </div>
    </footer>

    <!-- JavaScript Libraries -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    
    <!-- Select2 JS -->
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    
    <!-- DataTables -->
    <script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap5.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.3.6/js/dataTables.buttons.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.3.6/js/buttons.bootstrap5.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.3.6/js/buttons.html5.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.3.6/js/buttons.print.min.js"></script>
    
    <!-- JSZip for Excel export -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
    
    <script>
        let timeoutTimer;
        let timeoutProgress;

        // Initialize Select2
        $(document).ready(function() {
            $('.select2').select2({
                theme: 'bootstrap-5',
                width: '100%',
                placeholder: '-- Select Option --',
                allowClear: true
            });
            
            // Initialize DataTable if results exist
            <?php if (!empty($search_results)): ?>
                $('#resultsTable').DataTable({
                    dom: 'Bfrtip',
                    buttons: [
                        {
                            extend: 'excelHtml5',
                            text: '<i class="fas fa-file-excel me-2"></i> Excel',
                            className: 'btn btn-success',
                            title: 'CBT_Results_<?= date('Y-m-d') ?>'
                        },
                        {
                            extend: 'print',
                            text: '<i class="fas fa-print me-2"></i> Print',
                            className: 'btn btn-primary',
                            title: 'CBT Results - <?= $schoolName ?>'
                        }
                    ],
                    pageLength: 25,
                    order: [[0, 'asc']],
                    language: {
                        search: "<i class='fas fa-search me-2'></i>Search:",
                        lengthMenu: "Show _MENU_ entries",
                        info: "Showing _START_ to _END_ of _TOTAL_ entries",
                        paginate: {
                            first: '<i class="fas fa-angle-double-left"></i>',
                            previous: '<i class="fas fa-angle-left"></i>',
                            next: '<i class="fas fa-angle-right"></i>',
                            last: '<i class="fas fa-angle-double-right"></i>'
                        }
                    }
                });
            <?php endif; ?>
            
            <?php if ($show_warning): ?>
                showSessionTimeoutModal(<?= $time_until_timeout ?>);
            <?php endif; ?>
            
            // Set active tab based on previous search
            const searchType = '<?= $search_type ?>';
            if (searchType) {
                const tab = document.querySelector(`[data-bs-target="#${searchType}-search"]`);
                if (tab) {
                    new bootstrap.Tab(tab).show();
                }
            }
        });

        // Reset form function
        function resetForm(type) {
            document.getElementById(type + 'SearchForm').reset();
            $(`#${type}SearchForm .select2`).val(null).trigger('change');
        }

        // View result details
        document.querySelectorAll('.view-details').forEach(button => {
            button.addEventListener('click', function() {
                const resultData = JSON.parse(this.getAttribute('data-result'));
                const modalBody = document.getElementById('resultDetails');
                
                // Show loading spinner
                modalBody.innerHTML = `
                    <div class="text-center py-5">
                        <div class="spinner-border text-primary" style="width: 3rem; height: 3rem;" role="status">
                            <span class="visually-hidden">Loading...</span>
                        </div>
                        <p class="mt-3 text-muted">Loading result details...</p>
                    </div>
                `;
                
                // Display result details
                setTimeout(() => {
                    const classType = resultData.class;
                    const secondSumPercentage = classType.toUpperCase().includes('GRADE') ? '30%' : '25%';
                    const secondSumScore = classType.toUpperCase().includes('GRADE') ? 
                                          (resultData.score * 0.3).toFixed(1) : 
                                          (resultData.score * 0.25).toFixed(1);
                    
                    const subjective = resultData.subjective_score || 0;
                    const theory = resultData.theory_score || 0;
                    const practical = resultData.practical_score || 0;
                    const total = parseFloat(secondSumScore) + parseFloat(subjective) + parseFloat(theory) + parseFloat(practical);
                    
                    let grade = resultData.grade || 'F';
                    if (total >= 80) grade = 'A';
                    else if (total >= 70) grade = 'B';
                    else if (total >= 60) grade = 'C';
                    else if (total >= 50) grade = 'D';
                    else if (total >= 40) grade = 'E';
                    
                    let remark = '';
                    if (grade === 'A') remark = 'Excellent';
                    else if (grade === 'B') remark = 'Very Good';
                    else if (grade === 'C') remark = 'Good';
                    else if (grade === 'D') remark = 'Fair';
                    else if (grade === 'E') remark = 'Pass';
                    else remark = 'Fail';
                    
                    let answersHtml = '';
                    if (resultData.answers) {
                        try {
                            const answers = JSON.parse(resultData.answers);
                            answersHtml = `
                                <div class="mt-4">
                                    <h6><i class="fas fa-list me-2" style="color: var(--secondary-gold);"></i> Question Answers</h6>
                                    <div class="table-responsive">
                                        <table class="table table-sm table-bordered">
                                            <thead class="table-light">
                                                <tr>
                                                    <th>Q#</th>
                                                    <th>Selected Answer</th>
                                                    <th>Correct Answer</th>
                                                    <th>Status</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                            `;
                            
                            Object.keys(answers).forEach(qIndex => {
                                const answer = answers[qIndex];
                                const isCorrect = answer.selected === answer.correct;
                                answersHtml += `
                                    <tr>
                                        <td><strong>${parseInt(qIndex) + 1}</strong></td>
                                        <td>${answer.selected || '<span class="text-muted">Not answered</span>'}</td>
                                        <td>${answer.correct}</td>
                                        <td><span class="badge ${isCorrect ? 'cbt-score' : 'badge bg-danger'}">${isCorrect ? 'Correct' : 'Wrong'}</span></td>
                                    </tr>
                                `;
                            });
                            
                            answersHtml += '</tbody></table></div></div>';
                        } catch (e) {
                            console.error('Error parsing answers:', e);
                            answersHtml = '<p class="text-muted mt-3">Answer details not available.</p>';
                        }
                    } else {
                        answersHtml = '<p class="text-muted mt-3">No answer details available.</p>';
                    }

                    modalBody.innerHTML = `
                        <div class="row">
                            <div class="col-md-6">
                                <p><strong><i class="fas fa-user me-2" style="color: var(--secondary-gold);"></i>Student Name:</strong> ${resultData.fullname || resultData.name || 'N/A'}</p>
                                <p><strong><i class="fas fa-id-card me-2" style="color: var(--secondary-gold);"></i>Admission No:</strong> ${resultData.registration_no || 'N/A'}</p>
                                <p><strong><i class="fas fa-users me-2" style="color: var(--secondary-gold);"></i>Class:</strong> ${resultData.class || 'N/A'} <small class="text-muted">(${secondSumPercentage} of CBT for 2nd SUM)</small></p>
                                <p><strong><i class="fas fa-book me-2" style="color: var(--secondary-gold);"></i>Subject:</strong> ${resultData.subject || 'N/A'}</p>
                            </div>
                            <div class="col-md-6">
                                <p><strong><i class="fas fa-calendar-alt me-2" style="color: var(--secondary-gold);"></i>Term:</strong> ${resultData.term || 'N/A'}</p>
                                <p><strong><i class="fas fa-calendar me-2" style="color: var(--secondary-gold);"></i>Session:</strong> ${resultData.session || 'N/A'}</p>
                                <p><strong><i class="fas fa-clock me-2" style="color: var(--secondary-gold);"></i>Date Taken:</strong> ${resultData.date_taken ? new Date(resultData.date_taken).toLocaleString() : 'N/A'}</p>
                                <p><strong><i class="fas fa-hourglass-half me-2" style="color: var(--secondary-gold);"></i>Time Spent:</strong> ${resultData.time_spent ? new Date(resultData.time_spent * 1000).toISOString().substr(11, 8) : 'N/A'}</p>
                            </div>
                        </div>
                        
                        <div class="row mt-4">
                            <div class="col-12">
                                <h6><i class="fas fa-chart-pie me-2" style="color: var(--secondary-gold);"></i> Score Breakdown</h6>
                                <div class="table-responsive">
                                    <table class="table table-bordered">
                                        <thead class="table-light">
                                            <tr>
                                                <th>CBT Score</th>
                                                <th>2nd SUM Score</th>
                                                <th>Subjective</th>
                                                <th>Theory</th>
                                                <th>Practical</th>
                                                <th>Total</th>
                                                <th>Grade</th>
                                                <th>Remark</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <tr class="text-center">
                                                <td><span class="badge cbt-score">${parseFloat(resultData.score).toFixed(1)}%</span></td>
                                                <td><span class="badge second-sum-score">${secondSumScore}%</span></td>
                                                <td>${subjective ? '<span class="badge subjective-score">' + parseFloat(subjective).toFixed(1) + '%</span>' : '<span class="text-muted">—</span>'}</td>
                                                <td>${theory ? '<span class="badge theory-score">' + parseFloat(theory).toFixed(1) + '%</span>' : '<span class="text-muted">—</span>'}</td>
                                                <td>${practical ? '<span class="badge practical-score">' + parseFloat(practical).toFixed(1) + '%</span>' : '<span class="text-muted">—</span>'}</td>
                                                <td><span class="badge total-score">${total.toFixed(1)}%</span></td>
                                                <td><span class="badge grade-${grade}">${grade}</span></td>
                                                <td><strong>${remark}</strong></td>
                                            </tr>
                                        </tbody>
                                    </table>
                                    <small class="text-muted"><i class="fas fa-calculator me-1"></i> 2nd SUM Score Calculation: ${resultData.score}% × ${secondSumPercentage} = ${secondSumScore}%</small>
                                </div>
                            </div>
                        </div>
                        
                        <div class="row mt-4">
                            <div class="col-md-6">
                                <div class="stat-card text-center">
                                    <h6><i class="fas fa-check-circle me-1"></i> Correct Answers</h6>
                                    <h3>${resultData.correct_answers || 0}/${resultData.total_questions || 0}</h3>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="stat-card text-center">
                                    <h6><i class="fas fa-percentage me-1"></i> CBT Percentage</h6>
                                    <h3>${resultData.total_questions ? Math.round(((resultData.correct_answers || 0) / resultData.total_questions) * 100) : 0}%</h3>
                                </div>
                            </div>
                        </div>
                        ${answersHtml}
                    `;
                }, 500);
            });
        });

        // Export to Excel function
        function exportToExcel() {
            const table = document.querySelector('table');
            let csv = [];
            
            // Get headers (excluding Actions column)
            const headers = [];
            table.querySelectorAll('thead th').forEach((th, index) => {
                if (index !== table.querySelectorAll('thead th').length - 1) {
                    headers.push(th.textContent.trim());
                }
            });
            csv.push(headers.join(','));
            
            // Get rows (excluding Actions column)
            table.querySelectorAll('tbody tr').forEach(tr => {
                const row = [];
                const tds = tr.querySelectorAll('td');
                
                for (let i = 0; i < tds.length - 1; i++) {
                    let text = tds[i].textContent.trim();
                    text = text.replace(/[^\d.%A-Za-z\s-]/g, '').replace(/,/g, '');
                    row.push(text);
                }
                csv.push(row.join(','));
            });
            
            // Download CSV
            const csvContent = "data:text/csv;charset=utf-8," + csv.join('\n');
            const encodedUri = encodeURI(csvContent);
            const link = document.createElement("a");
            link.setAttribute("href", encodedUri);
            link.setAttribute("download", "cbt_results_<?= date('Y-m-d') ?>.csv");
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }

        // Session timeout functions
        function showSessionTimeoutModal(secondsLeft) {
            const modal = new bootstrap.Modal(document.getElementById('sessionTimeoutModal'));
            modal.show();
            
            let timeLeft = secondsLeft;
            timeoutTimer = setInterval(function() {
                timeLeft--;
                if (timeLeft <= 0) {
                    clearInterval(timeoutTimer);
                    document.getElementById('sessionTimeoutModal').classList.remove('show');
                    showSessionExpiredModal();
                } else {
                    updateTimeoutDisplay(timeLeft);
                }
            }, 1000);
        }

        function updateTimeoutDisplay(seconds) {
            const minutes = Math.floor(seconds / 60);
            const secs = seconds % 60;
            document.getElementById('timeoutTimer').textContent = 
                `${minutes}:${secs.toString().padStart(2, '0')}`;
            
            const progressPercent = (seconds / (<?= TIMEOUT_TIME ?> * 60)) * 100;
            document.getElementById('timeoutProgress').style.width = progressPercent + '%';
        }

        function keepSessionAlive() {
            $.ajax({
                url: window.location.href,
                method: 'POST',
                data: { keep_session_alive: true },
                success: function(response) {
                    bootstrap.Modal.getInstance(document.getElementById('sessionTimeoutModal')).hide();
                    clearInterval(timeoutTimer);
                }
            });
        }

        function showSessionExpiredModal() {
            const modal = new bootstrap.Modal(document.getElementById('sessionExpiredModal'));
            modal.show();
            setTimeout(function() {
                window.location.href = '../logout.php?timeout=1';
            }, 5000);
        }
    </script>
</body>
</html>