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

// Get current branch settings from central database
$branchCode = getCurrentBranchCode();
$branchSettings = getSchoolSettings($branchCode);

if ($branchSettings) {
    $schoolName = $branchSettings['branch_name'];
    $schoolAddress = $branchSettings['branch_address'];
    $schoolShortName = $branchSettings['branch_short_name'];
    $schoolMotto = $branchSettings['school_motto'];
    $schoolLogo = $branchSettings['school_logo_path'];
    $schoolPhone = $branchSettings['contact_phone'];
    $schoolEmail = $branchSettings['contact_email'];
    $footerText = $branchSettings['footer_text'];
    $footerCopyright = $branchSettings['footer_copyright'];
} else {
    // Fallback values if no branch settings found
    $schoolName = "Henzy Royal International School";
    $schoolAddress = "No 17 Amadi Street, Amakohia, Uratta Owerri Imo State Nigeria";
    $schoolShortName = "HRIS";
    $schoolMotto = "THE PRIDE OF EXCELLENCE";
    $schoolLogo = "coll_logo.png";
    $schoolPhone = "+234 803 292 9756";
    $schoolEmail = "support@hris.com.ng";
    $footerText = "THE PRIDE OF EXCELLENCE";
    $footerCopyright = "Copyright © Henzy Royal International School";
}

// Get system-wide settings
$supportPhone = getSystemSetting('support_phone') ?: $schoolPhone;
$supportEmail = getSystemSetting('support_email') ?: $schoolEmail;
$developerName = getSystemSetting('developer_name') ?: 'DataSwift Coders';
$developerWebsite = getSystemSetting('developer_website') ?: 'https://dataswift.com.ng';

// Create a database connection (using existing dbconfig)
$conn = $DBH; // Use the existing PDO connection from dbconfig.php

// Fetch dynamic options for class, term, year, and subject from the database
$query = "SELECT DISTINCT class FROM tbl_student_results ORDER BY class";
$stmt = $conn->prepare($query);
$stmt->execute();
$classes = $stmt->fetchAll(PDO::FETCH_COLUMN);

$query = "SELECT DISTINCT term FROM tbl_student_results ORDER BY term";
$stmt = $conn->prepare($query);
$stmt->execute();
$terms = $stmt->fetchAll(PDO::FETCH_COLUMN);

$query = "SELECT DISTINCT year FROM tbl_student_results ORDER BY year DESC";
$stmt = $conn->prepare($query);
$stmt->execute();
$years = $stmt->fetchAll(PDO::FETCH_COLUMN);

$query = "SELECT DISTINCT subject FROM tbl_student_results ORDER BY subject";
$stmt = $conn->prepare($query);
$stmt->execute();
$subjects = $stmt->fetchAll(PDO::FETCH_COLUMN);

// Initialize variables
$page_title = '';
$subject_name = '';
$total_results_count = 0;
$score_records = [];
$class = $term = $year = $subject = '';

// Handle search form submission
if ($_SERVER["REQUEST_METHOD"] == "POST" && !isset($_POST['update_results'])) {
    // Extract search data from the form
    $class = strip_tags($_POST['class']);
    $term = strip_tags($_POST['term']);
    $year = strip_tags($_POST['year']);
    $subject = strip_tags($_POST['subject']);

    // Retrieve score records from the database based on the search criteria
    $query = "SELECT * FROM tbl_student_results WHERE class = ? AND term = ? AND year = ? AND subject = ? ORDER BY name ASC";
    $stmt = $conn->prepare($query);
    $stmt->execute([$class, $term, $year, $subject]);
    $score_records = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Set page title
    $page_title = "Class: $class | Term: $term | Year: $year";

    // Set subject name
    $subject_name = $subject;

    // Count of total student results
    $total_results_count = count($score_records);
}

// Handle form submission for updating scores
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['update_results'])) {
    // Extract data from the form
    $record_ids = $_POST['record_id'];
    $test1_scores = $_POST['test1'];
    $test2_scores = $_POST['test2'];
    $exam_scores = $_POST['exam'];
    $class = $_POST['class'];
    $term = $_POST['term'];
    $year = $_POST['year'];
    $subject = $_POST['subject'];

    // Update the records in the database
    $update_query = "UPDATE tbl_student_results SET test1 = ?, test2 = ?, exam = ?, total = (test1 + test2 + exam) WHERE id = ?";
    $stmt = $conn->prepare($update_query);
    $success_count = 0;

    foreach ($record_ids as $index => $record_id) {
        $test1 = $test1_scores[$index];
        $test2 = $test2_scores[$index];
        $exam = $exam_scores[$index];
        
        // Validate scores are numbers
        if (is_numeric($test1) && is_numeric($test2) && is_numeric($exam)) {
            $stmt->execute([$test1, $test2, $exam, $record_id]);
            $success_count += $stmt->rowCount();
        }
    }

    if ($success_count > 0) {
        $success_message = "Successfully updated $success_count scores for $subject - $class, $term, $year";
        
        // Refresh the records
        $query = "SELECT * FROM tbl_student_results WHERE class = ? AND term = ? AND year = ? AND subject = ? ORDER BY name ASC";
        $stmt = $conn->prepare($query);
        $stmt->execute([$class, $term, $year, $subject]);
        $score_records = $stmt->fetchAll(PDO::FETCH_ASSOC);
        $total_results_count = count($score_records);
        $page_title = "Class: $class | Term: $term | Year: $year";
        $subject_name = $subject;
    } else {
        $error_message = "Error updating scores. Please check your inputs.";
    }
}

// Get admin full name
$admin_fullname = '';
$rows = sql($DBH, "SELECT fullname FROM tbl_admin WHERE status = ?", ["Active"], "rows");
if(!empty($rows)) {
    $admin_fullname = $rows[0]['fullname'];
}

// Get all branches for branch switcher
$allBranches = getAllBranches();
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Edit Subject Scores - <?php echo $schoolName; ?></title>
    <link rel="icon" type="image/png" href="../<?php echo $schoolLogo; ?>">
    
    <!-- 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 -->
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    
    <!-- DataTables CSS -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css">
    
    <style>
        :root {
            --primary-blue: #1a4b8c;
            --secondary-gold: #FFD700;
            --dark-blue: #0f2b4f;
            --light-blue: #4a7db5;
            --light-gold: #FFF1B8;
            --bg-light: #f5f9ff;
        }
        
        body {
            font-family: 'Poppins', sans-serif;
            background-color: var(--bg-light);
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }
        
        /* Navbar Styles */
        .navbar {
            background: linear-gradient(135deg, var(--primary-blue), var(--dark-blue));
            box-shadow: 0 0.15rem 1.75rem 0 rgba(26, 75, 140, 0.2);
            position: fixed;
            top: 0;
            width: 100%;
            z-index: 1030;
            color: white;
            border-bottom: 2px solid var(--secondary-gold);
        }
        
        .navbar-brand {
            font-weight: 800;
            font-size: 1.2rem;
            color: white;
            display: flex;
            align-items: center;
        }
        
        .navbar-brand img {
            border-radius: 4px;
            margin-right: 10px;
        }
        
        /* Branch Badge */
        .branch-badge {
            background: var(--secondary-gold);
            color: var(--dark-blue);
            padding: 0.25rem 0.75rem;
            border-radius: 20px;
            font-size: 0.75rem;
            font-weight: 600;
            display: inline-block;
        }
        
        /* Sidebar Styles */
        .sidebar {
            background: linear-gradient(180deg, var(--dark-blue) 0%, var(--primary-blue) 100%);
            position: fixed;
            top: 56px;
            left: -250px;
            width: 250px;
            height: calc(100vh - 56px);
            transition: all 0.3s;
            z-index: 1000;
            overflow-y: auto;
            border-right: 3px solid var(--secondary-gold);
        }
        
        .sidebar.active {
            left: 0;
        }
        
        .sidebar .nav-link {
            color: rgba(255, 255, 255, 0.9);
            font-weight: 500;
            padding: 0.75rem 1rem;
            margin-bottom: 0.2rem;
            transition: all 0.2s;
            border-left: 3px solid transparent;
        }
        
        .sidebar .nav-link:hover {
            color: white;
            background-color: rgba(255, 215, 0, 0.15);
            border-left-color: var(--secondary-gold);
        }
        
        .sidebar .nav-link.active {
            color: var(--dark-blue);
            background-color: var(--secondary-gold);
            border-left-color: var(--dark-blue);
            font-weight: 600;
        }
        
        .sidebar .nav-link i {
            margin-right: 0.5rem;
            width: 20px;
            text-align: center;
        }
        
        .sidebar-logo {
            text-align: center;
            margin-bottom: 1rem;
            padding: 1rem;
        }
        
        .logo-text {
            font-size: 1.5rem;
            font-weight: 900;
            color: white;
            letter-spacing: 2px;
            line-height: 1.2;
        }
        
        .logo-text span {
            color: var(--secondary-gold);
        }
        
        .logo-tagline {
            font-size: 0.65rem;
            color: var(--secondary-gold);
            letter-spacing: 1px;
        }
        
        /* Main Content Styles */
        .main-content {
            margin-left: 0;
            width: 100%;
            transition: all 0.3s;
            flex: 1 0 auto;
            padding-top: 56px;
        }
        
        @media (min-width: 992px) {
            .sidebar {
                left: 0;
            }
            .main-content {
                margin-left: 250px;
                width: calc(100% - 250px);
            }
        }
        
        /* Card Styles */
        .card {
            border: none;
            border-radius: 12px;
            box-shadow: 0 0.5rem 1rem rgba(26, 75, 140, 0.1);
            margin-bottom: 1.5rem;
            transition: transform 0.3s, box-shadow 0.3s;
            border: 1px solid rgba(255, 215, 0, 0.2);
        }
        
        .card:hover {
            transform: translateY(-5px);
            box-shadow: 0 1rem 2rem rgba(26, 75, 140, 0.15);
            border-color: var(--secondary-gold);
        }
        
        .card-header {
            background: linear-gradient(135deg, var(--primary-blue), var(--dark-blue));
            border-bottom: 2px solid var(--secondary-gold);
            font-weight: 700;
            color: white;
            padding: 1rem 1.5rem;
        }
        
        .card-header h6 {
            margin: 0;
            color: white;
        }
        
        /* Button Styles */
        .btn-primary {
            background: linear-gradient(135deg, var(--primary-blue), var(--dark-blue));
            border-color: var(--secondary-gold);
            padding: 0.5rem 1.5rem;
            font-weight: 600;
            color: white;
        }
        
        .btn-primary:hover {
            background: linear-gradient(135deg, var(--secondary-gold), #e6b800);
            border-color: var(--dark-blue);
            color: var(--dark-blue);
        }
        
        .btn-success {
            background: linear-gradient(135deg, #28a745, #218838);
            border-color: var(--secondary-gold);
            color: white;
        }
        
        .btn-success:hover {
            background: linear-gradient(135deg, var(--secondary-gold), #e6b800);
            color: var(--dark-blue);
        }
        
        .btn-danger {
            background-color: #dc3545;
            border-color: #dc3545;
        }
        
        .btn-danger:hover {
            background-color: #c82333;
            border-color: #bd2130;
        }
        
        /* Form Styles */
        .form-control, .form-select {
            height: 45px;
            border-radius: 8px;
            padding: 0.5rem 1rem;
            border: 1px solid #ced4da;
            transition: all 0.3s;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: var(--secondary-gold);
            box-shadow: 0 0 0 0.25rem rgba(255, 215, 0, 0.25);
        }
        
        .form-label {
            font-weight: 600;
            color: var(--dark-blue);
        }
        
        .form-label i {
            color: var(--secondary-gold);
        }
        
        /* Table Styles */
        .table-responsive {
            overflow-x: auto;
        }
        
        .table {
            margin-bottom: 0;
        }
        
        .table thead {
            background: linear-gradient(135deg, var(--light-blue), var(--primary-blue));
            color: white;
        }
        
        .table thead th {
            font-weight: 600;
            border-bottom: 2px solid var(--secondary-gold);
            white-space: nowrap;
        }
        
        .table tbody tr:hover {
            background-color: var(--light-gold);
        }
        
        .score-input {
            width: 70px;
            text-align: center;
            border: 1px solid #ced4da;
            border-radius: 4px;
            padding: 0.25rem;
        }
        
        .score-input:focus {
            border-color: var(--secondary-gold);
            outline: none;
            box-shadow: 0 0 0 0.2rem rgba(255, 215, 0, 0.25);
        }
        
        /* Admin Info Styles */
        .admin-info {
            display: flex;
            align-items: center;
            background-color: rgba(255, 215, 0, 0.2);
            padding: 8px 12px;
            border-radius: 8px;
            color: white;
        }
        
        .admin-name {
            margin-right: 5px;
            font-weight: 600;
        }
        
        .admin-access {
            font-style: italic;
            opacity: 0.8;
            margin-right: 10px;
            font-size: 0.9rem;
        }
        
        .admin-icon {
            font-size: 1.5rem;
            color: var(--secondary-gold);
        }
        
        /* Footer styles */
        .footer {
            background: linear-gradient(135deg, var(--dark-blue), var(--primary-blue));
            color: white;
            padding: 20px 0;
            flex-shrink: 0;
            width: 100%;
            border-top: 2px solid var(--secondary-gold);
        }
        
        @media (min-width: 992px) {
            .footer {
                margin-left: 250px;
                width: calc(100% - 250px);
            }
        }
        
        .copyright-text {
            font-weight: 600;
            font-size: 1rem;
        }
        
        .copyright-text i {
            color: var(--secondary-gold);
        }
        
        /* Support badge */
        .support-badge {
            background: linear-gradient(135deg, var(--secondary-gold), #e6b800);
            color: var(--dark-blue);
            font-weight: 600;
            padding: 0.5rem 1rem;
            border: 1px solid var(--dark-blue);
        }
        
        /* Breadcrumbs */
        .breadcrumb-custom .breadcrumb {
            background-color: transparent;
            padding: 0;
        }
        
        .breadcrumb-custom .breadcrumb-item a {
            color: var(--primary-blue);
            text-decoration: none;
            font-weight: 500;
        }
        
        .breadcrumb-custom .breadcrumb-item a:hover {
            color: var(--secondary-gold);
        }
        
        .breadcrumb-custom .breadcrumb-item.active {
            color: var(--dark-blue);
            font-weight: 600;
        }
        
        .breadcrumb-item + .breadcrumb-item::before {
            color: var(--secondary-gold);
        }
        
        /* Search Form */
        .search-form {
            background-color: #f8f9fa;
            padding: 1.5rem;
            border-radius: 8px;
            margin-bottom: 1.5rem;
            border-left: 4px solid var(--secondary-gold);
        }
        
        .info-box {
            background-color: var(--light-gold);
            border-left: 4px solid var(--secondary-gold);
            padding: 1rem;
            border-radius: 8px;
            margin-bottom: 1.5rem;
        }
        
        /* Page heading */
        .text-gray-800 {
            color: var(--dark-blue);
            font-weight: 700;
        }
        
        /* Branch Switcher */
        .branch-switcher {
            background: rgba(255,255,255,0.1);
            padding: 0.25rem 0.5rem;
            border-radius: 4px;
            margin-left: 1rem;
        }
        
        .branch-switcher select {
            background: white;
            border: 1px solid var(--secondary-gold);
            border-radius: 4px;
            padding: 0.25rem;
            font-size: 0.8rem;
        }
    </style>
</head>

<body>
    <!-- Top Navigation -->
    <nav class="navbar navbar-expand-lg navbar-dark">
        <div class="container-fluid">
            <button id="sidebarToggle" class="btn btn-link d-lg-none me-2">
                <i class="fas fa-bars" style="color: white;"></i>
            </button>
            <a class="navbar-brand d-none d-lg-block" href="#">
                <img src="../<?php echo $schoolLogo; ?>" alt="<?php echo $schoolName; ?>" height="35" style="border-radius: 4px;" onerror="this.src='coll_logo.png';">
                <?php echo $schoolShortName ?: substr($schoolName, 0, 20); ?>
            </a>
            
            <!-- Branch Switcher (visible on desktop) -->
            <?php if (count($allBranches) > 1): ?>
            <div class="d-none d-lg-block branch-switcher">
                <form method="get" class="d-flex align-items-center">
                    <span class="text-white me-2 small">Branch:</span>
                    <select name="branch" class="form-select form-select-sm" style="width: auto;" onchange="this.form.submit()">
                        <option value="" style="color: #333;">Select</option>
                        <?php foreach ($allBranches as $branch): ?>
                        <option value="<?php echo $branch['branch_code']; ?>" style="color: #333;" 
                                <?php echo ($branchCode == $branch['branch_code']) ? 'selected' : ''; ?>>
                            <?php echo $branch['branch_code']; ?> - <?php echo substr($branch['branch_name'], 0, 10); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </form>
            </div>
            <?php endif; ?>
            
            <div class="ms-auto d-flex align-items-center">
                <div class="admin-info me-3">
                    <span class="admin-name"><?php echo htmlspecialchars($admin_fullname ?: 'Admin'); ?></span>
                    <span class="admin-access">(Administrator)</span>
                    <?php if ($branchCode): ?>
                    <span class="branch-badge ms-2"><?php echo strtoupper($branchCode); ?></span>
                    <?php endif; ?>
                    <i class="fas fa-user-circle admin-icon ms-2"></i>
                </div>
                <a href="logout.php" class="btn btn-sm btn-outline-light" style="border-color: var(--secondary-gold); color: var(--secondary-gold);">
                    <i class="fas fa-sign-out-alt"></i>
                </a>
            </div>
        </div>
    </nav>

    <!-- Sidebar -->
    <nav id="sidebar" class="sidebar">
        <div class="position-sticky pt-3">
            <div class="sidebar-logo d-none d-lg-block">
                <div class="logo-text">
                    <?php 
                        $words = explode(' ', $schoolName);
                        $initials = '';
                        foreach ($words as $word) {
                            if (!empty($word)) $initials .= strtoupper(substr($word, 0, 1));
                        }
                        echo substr($initials, 0, 2) . '.<span>' . (isset($initials[2]) ? substr($initials, 2, 1) : 'S') . '</span>';
                    ?>
                </div>
                <div class="logo-tagline">
                    <?php echo $schoolMotto; ?>
                </div>
                <hr style="border-color: var(--secondary-gold); opacity: 0.3;">
                <p class="text-white small px-2">
                    <i class="fas fa-map-marker-alt" style="color: var(--secondary-gold);"></i><br>
                    <?php echo $schoolAddress; ?>
                </p>
            </div>
            
            <ul class="nav flex-column">
                <li class="nav-item">
                    <a class="nav-link" href="main.php<?php echo $branchCode ? '?branch='.$branchCode : ''; ?>">
                        <i class="fas fa-fw fa-tachometer-alt"></i>
                        Admin Centre
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="post_session.php<?php echo $branchCode ? '?branch='.$branchCode : ''; ?>">
                        <i class="fas fa-fw fa-calendar-alt"></i>
                        School Year/Session
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="post_classes.php<?php echo $branchCode ? '?branch='.$branchCode : ''; ?>">
                        <i class="fas fa-fw fa-building"></i>
                        Manage Classes
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="add_students.php<?php echo $branchCode ? '?branch='.$branchCode : ''; ?>">
                        <i class="fas fa-fw fa-user-plus"></i>
                        Register New Student
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="post_subjects.php<?php echo $branchCode ? '?branch='.$branchCode : ''; ?>">
                        <i class="fas fa-fw fa-book"></i>
                        Create Subjects
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="teachers.php<?php echo $branchCode ? '?branch='.$branchCode : ''; ?>">
                        <i class="fas fa-fw fa-chalkboard-teacher"></i>
                        Manage Teachers
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="students.php<?php echo $branchCode ? '?branch='.$branchCode : ''; ?>">
                        <i class="fas fa-fw fa-users"></i>
                        Manage Students
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="deactivate_students.php<?php echo $branchCode ? '?branch='.$branchCode : ''; ?>">
                        <i class="fas fa-fw fa-user-lock"></i>
                        Activate/Deactivate
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link active" href="edit_scores_subject.php<?php echo $branchCode ? '?branch='.$branchCode : ''; ?>">
                        <i class="fas fa-fw fa-edit"></i>
                        Edit Subject Scores
                    </a>
                </li>
                <li class="nav-item mt-3">
                    <a class="nav-link" href="portal_settings.php<?php echo $branchCode ? '?branch='.$branchCode : ''; ?>">
                        <i class="fas fa-fw fa-cog" style="color: var(--secondary-gold);"></i>
                        <span style="color: var(--secondary-gold);">Portal Settings</span>
                    </a>
                </li>
            </ul>
        </div>
    </nav>

    <!-- Main Content -->
    <main class="main-content">
        <div class="container-fluid px-4 pt-4">
            <!-- Page Heading -->
            <div class="d-sm-flex align-items-center justify-content-between mb-4">
                <h1 class="h3 mb-0 text-gray-800">
                    <i class="fas fa-edit me-2" style="color: var(--secondary-gold);"></i>
                    Edit Subject Scores
                    <?php if ($branchCode): ?>
                    <span class="branch-badge ms-2"><?php echo strtoupper($branchCode); ?></span>
                    <?php endif; ?>
                </h1>
                <div class="d-none d-sm-inline-block">
                    <span class="badge support-badge p-2">
                        <i class="fas fa-phone-alt me-1"></i> Support: <?php echo $supportPhone; ?>
                    </span>
                </div>
            </div>

            <!-- Mobile Branch Switcher -->
            <?php if (count($allBranches) > 1): ?>
            <div class="d-lg-none mb-3">
                <div class="card">
                    <div class="card-body py-2">
                        <form method="get" class="d-flex align-items-center">
                            <label class="me-2 mb-0"><i class="fas fa-school"></i></label>
                            <select name="branch" class="form-select form-select-sm" onchange="this.form.submit()">
                                <option value="">Select Branch</option>
                                <?php foreach ($allBranches as $branch): ?>
                                <option value="<?php echo $branch['branch_code']; ?>" 
                                        <?php echo ($branchCode == $branch['branch_code']) ? 'selected' : ''; ?>>
                                    <?php echo $branch['branch_name']; ?> (<?php echo $branch['branch_code']; ?>)
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </form>
                    </div>
                </div>
            </div>
            <?php endif; ?>

            <!-- Breadcrumbs -->
            <div class="breadcrumb-custom mb-4">
                <nav aria-label="breadcrumb">
                    <ol class="breadcrumb mb-0">
                        <li class="breadcrumb-item"><a href="main.php<?php echo $branchCode ? '?branch='.$branchCode : ''; ?>">Admin Dashboard</a></li>
                        <li class="breadcrumb-item active">Edit Subject Scores</li>
                    </ol>
                </nav>
            </div>

            <!-- Success/Error Messages -->
            <?php if (isset($success_message)): ?>
                <div class="alert alert-success alert-dismissible fade show" role="alert">
                    <i class="fas fa-check-circle me-2"></i><?php echo $success_message; ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
            <?php endif; ?>

            <?php if (isset($error_message)): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <i class="fas fa-exclamation-circle me-2"></i><?php echo $error_message; ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
            <?php endif; ?>

            <!-- Search Form -->
            <div class="card shadow mb-4">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold">
                        <i class="fas fa-search me-2" style="color: var(--secondary-gold);"></i>
                        Select Criteria
                    </h6>
                </div>
                <div class="card-body">
                    <form method="POST" class="search-form">
                        <div class="row g-3">
                            <div class="col-md-3">
                                <label class="form-label">
                                    <i class="fas fa-building me-2"></i>Class
                                </label>
                                <select name="class" class="form-select" required>
                                    <option value="">Select Class</option>
                                    <?php foreach ($classes as $class_option): ?>
                                        <option value="<?php echo $class_option; ?>" <?php echo ($class_option == $class) ? 'selected' : ''; ?>>
                                            <?php echo $class_option; ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="col-md-2">
                                <label class="form-label">
                                    <i class="fas fa-calendar-alt me-2"></i>Term
                                </label>
                                <select name="term" class="form-select" required>
                                    <option value="">Select Term</option>
                                    <?php foreach ($terms as $term_option): ?>
                                        <option value="<?php echo $term_option; ?>" <?php echo ($term_option == $term) ? 'selected' : ''; ?>>
                                            <?php echo $term_option; ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="col-md-2">
                                <label class="form-label">
                                    <i class="fas fa-calendar me-2"></i>Year
                                </label>
                                <select name="year" class="form-select" required>
                                    <option value="">Select Year</option>
                                    <?php foreach ($years as $year_option): ?>
                                        <option value="<?php echo $year_option; ?>" <?php echo ($year_option == $year) ? 'selected' : ''; ?>>
                                            <?php echo $year_option; ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="col-md-3">
                                <label class="form-label">
                                    <i class="fas fa-book me-2"></i>Subject
                                </label>
                                <select name="subject" class="form-select" required>
                                    <option value="">Select Subject</option>
                                    <?php foreach ($subjects as $subject_option): ?>
                                        <option value="<?php echo $subject_option; ?>" <?php echo ($subject_option == $subject) ? 'selected' : ''; ?>>
                                            <?php echo $subject_option; ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="col-md-2 d-flex align-items-end">
                                <button type="submit" class="btn btn-primary w-100">
                                    <i class="fas fa-search me-2"></i>Search
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Results Section -->
            <?php if (!empty($score_records)): ?>
                <div class="info-box">
                    <div class="row">
                        <div class="col-md-4">
                            <strong><i class="fas fa-book me-2"></i>Subject:</strong> <?php echo $subject_name; ?>
                        </div>
                        <div class="col-md-4">
                            <strong><i class="fas fa-users me-2"></i>Total Students:</strong> <?php echo $total_results_count; ?>
                        </div>
                        <div class="col-md-4">
                            <strong><i class="fas fa-calendar-alt me-2"></i>Session:</strong> <?php echo "$class | $term | $year"; ?>
                        </div>
                    </div>
                </div>

                <div class="card shadow mb-4">
                    <div class="card-header py-3">
                        <h6 class="m-0 font-weight-bold">
                            <i class="fas fa-list me-2" style="color: var(--secondary-gold);"></i>
                            Student Scores - <?php echo $subject_name; ?>
                        </h6>
                    </div>
                    <div class="card-body">
                        <form method="POST">
                            <input type="hidden" name="class" value="<?php echo $class; ?>">
                            <input type="hidden" name="term" value="<?php echo $term; ?>">
                            <input type="hidden" name="year" value="<?php echo $year; ?>">
                            <input type="hidden" name="subject" value="<?php echo $subject; ?>">
                            
                            <div class="table-responsive">
                                <table class="table table-hover" id="scoresTable">
                                    <thead>
                                        <tr>
                                            <th>S/N</th>
                                            <th>Student Name</th>
                                            <th>Admission No.</th>
                                            <th>CA1 (Test 1)</th>
                                            <th>CA2 (Test 2)</th>
                                            <th>Exam</th>
                                            <th>Total</th>
                                            <th>Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($score_records as $index => $record): ?>
                                            <tr>
                                                <td><?php echo $index + 1; ?></td>
                                                <td><?php echo htmlspecialchars($record['name']); ?></td>
                                                <td><?php echo htmlspecialchars($record['registration_no']); ?></td>
                                                <td>
                                                    <input type="number" name="test1[]" class="score-input" 
                                                           value="<?php echo $record['test1']; ?>" min="0" max="40" required>
                                                </td>
                                                <td>
                                                    <input type="number" name="test2[]" class="score-input" 
                                                           value="<?php echo $record['test2']; ?>" min="0" max="40" required>
                                                </td>
                                                <td>
                                                    <input type="number" name="exam[]" class="score-input" 
                                                           value="<?php echo $record['exam']; ?>" min="0" max="100" required>
                                                </td>
                                                <td><strong><?php echo $record['total']; ?></strong></td>
                                                <td>
                                                    <input type="hidden" name="record_id[]" value="<?php echo $record['id']; ?>">
                                                    <a href="delete_result_subject.php?record_id=<?php echo $record['id']; ?><?php echo $branchCode ? '&branch='.$branchCode : ''; ?>" 
                                                       class="btn btn-sm btn-danger" 
                                                       onclick="return confirm('Are you sure you want to delete this record?')">
                                                        <i class="fas fa-trash-alt"></i>
                                                    </a>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                            
                            <div class="text-center mt-4">
                                <button type="submit" name="update_results" class="btn btn-success btn-lg px-5">
                                    <i class="fas fa-save me-2"></i>Save Updated Results
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            <?php elseif ($_SERVER["REQUEST_METHOD"] == "POST" && !isset($_POST['update_results'])): ?>
                <div class="alert alert-warning">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    No records found for the selected criteria.
                </div>
            <?php endif; ?>
        </div>
    </main>

    <!-- Footer -->
    <footer class="footer">
        <div class="container-fluid">
            <div class="row align-items-center">
                <div class="col-md-6">
                    <span class="copyright-text">
                        <i class="fas fa-copyright me-1"></i> <?php echo $footerCopyright; ?> <?php echo date("Y"); ?>
                        <?php if ($branchCode): ?>
                        <span class="branch-badge ms-2"><?php echo strtoupper($branchCode); ?></span>
                        <?php endif; ?>
                    </span>
                </div>
                <div class="col-md-6">
                    <div class="text-md-end">
                        <a href="<?php echo $developerWebsite; ?>" target="_blank" rel="noopener noreferrer" style="color: var(--secondary-gold); text-decoration: none;">
                            <span>Powered by <?php echo $developerName; ?></span>
                            <img src="datalogo.png" alt="<?php echo $developerName; ?> Logo" class="ms-2" height="24" style="filter: brightness(0) invert(1);" onerror="this.style.display='none';">
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </footer>

    <!-- Bootstrap 5 JS Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    
    <!-- DataTables -->
    <script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap5.min.js"></script>
    
    <!-- Custom Scripts -->
    <script>
        // Toggle sidebar on mobile
        document.getElementById('sidebarToggle').addEventListener('click', function() {
            document.getElementById('sidebar').classList.toggle('active');
            document.querySelector('.main-content').classList.toggle('active');
        });
        
        $(document).ready(function() {
            // Initialize DataTable if there are records
            if ($('#scoresTable tbody tr').length > 0) {
                $('#scoresTable').DataTable({
                    pageLength: 25,
                    order: [[0, 'asc']],
                    language: {
                        search: "<i class='fas fa-search me-2'></i>Search:",
                        lengthMenu: "Show _MENU_ entries",
                        info: "Showing _START_ to _END_ of _TOTAL_ students",
                        paginate: {
                            first: '<i class="fas fa-angle-double-left"></i>',
                            last: '<i class="fas fa-angle-double-right"></i>',
                            next: '<i class="fas fa-angle-right"></i>',
                            previous: '<i class="fas fa-angle-left"></i>'
                        }
                    }
                });
            }
            
            // Auto-hide alerts after 5 seconds
            setTimeout(function() {
                $('.alert').fadeOut('slow');
            }, 5000);
            
            // Validate score inputs
            $('.score-input').on('input', function() {
                var value = parseInt($(this).val());
                var max = $(this).attr('max');
                var min = $(this).attr('min');
                
                if (value > max) {
                    $(this).val(max);
                } else if (value < min) {
                    $(this).val(min);
                }
            });
        });
    </script>
</body>
</html>