<?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'];

// 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 calculate grade and remark
function calculateGradeAndRemark($score) {
    if ($score >= 80) return ['A', 'Excellent'];
    elseif ($score >= 70) return ['B', 'Very Good'];
    elseif ($score >= 60) return ['C', 'Good'];
    elseif ($score >= 50) return ['D', 'Credit'];
    elseif ($score >= 40) return ['E', 'Pass'];
    else return ['F', 'Fail'];
}

// Handle form submission
$students_data = [];
$search_criteria = [];

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();
    }
    
    if (isset($_POST['search_students'])) {
        $class = $_POST['class'] ?? '';
        $subject = $_POST['subject'] ?? '';
        $term = $_POST['term'] ?? '';
        $session = $_POST['session'] ?? '';
        
        $search_criteria = compact('class', 'subject', 'term', 'session');
        
        try {
            $sql = "SELECT c.*, u.fullname 
                    FROM tbl_cbt_results c 
                    LEFT JOIN tbl_user u ON c.registration_no = u.registration_no 
                    WHERE c.class = :class 
                    AND c.subject = :subject 
                    AND c.term = :term 
                    AND c.session = :session 
                    ORDER BY u.fullname, c.registration_no";
            
            $stmt = $DBH->prepare($sql);
            $stmt->execute([
                ':class' => $class,
                ':subject' => $subject,
                ':term' => $term,
                ':session' => $session
            ]);
            
            $students_data = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            foreach ($students_data as &$student) {
                $student['second_sum_score'] = calculateSecondSumScore($student['score'], $student['class']);
            }
            
        } catch (PDOException $e) {
            $_SESSION['error'] = "Database error: " . $e->getMessage();
        }
        
    } elseif (isset($_POST['save_scores'])) {
        try {
            $DBH->beginTransaction();
            
            $saved_count = 0;
            $updated_student_results = 0;
            
            foreach ($_POST['scores'] as $result_id => $scores) {
                $subjective_score = !empty($scores['subjective']) ? floatval($scores['subjective']) : NULL;
                $theory_score = !empty($scores['theory']) ? floatval($scores['theory']) : NULL;
                $practical_score = !empty($scores['practical']) ? floatval($scores['practical']) : NULL;
                
                $class = $_POST['classes'][$result_id] ?? '';
                $cbt_score = floatval($_POST['cbt_scores'][$result_id]);
                $registration_no = $_POST['registration_nos'][$result_id] ?? '';
                
                $second_sum_score = calculateSecondSumScore($cbt_score, $class);
                
                $total_score = $second_sum_score + $subjective_score + $theory_score + $practical_score;
                
                list($grade, $remark) = calculateGradeAndRemark($total_score);
                
                $update_sql = "UPDATE tbl_cbt_results 
                              SET subjective_score = :subjective_score,
                                  theory_score = :theory_score,
                                  practical_score = :practical_score,
                                  total_score = :total_score,
                                  grade = :grade,
                                  remark = :remark,
                                  uploaded_by = :uploaded_by
                              WHERE id = :id";
                
                $stmt = $DBH->prepare($update_sql);
                $stmt->execute([
                    ':subjective_score' => $subjective_score,
                    ':theory_score' => $theory_score,
                    ':practical_score' => $practical_score,
                    ':total_score' => $total_score,
                    ':grade' => $grade,
                    ':remark' => $remark,
                    ':uploaded_by' => $_SESSION['SESS_ADMIN_ID'],
                    ':id' => $result_id
                ]);
                
                $check_sql = "SELECT exam, total FROM tbl_student_results 
                             WHERE registration_no = :reg_no 
                             AND class = :class 
                             AND subject = :subject 
                             AND term = :term 
                             AND year = :session 
                             LIMIT 1";
                
                $check_stmt = $DBH->prepare($check_sql);
                $check_stmt->execute([
                    ':reg_no' => $registration_no,
                    ':class' => $class,
                    ':subject' => $_POST['subject'],
                    ':term' => $_POST['term'],
                    ':session' => $_POST['session']
                ]);
                
                $existing_record = $check_stmt->fetch(PDO::FETCH_ASSOC);
                
                if ($existing_record) {
                    $current_exam = floatval($existing_record['exam'] ?? 0);
                    $current_total = floatval($existing_record['total'] ?? 0);
                    
                    $new_exam = $total_score;
                    $new_total = ($current_total - $current_exam) + $new_exam;
                    
                    $update_student_sql = "UPDATE tbl_student_results 
                                          SET exam = :exam,
                                              total = :total,
                                              grade = :grade,
                                              updated_at = NOW()
                                          WHERE registration_no = :reg_no 
                                          AND class = :class 
                                          AND subject = :subject 
                                          AND term = :term 
                                          AND year = :session";
                    
                    $update_stmt = $DBH->prepare($update_student_sql);
                    $update_stmt->execute([
                        ':exam' => $new_exam,
                        ':total' => $new_total,
                        ':grade' => $grade,
                        ':reg_no' => $registration_no,
                        ':class' => $class,
                        ':subject' => $_POST['subject'],
                        ':term' => $_POST['term'],
                        ':session' => $_POST['session']
                    ]);
                    
                    $updated_student_results++;
                } else {
                    $name_sql = "SELECT fullname FROM tbl_user WHERE registration_no = :reg_no LIMIT 1";
                    $name_stmt = $DBH->prepare($name_sql);
                    $name_stmt->execute([':reg_no' => $registration_no]);
                    $student_name = $name_stmt->fetchColumn() ?: 'Unknown';
                    
                    $insert_sql = "INSERT INTO tbl_student_results 
                                  (name, registration_no, exam, total, grade, class, subject, year, term, created_at, updated_at)
                                  VALUES (:name, :reg_no, :exam, :total, :grade, :class, :subject, :session, :term, NOW(), NOW())";
                    
                    $insert_stmt = $DBH->prepare($insert_sql);
                    $insert_stmt->execute([
                        ':name' => $student_name,
                        ':reg_no' => $registration_no,
                        ':exam' => $total_score,
                        ':total' => $total_score,
                        ':grade' => $grade,
                        ':class' => $class,
                        ':subject' => $_POST['subject'],
                        ':session' => $_POST['session'],
                        ':term' => $_POST['term']
                    ]);
                    
                    $updated_student_results++;
                }
                
                $saved_count++;
            }
            
            $DBH->commit();
            $_SESSION['success'] = "Successfully saved scores for $saved_count students! Updated $updated_student_results records in student results.";
            
            $search_criteria = [
                'class' => $_POST['class'],
                'subject' => $_POST['subject'],
                'term' => $_POST['term'],
                'session' => $_POST['session']
            ];
            
            header("Location: upload_other_scores.php?" . http_build_query($search_criteria));
            exit();
            
        } catch (PDOException $e) {
            $DBH->rollBack();
            $_SESSION['error'] = "Error saving scores: " . $e->getMessage();
        }
    }
}

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

$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>Upload Other Scores - 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;
            --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-lg {
            padding: 1rem 2rem;
            font-size: 1.1rem;
        }
        
        /* 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;
        }
        
        /* 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);
        }
        
        /* 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;
        }
        
        /* Score Styles */
        .cbt-score {
            background: linear-gradient(135deg, #e8f5e9, #c8e6c9);
            font-weight: 600;
            border-radius: 50px;
            padding: 0.3rem 0.8rem;
            display: inline-block;
        }
        
        .second-sum-score {
            background: linear-gradient(135deg, #e3f2fd, #bbdefb);
            color: var(--dark-blue);
            font-weight: 600;
            border-radius: 50px;
            padding: 0.3rem 0.8rem;
            display: inline-block;
            border-left: 3px solid var(--secondary-gold);
        }
        
        .total-score {
            background: linear-gradient(135deg, #2e7d32, #1b5e20);
            color: white;
            font-weight: 600;
            border-radius: 50px;
            padding: 0.3rem 0.8rem;
            display: inline-block;
        }
        
        .score-input {
            max-width: 100px;
            text-align: center;
            border-radius: 50px;
            border: 2px solid rgba(255, 215, 0, 0.3);
            transition: all 0.3s ease;
        }
        
        .score-input:focus {
            border-color: var(--secondary-gold);
            box-shadow: 0 0 0 0.25rem rgba(255, 215, 0, 0.25);
        }
        
        .score-input:hover {
            border-color: var(--secondary-gold);
        }
        
        /* Formula Info */
        .formula-info {
            font-size: 0.7rem;
            color: var(--dark-blue);
            margin-top: 0.25rem;
            opacity: 0.8;
        }
        
        /* Badge Styles */
        .badge {
            padding: 0.5rem 1rem;
            font-size: 0.75rem;
            font-weight: 500;
            border-radius: 50px;
        }
        
        .badge.bg-info {
            background: linear-gradient(135deg, #17a2b8, #138496) !important;
            color: white;
        }
        
        .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; }
        
        /* 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-secondary {
            background: linear-gradient(135deg, #e2e3e5, #d6d8d9);
            color: #383d41;
            border-left-color: #6c757d;
        }
        
        .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);
        }
        
        /* Info Box */
        .info-box {
            background: linear-gradient(135deg, #e3f2fd, #bbdefb);
            border-left: 4px solid var(--secondary-gold);
            padding: 1.5rem;
            border-radius: 10px;
            margin-bottom: 1.5rem;
        }
        
        .info-box h6 {
            color: var(--dark-blue);
            font-weight: 600;
        }
        
        .info-box ul {
            margin-bottom: 0;
        }
        
        .info-box li {
            margin-bottom: 0.5rem;
        }
        
        /* 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);
        }
        
        /* 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 td {
                white-space: normal;
            }
            
            .score-input {
                max-width: 80px;
            }
        }
    </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>

    <!-- 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 - Upload Other Scores</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="view_cbt_results.php"><i class="fas fa-chart-line me-2"></i> View Results</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 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"><a href="view_cbt_results.php" class="text-decoration-none" style="color: var(--primary-blue);">View Results</a></li>
                <li class="breadcrumb-item active" aria-current="page">Upload Other Scores</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">
                    <div class="card-header">
                        <h3 class="mb-0"><i class="fas fa-upload me-2"></i> Upload Other Scores</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 Form -->
                        <div class="search-section">
                            <h5><i class="fas fa-download me-2"></i> Load Class Scores</h5>
                            <form method="POST" id="searchForm">
                                <input type="hidden" name="search_students" value="1">
                                <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" 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="form-label">
                                            <i class="fas fa-book me-1"></i> Subject
                                        </label>
                                        <select name="subject" id="subject" 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-2">
                                        <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" 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="form-label">
                                            <i class="fas fa-calendar me-1"></i> Session
                                        </label>
                                        <select name="session" id="session" 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-download me-2"></i> Load Scores
                                        </button>
                                    </div>
                                </div>
                            </form>
                        </div>

                        <!-- Scores Form -->
                        <?php if (!empty($students_data)): ?>
                            <form method="POST" id="scoresForm">
                                <input type="hidden" name="save_scores" value="1">
                                <input type="hidden" name="class" value="<?= htmlspecialchars($search_criteria['class']) ?>">
                                <input type="hidden" name="subject" value="<?= htmlspecialchars($search_criteria['subject']) ?>">
                                <input type="hidden" name="term" value="<?= htmlspecialchars($search_criteria['term']) ?>">
                                <input type="hidden" name="session" value="<?= htmlspecialchars($search_criteria['session']) ?>">
                                
                                <div class="alert alert-info">
                                    <i class="fas fa-info-circle me-2"></i>
                                    <strong>Class:</strong> <?= htmlspecialchars($search_criteria['class']) ?> | 
                                    <strong>Subject:</strong> <?= htmlspecialchars($search_criteria['subject']) ?> | 
                                    <strong>Term:</strong> <?= htmlspecialchars($search_criteria['term']) ?> | 
                                    <strong>Session:</strong> <?= htmlspecialchars($search_criteria['session']) ?>
                                    <span class="badge bg-primary ms-2">
                                        <i class="fas fa-users me-1"></i> <?= count($students_data) ?> students
                                    </span>
                                </div>
                                
                                <!-- Calculation Info -->
                                <div class="info-box mb-3">
                                    <h6><i class="fas fa-calculator me-2" style="color: var(--secondary-gold);"></i> Actual 2nd SUM Score Calculation:</h6>
                                    <ul class="mb-0">
                                        <li><span class="badge bg-info">GRADE classes</span> (GRADE 101, GRADE 401, etc.): <strong>30%</strong> of CBT Score</li>
                                        <li><span class="badge bg-info">JSS/SSS classes</span> (JSS 1A, SSS 2C, etc.): <strong>25%</strong> of CBT Score</li>
                                        <li><span class="badge bg-secondary">Other classes</span>: <strong>25%</strong> of CBT Score (Default)</li>
                                    </ul>
                                </div>

                                <div class="table-responsive">
                                    <table class="table table-hover">
                                        <thead>
                                            <tr>
                                                <th>#</th>
                                                <th>Student Name</th>
                                                <th>Admission No</th>
                                                <th>Class</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>Remark</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($students_data as $index => $student): 
                                                $subjective = $student['subjective_score'] ?? 0;
                                                $theory = $student['theory_score'] ?? 0;
                                                $practical = $student['practical_score'] ?? 0;
                                                $total_score = $student['second_sum_score'] + $subjective + $theory + $practical;
                                                $percentage = (stripos($student['class'], 'GRADE') !== false) ? '30%' : '25%';
                                            ?>
                                                <tr>
                                                    <td><strong><?= $index + 1 ?></strong></td>
                                                    <td><?= htmlspecialchars($student['fullname'] ?? $student['name'] ?? 'N/A') ?></td>
                                                    <td>
                                                        <span class="badge bg-secondary"><?= htmlspecialchars($student['registration_no']) ?></span>
                                                        <input type="hidden" name="registration_nos[<?= $student['id'] ?>]" value="<?= htmlspecialchars($student['registration_no']) ?>">
                                                    </td>
                                                    <td>
                                                        <span class="badge bg-info"><?= htmlspecialchars($student['class']) ?></span>
                                                        <input type="hidden" name="classes[<?= $student['id'] ?>]" value="<?= htmlspecialchars($student['class']) ?>">
                                                    </td>
                                                    <td>
                                                        <span class="cbt-score"><?= round($student['score'], 1) ?>%</span>
                                                        <input type="hidden" name="cbt_scores[<?= $student['id'] ?>]" value="<?= $student['score'] ?>">
                                                    </td>
                                                    <td>
                                                        <span class="second-sum-score">
                                                            <?= round($student['second_sum_score'], 1) ?>%
                                                        </span>
                                                        <div class="formula-info">
                                                            <?= round($student['score'], 1) ?> × <?= $percentage ?> = <?= round($student['second_sum_score'], 1) ?>%
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <input type="number" name="scores[<?= $student['id'] ?>][subjective]" 
                                                               class="form-control score-input" 
                                                               value="<?= $student['subjective_score'] ?? '' ?>" 
                                                               min="0" max="100" step="0.5" placeholder="0-100">
                                                    </td>
                                                    <td>
                                                        <input type="number" name="scores[<?= $student['id'] ?>][theory]" 
                                                               class="form-control score-input" 
                                                               value="<?= $student['theory_score'] ?? '' ?>" 
                                                               min="0" max="100" step="0.5" placeholder="0-100">
                                                    </td>
                                                    <td>
                                                        <input type="number" name="scores[<?= $student['id'] ?>][practical]" 
                                                               class="form-control score-input" 
                                                               value="<?= $student['practical_score'] ?? '' ?>" 
                                                               min="0" max="100" step="0.5" placeholder="0-100">
                                                    </td>
                                                    <td>
                                                        <span class="total-score"><?= round($total_score, 1) ?>%</span>
                                                    </td>
                                                    <td>
                                                        <?php if ($student['grade']): ?>
                                                            <span class="badge grade-<?= $student['grade'] ?>"><?= $student['grade'] ?></span>
                                                        <?php else: ?>
                                                            <span class="text-muted">—</span>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <small><?= $student['remark'] ?? '—' ?></small>
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>

                                <div class="text-center mt-4">
                                    <button type="submit" class="btn btn-success btn-lg">
                                        <i class="fas fa-save me-2"></i> Save All Scores
                                    </button>
                                    <button type="button" class="btn btn-outline-secondary btn-lg" onclick="resetForm()">
                                        <i class="fas fa-redo me-2"></i> Reset Changes
                                    </button>
                                </div>
                            </form>

                            <!-- Auto-calculation script -->
                            <script>
                                document.addEventListener('DOMContentLoaded', function() {
                                    const scoreInputs = document.querySelectorAll('.score-input');
                                    
                                    scoreInputs.forEach(input => {
                                        input.addEventListener('input', function() {
                                            const row = this.closest('tr');
                                            updateTotalScore(row);
                                        });
                                    });
                                    
                                    function updateTotalScore(row) {
                                        const cbtScore = parseFloat(row.querySelector('input[name*="cbt_scores"]')?.value) || 0;
                                        const classInfo = row.querySelector('input[name*="classes"]')?.value || '';
                                        const subjectiveScore = parseFloat(row.querySelector('input[name*="[subjective]"]')?.value) || 0;
                                        const theoryScore = parseFloat(row.querySelector('input[name*="[theory]"]')?.value) || 0;
                                        const practicalScore = parseFloat(row.querySelector('input[name*="[practical]"]')?.value) || 0;
                                        
                                        let secondSumScore;
                                        let percentage;
                                        
                                        if (classInfo.toUpperCase().includes('GRADE')) {
                                            secondSumScore = cbtScore * 0.3;
                                            percentage = '30%';
                                        } else if (classInfo.toUpperCase().includes('JSS') || classInfo.toUpperCase().includes('SSS')) {
                                            secondSumScore = cbtScore * 0.25;
                                            percentage = '25%';
                                        } else {
                                            secondSumScore = cbtScore * 0.25;
                                            percentage = '25%';
                                        }
                                        
                                        const secondSumCell = row.querySelector('.second-sum-score');
                                        if (secondSumCell) {
                                            secondSumCell.innerHTML = `${secondSumScore.toFixed(1)}%`;
                                            const formulaDiv = row.querySelector('.formula-info');
                                            if (formulaDiv) {
                                                formulaDiv.innerHTML = `${cbtScore.toFixed(1)} × ${percentage} = ${secondSumScore.toFixed(1)}%`;
                                            }
                                        }
                                        
                                        const totalScore = secondSumScore + subjectiveScore + theoryScore + practicalScore;
                                        const totalCell = row.querySelector('.total-score');
                                        if (totalCell) {
                                            totalCell.textContent = totalScore.toFixed(1) + '%';
                                        }
                                        
                                        updateGradeAndRemark(row, totalScore);
                                    }
                                    
                                    function updateGradeAndRemark(row, totalScore) {
                                        let grade, remark;
                                        
                                        if (totalScore >= 80) {
                                            grade = 'A'; remark = 'Excellent';
                                        } else if (totalScore >= 70) {
                                            grade = 'B'; remark = 'Very Good';
                                        } else if (totalScore >= 60) {
                                            grade = 'C'; remark = 'Good';
                                        } else if (totalScore >= 50) {
                                            grade = 'D'; remark = 'Credit';
                                        } else if (totalScore >= 40) {
                                            grade = 'E'; remark = 'Pass';
                                        } else {
                                            grade = 'F'; remark = 'Fail';
                                        }
                                        
                                        const gradeCell = row.querySelector('td:nth-child(11)');
                                        if (gradeCell) {
                                            gradeCell.innerHTML = `<span class="badge grade-${grade}">${grade}</span>`;
                                        }
                                        
                                        const remarkCell = row.querySelector('td:nth-child(12)');
                                        if (remarkCell) {
                                            remarkCell.innerHTML = `<small>${remark}</small>`;
                                        }
                                    }
                                    
                                    document.querySelectorAll('tbody tr').forEach(row => {
                                        updateTotalScore(row);
                                    });
                                });
                                
                                function resetForm() {
                                    if (confirm('Are you sure you want to reset all changes?')) {
                                        document.getElementById('scoresForm').reset();
                                        location.reload();
                                    }
                                }
                            </script>

                        <?php elseif ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['search_students'])): ?>
                            <div class="empty-state text-center py-5">
                                <i class="fas fa-users fa-4x mb-3"></i>
                                <h4 class="text-muted">No students found</h4>
                                <p class="text-muted">No CBT results found for the selected criteria.</p>
                            </div>
                        <?php else: ?>
                            <div class="empty-state text-center py-5">
                                <i class="fas fa-upload fa-4x mb-3"></i>
                                <h4 class="text-muted">Upload Other Scores</h4>
                                <p class="text-muted">Use the search form above to load class scores and upload their subjective, theory, and practical scores.</p>
                                <div class="info-box mt-4">
                                    <h6><i class="fas fa-info-circle me-2" style="color: var(--secondary-gold);"></i> Important Notes:</h6>
                                    <ul class="text-start">
                                        <li><i class="fas fa-check-circle text-success me-2"></i> Total Score = Actual 2nd SUM Score + Subjective + Theory + Practical</li>
                                        <li><i class="fas fa-check-circle text-success me-2"></i> Actual 2nd SUM Score is calculated automatically based on class type</li>
                                        <li><i class="fas fa-check-circle text-success me-2"></i> Scores will also be updated in the student results table (tbl_student_results)</li>
                                        <li><i class="fas fa-check-circle text-success me-2"></i> All score inputs accept values from 0 to 100 with 0.5 increments</li>
                                    </ul>
                                </div>
                            </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 timeoutTimer;
        let timeoutProgress;

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

        // 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
        document.getElementById('searchForm')?.addEventListener('submit', function(e) {
            const classSelect = document.getElementById('class');
            const subjectSelect = document.getElementById('subject');
            const termSelect = document.getElementById('term');
            const sessionSelect = document.getElementById('session');
            
            if (!classSelect.value) {
                alert('Please select a class');
                e.preventDefault();
                return false;
            }
            if (!subjectSelect.value) {
                alert('Please select a subject');
                e.preventDefault();
                return false;
            }
            if (!termSelect.value) {
                alert('Please select a term');
                e.preventDefault();
                return false;
            }
            if (!sessionSelect.value) {
                alert('Please select a session');
                e.preventDefault();
                return false;
            }
            return true;
        });

        document.getElementById('scoresForm')?.addEventListener('submit', function(e) {
            return confirm('Are you sure you want to save all scores? This will update the student results table.');
        });
    </script>
</body>
</html>