<?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); // Warning after 15 minutes
define('TIMEOUT_TIME', 10); // Timeout after additional 10 minutes if no action

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

// Fetch all classes, subjects, terms, and sessions for dropdowns
$stmt_classes = $DBH->query("SELECT DISTINCT class FROM tbl_exam_class ORDER BY class");
$classes = $stmt_classes->fetchAll(PDO::FETCH_COLUMN);

$stmt_subjects = $DBH->query("SELECT * FROM tbl_subject ORDER BY subject");
$subjects = $stmt_subjects->fetchAll(PDO::FETCH_ASSOC);

$stmt_terms = $DBH->query("SELECT DISTINCT term FROM tbl_exam_class ORDER BY term");
$terms = $stmt_terms->fetchAll(PDO::FETCH_COLUMN);

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

// Handle search form submission
$search_results = [];
$class = $subject_id = $term = $session = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $class = $_POST['class'] ?? '';
    $subject_id = $_POST['subject_id'] ?? '';
    $term = $_POST['term'] ?? '';
    $session = $_POST['session'] ?? '';

    // Build the SQL query based on search criteria
    $sql = "
        SELECT q.id, q.question_text, q.question_type, q.option_a, q.option_b, q.option_c, q.option_d, 
               q.correct_answer, q.file_path, q.marks, q.assessment_type,
               e.exam_name, s.subject, ec.class, ec.term, ec.session, ec.id as exam_class_id,
               es.id as exam_subject_id
        FROM tbl_question q
        JOIN tbl_exam_class ec ON q.exam_class_id = ec.id
        JOIN tbl_exam e ON ec.exam_id = e.id
        JOIN tbl_subject s ON q.subject_id = s.id
        JOIN tbl_exam_subject es ON q.exam_subject_id = es.id
        WHERE 1=1
    ";

    $params = [];

    if (!empty($class)) {
        $sql .= " AND ec.class = :class";
        $params[':class'] = $class;
    }
    if (!empty($subject_id)) {
        $sql .= " AND q.subject_id = :subject_id";
        $params[':subject_id'] = $subject_id;
    }
    if (!empty($term)) {
        $sql .= " AND ec.term = :term";
        $params[':term'] = $term;
    }
    if (!empty($session)) {
        $sql .= " AND ec.session = :session";
        $params[':session'] = $session;
    }
    
    $sql .= " ORDER BY e.exam_name, s.subject, ec.class, q.id";

    $stmt = $DBH->prepare($sql);
    $stmt->execute($params);
    $search_results = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// Handle AJAX delete request
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['delete_question_id'])) {
    header('Content-Type: application/json');
    
    try {
        $question_id = $_POST['delete_question_id'];
        
        // Get file path to delete physical file
        $stmt = $DBH->prepare("SELECT file_path FROM tbl_question WHERE id = :id");
        $stmt->execute(['id' => $question_id]);
        $question = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($question && $question['file_path']) {
            @unlink($_SERVER['DOCUMENT_ROOT'] . $question['file_path']);
        }
        
        // Delete the question
        $stmt = $DBH->prepare("DELETE FROM tbl_question WHERE id = :id");
        $result = $stmt->execute(['id' => $question_id]);
        
        if ($result) {
            echo json_encode(['success' => true, 'message' => 'Question deleted successfully']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to delete question']);
        }
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
    }
    exit();
} elseif (isset($_POST['keep_session_alive'])) {
    // AJAX call to keep session alive
    $_SESSION['last_activity'] = time();
    $_SESSION['warning_shown'] = false;
    $_SESSION['timeout_triggered'] = false;
    echo json_encode(['success' => true]);
    exit();
}

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

// Determine if we should show warning
$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 has timed out
    $_SESSION['timeout_triggered'] = true;
    session_destroy();
    header("Location: ../logout.php?timeout=1");
    exit();
}

// Function to get assessment type badge class
function getAssessmentBadgeClass($assessment_type) {
    switch($assessment_type) {
        case 'CA1': return 'badge-ca1';
        case 'CA2': return 'badge-ca2';
        case 'CA3': return 'badge-ca3';
        case 'Term Exam': return 'badge-term';
        case 'Mock Exam': return 'badge-mock';
        default: return 'badge-secondary';
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Questions - 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" />
    
    <!-- Custom CSS -->
    <style>
        :root {
            --primary-blue: #1a4b8c;    /* Royal Blue */
            --secondary-gold: #FFD700;    /* Gold */
            --dark-blue: #0f2b4f;         /* Dark Blue */
            --light-blue: #4a7db5;         /* Medium Blue */
            --light-gold: #FFF1B8;          /* Light Gold */
            --bg-light: #f5f9ff;
        }
        
        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;
        }
        
        .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-danger {
            border: 2px solid #dc3545;
            color: #dc3545;
            background: transparent;
            padding: 0.75rem 1.5rem;
            border-radius: 50px;
            font-weight: 500;
        }
        
        .btn-outline-danger:hover {
            background: #dc3545;
            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;
        }
        
        /* 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.9rem;
        }
        
        .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);
        }
        
        /* Badge Styles */
        .badge-ca1 { background: linear-gradient(135deg, #17a2b8, #138496); color: white; }
        .badge-ca2 { background: linear-gradient(135deg, #28a745, #218838); color: white; }
        .badge-ca3 { background: linear-gradient(135deg, #ffc107, #e0a800); color: var(--dark-blue); }
        .badge-term { background: linear-gradient(135deg, #6610f2, #520dc2); color: white; }
        .badge-mock { background: linear-gradient(135deg, #fd7e14, #e56b08); color: white; }
        .badge-secondary { background: linear-gradient(135deg, #6c757d, #545b62); color: white; }
        
        .badge-class {
            background: linear-gradient(135deg, var(--primary-blue), var(--dark-blue));
            color: white;
            padding: 0.5rem 1rem;
            border-radius: 50px;
            font-size: 0.85rem;
        }
        
        .badge-term {
            background: linear-gradient(135deg, #ffc107, #e0a800);
            color: var(--dark-blue);
            padding: 0.5rem 1rem;
            border-radius: 50px;
            font-size: 0.85rem;
        }
        
        .badge-session {
            background: linear-gradient(135deg, #6c757d, #545b62);
            color: white;
            padding: 0.5rem 1rem;
            border-radius: 50px;
            font-size: 0.85rem;
        }
        
        .badge-correct {
            background: linear-gradient(135deg, #28a745, #218838);
            color: white;
            padding: 0.4rem 0.8rem;
            border-radius: 50px;
            font-size: 0.8rem;
        }
        
        /* Option Preview */
        .option-preview {
            margin-bottom: 0.25rem;
        }
        
        .option-preview .badge {
            background: linear-gradient(135deg, #f8f9fa, #e9ecef);
            color: var(--dark-blue);
            border: 1px solid rgba(255, 215, 0, 0.3);
            padding: 0.4rem 0.6rem;
            font-size: 0.75rem;
        }
        
        /* Question Preview */
        .question-preview {
            max-width: 250px;
            background: #f8f9fa;
            padding: 0.5rem;
            border-radius: 5px;
            border-left: 3px solid var(--secondary-gold);
            font-size: 0.9rem;
        }
        
        /* 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;
        }
        
        /* Count Badge */
        .count-badge {
            background: linear-gradient(135deg, var(--secondary-gold), #e6b800);
            color: var(--dark-blue);
            font-weight: 600;
            padding: 0.5rem 1rem;
            border-radius: 50px;
        }
        
        /* 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);
        }
        
        /* 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;
        }
        
        /* 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;
            }
            
            .table thead {
                display: none;
            }
            
            .table tbody tr {
                display: block;
                margin-bottom: 1rem;
                border: 1px solid rgba(255, 215, 0, 0.2);
                border-radius: 10px;
            }
            
            .table td {
                display: block;
                text-align: right;
                padding: 0.75rem;
                border-bottom: 1px solid rgba(255, 215, 0, 0.1);
            }
            
            .table td::before {
                content: attr(data-label);
                float: left;
                font-weight: 600;
                color: var(--primary-blue);
            }
        }
    </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>

    <!-- Delete Confirmation Modal -->
    <div class="modal fade" id="deleteConfirmModal" tabindex="-1" aria-labelledby="deleteConfirmModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="deleteConfirmModalLabel">
                        <i class="fas fa-exclamation-triangle me-2" style="color: var(--secondary-gold);"></i>
                        Confirm Delete
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body text-center py-4">
                    <i class="fas fa-trash-alt fa-4x mb-3" style="color: #dc3545;"></i>
                    <h4 class="mb-3">Are you sure?</h4>
                    <p class="mb-2">You are about to delete this question.</p>
                    <p class="text-danger"><strong>This action cannot be undone!</strong></p>
                    <input type="hidden" id="delete-question-id">
                </div>
                <div class="modal-footer justify-content-center">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">
                        <i class="fas fa-times me-2"></i> Cancel
                    </button>
                    <button type="button" class="btn btn-danger" onclick="confirmDelete()" id="confirmDeleteBtn">
                        <i class="fas fa-trash me-2"></i> Delete Question
                    </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 - Manage Questions</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="../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 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">Manage Questions</li>
            </ol>
        </nav>

        <div class="row">
            <div class="col-12">
                <!-- Back to Dashboard Button -->
                <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>
                    </div>
                </div>

                <div class="card action-card mb-4">
                    <div class="card-header">
                        <h3 class="mb-0"><i class="fas fa-search me-2"></i> Search Questions</h3>
                    </div>
                    <div class="card-body">
                        <form method="POST" id="searchForm">
                            <div class="row g-3">
                                <div class="col-md-3">
                                    <label for="class" class="form-label"><i class="fas fa-users me-1"></i> Class</label>
                                    <select name="class" id="class" class="form-select select2-single">
                                        <option value="">-- All Classes --</option>
                                        <?php foreach ($classes as $class_item): ?>
                                            <option value="<?= htmlspecialchars($class_item) ?>" <?= ($class == $class_item) ? 'selected' : '' ?>>
                                                <?= htmlspecialchars($class_item) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-md-3">
                                    <label for="subject_id" class="form-label"><i class="fas fa-book me-1"></i> Subject</label>
                                    <select name="subject_id" id="subject_id" class="form-select select2-single">
                                        <option value="">-- All Subjects --</option>
                                        <?php foreach ($subjects as $subject): ?>
                                            <option value="<?= $subject['id'] ?>" <?= ($subject_id == $subject['id']) ? 'selected' : '' ?>>
                                                <?= htmlspecialchars($subject['subject']) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-md-3">
                                    <label for="term" class="form-label"><i class="fas fa-calendar-alt me-1"></i> Term</label>
                                    <select name="term" id="term" class="form-select select2-single">
                                        <option value="">-- All Terms --</option>
                                        <?php foreach ($terms as $term_item): ?>
                                            <option value="<?= htmlspecialchars($term_item) ?>" <?= ($term == $term_item) ? 'selected' : '' ?>>
                                                <?= htmlspecialchars($term_item) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-md-3">
                                    <label for="session" class="form-label"><i class="fas fa-calendar me-1"></i> Session</label>
                                    <select name="session" id="session" class="form-select select2-single">
                                        <option value="">-- All Sessions --</option>
                                        <?php foreach ($sessions as $session_item): ?>
                                            <option value="<?= htmlspecialchars($session_item) ?>" <?= ($session == $session_item) ? 'selected' : '' ?>>
                                                <?= htmlspecialchars($session_item) ?>
                                            </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 Questions
                                </button>
                                <button type="button" class="btn btn-outline-secondary" onclick="resetForm()">
                                    <i class="fas fa-redo me-2"></i> Reset
                                </button>
                                <a href="set_questions.php" class="btn btn-success">
                                    <i class="fas fa-plus me-2"></i> Add New Questions
                                </a>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- Search Results -->
                <div class="card action-card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h3 class="mb-0"><i class="fas fa-list me-2"></i> Question List</h3>
                        <span class="count-badge">
                            <i class="fas fa-question-circle me-1"></i> <?= count($search_results) ?> question(s) found
                        </span>
                    </div>
                    <div class="card-body">
                        <?php if (!empty($search_results)): ?>
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead>
                                        <tr>
                                            <th>ID</th>
                                            <th>Question</th>
                                            <th>Options</th>
                                            <th>Correct</th>
                                            <th>Ass. Type</th>
                                            <th>Marks</th>
                                            <th>File</th>
                                            <th>Exam</th>
                                            <th>Subject</th>
                                            <th>Class</th>
                                            <th>Term</th>
                                            <th>Session</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($search_results as $question): ?>
                                            <tr id="question-row-<?= $question['id'] ?>">
                                                <td data-label="ID"><strong><?= $question['id'] ?></strong></td>
                                                <td data-label="Question">
                                                    <div class="question-preview">
                                                        <?= strip_tags(substr($question['question_text'], 0, 50)) . (strlen(strip_tags($question['question_text'])) > 50 ? '...' : '') ?>
                                                    </div>
                                                    <small class="text-muted">Type: <?= ucfirst($question['question_type']) ?></small>
                                                </td>
                                                <td data-label="Options">
                                                    <?php if ($question['question_type'] == 'objective'): ?>
                                                        <div class="option-preview">
                                                            <span class="badge">A: <?= strip_tags(substr($question['option_a'] ?? '', 0, 20)) ?></span>
                                                        </div>
                                                        <div class="option-preview">
                                                            <span class="badge">B: <?= strip_tags(substr($question['option_b'] ?? '', 0, 20)) ?></span>
                                                        </div>
                                                        <div class="option-preview">
                                                            <span class="badge">C: <?= strip_tags(substr($question['option_c'] ?? '', 0, 20)) ?></span>
                                                        </div>
                                                        <div class="option-preview">
                                                            <span class="badge">D: <?= strip_tags(substr($question['option_d'] ?? '', 0, 20)) ?></span>
                                                        </div>
                                                    <?php else: ?>
                                                        <span class="badge bg-secondary">N/A</span>
                                                    <?php endif; ?>
                                                </td>
                                                <td data-label="Correct">
                                                    <?php if ($question['question_type'] == 'objective'): ?>
                                                        <span class="badge-correct"><?= $question['correct_answer'] ?></span>
                                                    <?php else: ?>
                                                        <span class="badge bg-secondary">N/A</span>
                                                    <?php endif; ?>
                                                </td>
                                                <td data-label="Ass. Type">
                                                    <span class="badge <?= getAssessmentBadgeClass($question['assessment_type'] ?? '') ?>">
                                                        <?= $question['assessment_type'] ?? 'N/A' ?>
                                                    </span>
                                                </td>
                                                <td data-label="Marks">
                                                    <span class="badge bg-info"><?= $question['marks'] ?? '1' ?></span>
                                                </td>
                                                <td data-label="File">
                                                    <?php if (!empty($question['file_path'])): ?>
                                                        <a href="<?= htmlspecialchars($question['file_path']) ?>" target="_blank" class="btn btn-sm btn-outline-primary" title="View File">
                                                            <i class="fas fa-eye"></i>
                                                        </a>
                                                    <?php else: ?>
                                                        <span class="text-muted">—</span>
                                                    <?php endif; ?>
                                                </td>
                                                <td data-label="Exam"><?= htmlspecialchars($question['exam_name']) ?></td>
                                                <td data-label="Subject"><?= htmlspecialchars($question['subject']) ?></td>
                                                <td data-label="Class">
                                                    <span class="badge-class"><?= htmlspecialchars($question['class']) ?></span>
                                                </td>
                                                <td data-label="Term">
                                                    <span class="badge-term"><?= htmlspecialchars($question['term']) ?></span>
                                                </td>
                                                <td data-label="Session">
                                                    <span class="badge-session"><?= htmlspecialchars($question['session']) ?></span>
                                                </td>
                                                <td data-label="Actions">
                                                    <div class="btn-group" role="group">
                                                        <a href="add_question.php?exam_subject_id=<?= $question['exam_subject_id'] ?>" class="btn btn-sm btn-warning" title="Edit Question">
                                                            <i class="fas fa-edit"></i>
                                                        </a>
                                                        <button type="button" class="btn btn-sm btn-danger delete-question-btn" 
                                                                data-question-id="<?= $question['id'] ?>" 
                                                                data-question-text="<?= htmlspecialchars(strip_tags(substr($question['question_text'], 0, 50))) ?>"
                                                                title="Delete Question">
                                                            <i class="fas fa-trash"></i>
                                                        </button>
                                                    </div>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php else: ?>
                            <div class="empty-state text-center py-5">
                                <i class="fas fa-search fa-4x mb-3" style="color: var(--secondary-gold);"></i>
                                <h4 class="text-muted">No questions found</h4>
                                <p class="text-muted mb-4">Use the search form above to filter questions or add new questions.</p>
                                <a href="set_questions.php" class="btn btn-primary">
                                    <i class="fas fa-plus me-2"></i> Add Your First Question
                                </a>
                            </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>
    
    <script>
        let deleteModal;
        let currentQuestionId = null;
        let timeoutTimer;
        let timeoutProgress;

        // Initialize Select2
        $(document).ready(function() {
            $('.select2-single').select2({
                theme: 'bootstrap-5',
                width: '100%',
                placeholder: '-- Select Option --',
                allowClear: true
            });
            
            // Initialize delete modal
            deleteModal = new bootstrap.Modal(document.getElementById('deleteConfirmModal'));
            
            <?php if ($show_warning): ?>
                showSessionTimeoutModal(<?= $time_until_timeout ?>);
            <?php endif; ?>
        });

        // Delete functionality
        document.querySelectorAll('.delete-question-btn').forEach(button => {
            button.addEventListener('click', function() {
                const questionId = this.getAttribute('data-question-id');
                const questionText = this.getAttribute('data-question-text');
                currentQuestionId = questionId;
                
                // Update modal message
                const modalBody = document.querySelector('#deleteConfirmModal .modal-body p.mb-2');
                if (modalBody) {
                    modalBody.innerHTML = `You are about to delete: <strong>"${questionText}"</strong>`;
                }
                
                deleteModal.show();
            });
        });

        function confirmDelete() {
            if (!currentQuestionId) return;
            
            const confirmBtn = document.getElementById('confirmDeleteBtn');
            const originalText = confirmBtn.innerHTML;
            confirmBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i> Deleting...';
            confirmBtn.disabled = true;

            // Create form data
            const formData = new FormData();
            formData.append('delete_question_id', currentQuestionId);

            // Send AJAX request
            fetch(window.location.href, {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Hide modal
                    deleteModal.hide();
                    
                    // Remove the row with animation
                    const row = document.getElementById(`question-row-${currentQuestionId}`);
                    if (row) {
                        row.style.transition = 'all 0.3s ease';
                        row.style.opacity = '0';
                        row.style.height = row.offsetHeight + 'px';
                        
                        setTimeout(() => {
                            row.style.height = '0';
                            row.style.paddingTop = '0';
                            row.style.paddingBottom = '0';
                            row.style.marginBottom = '0';
                            row.style.border = 'none';
                        }, 50);
                        
                        setTimeout(() => {
                            row.remove();
                            updateQuestionCount();
                            showAlert(data.message, 'success');
                        }, 350);
                    }
                } else {
                    showAlert(data.message || 'Error deleting question', 'danger');
                }
                
                // Reset button
                confirmBtn.innerHTML = originalText;
                confirmBtn.disabled = false;
                currentQuestionId = null;
            })
            .catch(error => {
                console.error('Error:', error);
                showAlert('Network error occurred', 'danger');
                confirmBtn.innerHTML = originalText;
                confirmBtn.disabled = false;
                currentQuestionId = null;
            });
        }

        function showAlert(message, type) {
            // Remove existing alerts
            const existingAlerts = document.querySelectorAll('.ajax-alert');
            existingAlerts.forEach(alert => alert.remove());
            
            // Create new alert
            const alertDiv = document.createElement('div');
            alertDiv.className = `alert alert-${type} alert-dismissible fade show ajax-alert`;
            alertDiv.innerHTML = `
                <i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-circle'} me-2"></i>
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            `;
            
            // Insert alert at the top of the card body
            const cardBody = document.querySelector('.card-body');
            cardBody.insertBefore(alertDiv, cardBody.firstChild);
            
            // Auto dismiss after 5 seconds
            setTimeout(() => {
                if (alertDiv.parentNode) {
                    alertDiv.remove();
                }
            }, 5000);
        }

        function updateQuestionCount() {
            const questionCount = document.querySelectorAll('tbody tr').length;
            const badge = document.querySelector('.count-badge');
            if (badge) {
                badge.innerHTML = `<i class="fas fa-question-circle me-1"></i> ${questionCount} question(s) found`;
            }
            
            // Show empty state if no questions left
            if (questionCount === 0) {
                const table = document.querySelector('table');
                if (table) {
                    table.style.display = 'none';
                    showEmptyState();
                }
            }
        }

        function showEmptyState() {
            const cardBody = document.querySelector('.card-body');
            const existingEmptyState = cardBody.querySelector('.empty-state');
            if (existingEmptyState) return;
            
            const emptyState = document.createElement('div');
            emptyState.className = 'empty-state text-center py-5';
            emptyState.innerHTML = `
                <i class="fas fa-search fa-4x mb-3" style="color: var(--secondary-gold);"></i>
                <h4 class="text-muted">No questions found</h4>
                <p class="text-muted mb-4">Use the search form above to filter questions or add new questions.</p>
                <a href="set_questions.php" class="btn btn-primary">
                    <i class="fas fa-plus me-2"></i> Add Your First Question
                </a>
            `;
            
            cardBody.appendChild(emptyState);
        }

        function resetForm() {
            document.getElementById('searchForm').reset();
            $('.select2-single').val(null).trigger('change');
        }

        // 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);
        }

        // Form validation for search
        document.getElementById('searchForm')?.addEventListener('submit', function(e) {
            // Optional: Add validation if needed
            return true;
        });
    </script>
</body>
</html>