<?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');
session_start();

// 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';

// Check if the user is logged in
if (isset($_SESSION['SESS_ID_ADMIN'])) {
    $userId = $_SESSION['SESS_ID_ADMIN'];

    // Fetch user details based on the ID
    $query = "SELECT * FROM tbl_admin WHERE id = :id";
    $stmt = $DBH->prepare($query);
    $stmt->bindParam(':id', $userId, PDO::PARAM_INT);
    $stmt->execute();

    if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $adminName = $row['username'];
    }
}

// Fetch dynamic options for class, term, year, and subject from the database
$classes = sql($DBH, "SELECT DISTINCT class FROM tbl_student_results ORDER BY class", [], "rows");
$terms = sql($DBH, "SELECT DISTINCT term FROM tbl_student_results ORDER BY term", [], "rows");
$years = sql($DBH, "SELECT DISTINCT year FROM tbl_student_results ORDER BY year DESC", [], "rows");
$subjects = sql($DBH, "SELECT DISTINCT subject FROM tbl_student_results ORDER BY subject", [], "rows");

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

// Initialize variables to store class, term, and year for display
$page_title = '';
$subject_name = '';
$total_results_count = 0;
$class = $_POST['class'] ?? '';
$term = $_POST['term'] ?? '';
$year = $_POST['year'] ?? '';
$subject = $_POST['subject'] ?? '';
$score_records = [];

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
    $score_records = sql($DBH, 
        "SELECT * FROM tbl_student_results 
         WHERE class = ? AND term = ? AND year = ? AND subject = ? 
         ORDER BY name",
        [$class, $term, $year, $subject], 
        "rows"
    );

    // 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
    $class = strip_tags($_POST['class']);
    $term = strip_tags($_POST['term']);
    $year = strip_tags($_POST['year']);
    $subject = strip_tags($_POST['subject']);
    $record_ids = $_POST['record_id'];
    $test1_scores = $_POST['test1'];
    $test2_scores = $_POST['test2'];
    $exam_scores = $_POST['exam'];

    // Update the records in the database
    $update_query = "UPDATE tbl_student_results SET test1 = ?, test2 = ?, exam = ?, total = (test1 + test2 + exam) WHERE id = ?";
    
    $success_count = 0;
    $error_messages = [];
    
    foreach ($record_ids as $index => $record_id) {
        $test1 = floatval($test1_scores[$index]);
        $test2 = floatval($test2_scores[$index]);
        $exam = floatval($exam_scores[$index]);
        
        // Validate scores
        if ($test1 >= 0 && $test2 >= 0 && $exam >= 0) {
            $stmt = $DBH->prepare($update_query);
            if ($stmt->execute([$test1, $test2, $exam, $record_id])) {
                $success_count++;
            } else {
                $error_messages[] = "Failed to update record ID: $record_id";
            }
        } else {
            $error_messages[] = "Invalid score values for record ID: $record_id";
        }
    }

    // Refresh the records after update
    $score_records = sql($DBH, 
        "SELECT * FROM tbl_student_results 
         WHERE class = ? AND term = ? AND year = ? AND subject = ? 
         ORDER BY name",
        [$class, $term, $year, $subject], 
        "rows"
    );
    
    $total_results_count = count($score_records);
    
    if ($success_count > 0 && empty($error_messages)) {
        $success_message = "Successfully updated $success_count scores for $subject - $class, $term, $year";
    } elseif (!empty($error_messages)) {
        $error_message = implode("<br>", $error_messages);
    } else {
        $error_message = "No scores were updated.";
    }
}
?>

<!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 - Poppins -->
  <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
  
  <!-- Custom CSS -->
  <style>
    :root {
      --primary-blue: #1a4b8c;    /* Royal Blue */
      --secondary-gold: #FFD700;    /* Gold */
      --dark-blue: #0f2b4f;         /* Dark Blue */
      --light-blue: #4a7db5;         /* Medium Blue */
      --light-gold: #FFF1B8;          /* Light Gold */
      --bg-light: #f5f9ff;
    }
    
    body {
      font-family: 'Poppins', sans-serif;
      background-color: var(--bg-light);
      padding-top: 56px;
      color: #333;
      font-size: 0.9rem;
    }
    
    /* 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: 0;
      width: 250px;
      height: calc(100vh - 56px);
      transition: all 0.3s;
      z-index: 1000;
      overflow-y: auto;
      border-right: 3px solid var(--secondary-gold);
    }
    
    .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: 250px;
      width: calc(100% - 250px);
      transition: all 0.3s;
      min-height: calc(100vh - 56px);
      padding-bottom: 60px;
    }
    
    @media (max-width: 991.98px) {
      .sidebar {
        left: -250px;
      }
      .main-content {
        margin-left: 0;
        width: 100%;
      }
      body {
        padding-top: 56px;
      }
    }
    
    /* Welcome banner */
    .welcome-banner {
      background: linear-gradient(135deg, var(--primary-blue), var(--light-blue));
      color: white;
      border-radius: 0.5rem;
      padding: 0.75rem 1rem;
      margin: 1rem;
      box-shadow: 0 4px 6px rgba(0,0,0,0.1);
      border-left: 5px solid var(--secondary-gold);
    }
    
    /* 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;
    }
    
    /* Form Styles */
    .form-container {
      background-color: white;
      border-radius: 0.5rem;
      padding: 1rem;
      margin: 1rem;
      box-shadow: 0 0.15rem 1.75rem 0 rgba(26, 75, 140, 0.1);
      border: 1px solid rgba(255, 215, 0, 0.2);
    }
    
    /* Table Styles */
    .table-container {
      background-color: white;
      border-radius: 0.5rem;
      padding: 1rem;
      margin: 1rem;
      box-shadow: 0 0.15rem 1.75rem 0 rgba(26, 75, 140, 0.1);
      overflow-x: auto;
      border: 1px solid rgba(255, 215, 0, 0.2);
    }
    
    .scores-table {
      width: 100%;
      border-collapse: collapse;
      font-size: 0.85rem;
    }
    
    .scores-table th,
    .scores-table td {
      padding: 0.5rem;
      border: 1px solid #dee2e6;
      text-align: center;
      vertical-align: middle;
    }
    
    .scores-table th {
      background: linear-gradient(135deg, var(--primary-blue), var(--dark-blue));
      color: white;
      font-weight: 600;
      position: sticky;
      top: 0;
      z-index: 10;
    }
    
    .scores-table th i {
      color: var(--secondary-gold);
    }
    
    .scores-table input {
      width: 70px;
      padding: 0.25rem 0.5rem;
      border: 1px solid #ced4da;
      border-radius: 0.25rem;
      text-align: center;
      font-size: 0.85rem;
      transition: all 0.2s;
    }
    
    .scores-table input:focus {
      border-color: var(--secondary-gold);
      box-shadow: 0 0 0 0.2rem rgba(255, 215, 0, 0.25);
      outline: none;
    }
    
    .scores-table .student-name {
      text-align: left;
      font-weight: 600;
      background-color: var(--light-gold);
    }
    
    .scores-table .student-name i {
      color: var(--primary-blue);
    }
    
    .scores-table .total-col {
      background-color: var(--light-gold);
      font-weight: 600;
    }
    
    .scores-table tr:nth-child(even) {
      background-color: #f9f9f9;
    }
    
    .scores-table tr:hover {
      background-color: var(--light-gold);
    }
    
    /* 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: 12px 0;
      position: fixed;
      bottom: 0;
      width: 100%;
      z-index: 100;
      font-size: 0.8rem;
      border-top: 2px solid var(--secondary-gold);
    }
    
    @media (min-width: 992px) {
      .footer {
        margin-left: 250px;
        width: calc(100% - 250px);
      }
    }
    
    @media (max-width: 991.98px) {
      .footer {
        margin-left: 0;
        width: 100%;
      }
    }
    
    .copyright-text {
      font-weight: 600;
    }
    
    .copyright-text i {
      color: var(--secondary-gold);
    }
    
    .powered-by {
      display: flex;
      align-items: center;
      justify-content: flex-end;
      color: white;
    }
    
    .powered-by img {
      height: 18px;
      margin-left: 6px;
      filter: brightness(0) invert(1);
    }
    
    .powered-by-link {
      display: flex;
      align-items: center;
      text-decoration: none;
      color: var(--secondary-gold);
      transition: opacity 0.3s ease;
    }
    
    .powered-by-link:hover {
      opacity: 0.8;
      color: white;
    }
    
    /* 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;
      margin: 1rem 1rem 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);
    }
    
    /* Action buttons */
    .btn-action {
      padding: 0.5rem 1rem;
      border-radius: 0.25rem;
      font-weight: 600;
      transition: all 0.3s;
      font-size: 0.85rem;
    }
    
    .btn-primary {
      background: linear-gradient(135deg, var(--primary-blue), var(--dark-blue));
      border-color: var(--secondary-gold);
      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);
      color: white;
      border: none;
    }
    
    .btn-success:hover {
      background: linear-gradient(135deg, #218838, #1e7e34);
    }
    
    .btn-danger {
      background-color: #dc3545;
      color: white;
      border: none;
    }
    
    .btn-danger:hover {
      background-color: #c82333;
    }
    
    .btn-secondary {
      background-color: #6c757d;
      color: white;
      border: none;
    }
    
    .btn-secondary:hover {
      background-color: #5a6268;
    }
    
    /* Alert styles */
    .alert {
      padding: 0.75rem 1rem;
      border-radius: 0.25rem;
      margin: 1rem;
    }
    
    .alert-success {
      background-color: #d4edda;
      border-color: #c3e6cb;
      color: #155724;
    }
    
    .alert-danger {
      background-color: #f8d7da;
      border-color: #f5c6cb;
      color: #721c24;
    }
    
    /* Info cards */
    .info-card {
      background: linear-gradient(135deg, var(--light-gold) 0%, #ffffff 100%);
      border-left: 4px solid var(--secondary-gold);
      padding: 0.75rem;
      margin-bottom: 0.5rem;
      border-radius: 0 0.25rem 0.25rem 0;
      color: var(--dark-blue);
    }
    
    .info-card i {
      color: var(--primary-blue);
    }
    
    /* Form elements */
    .form-select, .form-label {
      font-size: 0.85rem;
    }
    
    .form-select:focus {
      border-color: var(--secondary-gold);
      box-shadow: 0 0 0 0.25rem rgba(255, 215, 0, 0.25);
    }
    
    .form-label i {
      color: var(--secondary-gold);
    }
    
    /* Page heading */
    .text-gray-800 {
      color: var(--dark-blue);
      font-weight: 700;
    }
    
    /* Responsive */
    @media (max-width: 768px) {
      .row {
        flex-direction: column;
      }
      
      .btn-primary {
        width: 100%;
        margin-top: 0.5rem;
      }
      
      .scores-table th, .scores-table td {
        font-size: 0.8rem;
        padding: 0.25rem;
      }
      
      .scores-table input {
        width: 50px;
        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($adminName ?? '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">
          <i class="fas fa-sign-out-alt"></i> Logout
        </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 Dashboard
          </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">
          <a class="nav-link" href="download_broadsheet.php<?php echo $branchCode ? '?branch='.$branchCode : ''; ?>">
            <i class="fas fa-fw fa-file-pdf"></i>
            Result Broadsheet
          </a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="uploaded_class_results.php<?php echo $branchCode ? '?branch='.$branchCode : ''; ?>">
            <i class="fas fa-fw fa-list"></i>
            Uploaded Results
          </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">
    <!-- Welcome Banner -->
    <div class="welcome-banner">
      <div class="d-flex justify-content-between align-items-center">
        <div>
          <h4 class="mb-1"><i class="fas fa-crown me-2" style="color: var(--secondary-gold);"></i>Edit Subject Scores</h4>
          <p class="mb-0 small"><?php echo $schoolName; ?> - Admin Dashboard</p>
        </div>
        <div class="d-none d-sm-inline-block">
          <span class="badge support-badge p-1">
            <i class="fas fa-edit me-1"></i> Edit Scores
          </span>
        </div>
      </div>
    </div>

    <!-- Mobile Branch Switcher (visible only on mobile) -->
    <?php if (count($allBranches) > 1): ?>
    <div class="d-lg-none mb-3 mx-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">
      <nav aria-label="breadcrumb">
        <ol class="breadcrumb">
          <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>

    <!-- Search Form -->
    <div class="form-container">
      <form method="POST" action="">
        <?php if ($branchCode): ?>
        <input type="hidden" name="branch" value="<?php echo $branchCode; ?>">
        <?php endif; ?>
        
        <div class="row align-items-end">
          <div class="col-md-3">
            <div class="form-group mb-2">
              <label for="class" class="form-label"><i class="fas fa-building me-1"></i>Class:</label>
              <select id="class" name="class" class="form-select form-select-sm" required>
                <option value="">Select Class</option>
                <?php foreach ($classes as $classOption): ?>
                  <option value="<?php echo htmlspecialchars($classOption['class']); ?>" 
                    <?php echo ($classOption['class'] === $class) ? 'selected' : ''; ?>>
                    <?php echo htmlspecialchars($classOption['class']); ?>
                  </option>
                <?php endforeach; ?>
              </select>
            </div>
          </div>
          
          <div class="col-md-2">
            <div class="form-group mb-2">
              <label for="term" class="form-label"><i class="fas fa-calendar-alt me-1"></i>Term:</label>
              <select id="term" name="term" class="form-select form-select-sm" required>
                <option value="">Select Term</option>
                <?php foreach ($terms as $termOption): ?>
                  <option value="<?php echo htmlspecialchars($termOption['term']); ?>" 
                    <?php echo ($termOption['term'] === $term) ? 'selected' : ''; ?>>
                    <?php echo htmlspecialchars($termOption['term']); ?>
                  </option>
                <?php endforeach; ?>
              </select>
            </div>
          </div>
          
          <div class="col-md-2">
            <div class="form-group mb-2">
              <label for="year" class="form-label"><i class="fas fa-calendar me-1"></i>Year:</label>
              <select id="year" name="year" class="form-select form-select-sm" required>
                <option value="">Select Year</option>
                <?php foreach ($years as $yearOption): ?>
                  <option value="<?php echo htmlspecialchars($yearOption['year']); ?>" 
                    <?php echo ($yearOption['year'] === $year) ? 'selected' : ''; ?>>
                    <?php echo htmlspecialchars($yearOption['year']); ?>
                  </option>
                <?php endforeach; ?>
              </select>
            </div>
          </div>
          
          <div class="col-md-3">
            <div class="form-group mb-2">
              <label for="subject" class="form-label"><i class="fas fa-book me-1"></i>Subject:</label>
              <select id="subject" name="subject" class="form-select form-select-sm" required>
                <option value="">Select Subject</option>
                <?php foreach ($subjects as $subjectOption): ?>
                  <option value="<?php echo htmlspecialchars($subjectOption['subject']); ?>" 
                    <?php echo ($subjectOption['subject'] === $subject) ? 'selected' : ''; ?>>
                    <?php echo htmlspecialchars($subjectOption['subject']); ?>
                  </option>
                <?php endforeach; ?>
              </select>
            </div>
          </div>
          
          <div class="col-md-2">
            <button type="submit" class="btn btn-primary btn-sm w-100">
              <i class="fas fa-search me-1"></i> Search
            </button>
          </div>
        </div>
      </form>
    </div>

    <?php if (isset($error_message)): ?>
      <div class="alert alert-danger">
        <i class="fas fa-exclamation-circle me-2"></i> <?php echo $error_message; ?>
      </div>
    <?php endif; ?>

    <?php if (isset($success_message)): ?>
      <div class="alert alert-success">
        <i class="fas fa-check-circle me-2"></i> <?php echo $success_message; ?>
      </div>
    <?php endif; ?>

    <?php if (!empty($subject_name) && !empty($page_title)): ?>
      <div class="form-container">
        <div class="row">
          <div class="col-md-6">
            <div class="info-card">
              <h6 class="mb-1"><i class="fas fa-book me-2"></i>Subject: <strong><?php echo htmlspecialchars($subject_name); ?></strong></h6>
              <p class="mb-0 small"><?php echo htmlspecialchars($page_title); ?></p>
            </div>
          </div>
          <div class="col-md-6">
            <div class="info-card">
              <h6 class="mb-1"><i class="fas fa-users me-2"></i>Student Count: <strong><?php echo $total_results_count; ?></strong></h6>
              <p class="mb-0 small">Total records found for this selection</p>
            </div>
          </div>
        </div>
      </div>
    <?php endif; ?>

    <?php if (!empty($score_records)): ?>
      <div class="table-container">
        <form method="POST">
          <?php if ($branchCode): ?>
          <input type="hidden" name="branch" value="<?php echo $branchCode; ?>">
          <?php endif; ?>
          <input type="hidden" name="class" value="<?php echo htmlspecialchars($class); ?>">
          <input type="hidden" name="term" value="<?php echo htmlspecialchars($term); ?>">
          <input type="hidden" name="year" value="<?php echo htmlspecialchars($year); ?>">
          <input type="hidden" name="subject" value="<?php echo htmlspecialchars($subject); ?>">
          
          <div class="d-flex justify-content-between align-items-center mb-3">
            <h5 class="mb-0">
              <i class="fas fa-edit me-2" style="color: var(--secondary-gold);"></i>
              Edit Scores for <?php echo htmlspecialchars($subject); ?> 
              <small class="text-muted">(<?php echo $total_results_count; ?> students)</small>
              <?php if ($branchCode): ?>
              <span class="branch-badge ms-2"><?php echo strtoupper($branchCode); ?></span>
              <?php endif; ?>
            </h5>
            <button type="submit" name="update_results" class="btn btn-success btn-sm">
              <i class="fas fa-save me-1"></i> Save All Changes
            </button>
          </div>
          
          <div class="table-responsive">
            <table class="scores-table">
              <thead>
                <tr>
                  <th width="5%">S/N</th>
                  <th>Student Name</th>
                  <th>Admission No.</th>
                  <th><i class="fas fa-pencil-alt me-1"></i>CA1</th>
                  <th><i class="fas fa-pencil-alt me-1"></i>CA2</th>
                  <th><i class="fas fa-pencil-alt me-1"></i>Exam</th>
                  <th class="total-col"><i class="fas fa-calculator me-1"></i>Total</th>
                  <th width="10%">Action</th>
                </tr>
              </thead>
              <tbody>
                <?php foreach ($score_records as $index => $record): ?>
                  <tr>
                    <td><?php echo $index + 1; ?></td>
                    <td class="student-name"><i class="fas fa-user me-1"></i><?php echo htmlspecialchars($record['name']); ?></td>
                    <td><i class="fas fa-id-card me-1" style="color: var(--secondary-gold);"></i><?php echo htmlspecialchars($record['registration_no']); ?></td>
                    <td>
                      <input type="number" name="test1[]" value="<?php echo $record['test1']; ?>" 
                             min="0" max="100" step="0.5" required>
                    </td>
                    <td>
                      <input type="number" name="test2[]" value="<?php echo $record['test2']; ?>" 
                             min="0" max="100" step="0.5" required>
                    </td>
                    <td>
                      <input type="number" name="exam[]" value="<?php echo $record['exam']; ?>" 
                             min="0" max="100" step="0.5" required>
                    </td>
                    <td class="total-col"><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']; ?>&class=<?php echo urlencode($class); ?>&term=<?php echo urlencode($term); ?>&year=<?php echo urlencode($year); ?>&subject=<?php echo urlencode($subject); ?><?php echo $branchCode ? '&branch='.$branchCode : ''; ?>" 
                         class="btn btn-danger btn-sm py-0 px-2"
                         onclick="return confirm('Are you sure you want to delete this score record for <?php echo htmlspecialchars($record['name']); ?>?')">
                        <i class="fas fa-trash-alt"></i>
                      </a>
                    </td>
                  </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
          </div>
          
          <div class="mt-3 text-center">
            <button type="submit" name="update_results" class="btn btn-success btn-action">
              <i class="fas fa-save me-1"></i> Save All Updated Scores
            </button>
            <button type="button" class="btn btn-secondary btn-action ms-2" onclick="resetForm()">
              <i class="fas fa-undo me-1"></i> Reset Changes
            </button>
          </div>
        </form>
        
        <div class="mt-3">
          <div class="alert alert-info py-2">
            <h6 class="mb-1"><i class="fas fa-info-circle me-1" style="color: var(--secondary-gold);"></i> Instructions</h6>
            <p class="mb-0 small">
              1. Edit scores in the CA1, CA2, and Exam columns.<br>
              2. Total scores are automatically calculated as you type.<br>
              3. Click "Save All Updated Scores" to apply all changes at once.<br>
              4. Use the delete button to remove individual records.
            </p>
          </div>
        </div>
      </div>
    <?php elseif ($_SERVER["REQUEST_METHOD"] == "POST" && empty($score_records)): ?>
      <div class="form-container text-center py-4">
        <i class="fas fa-search fa-3x mb-2" style="color: var(--primary-blue);"></i>
        <h5 class="text-muted">No Records Found</h5>
        <p class="mb-0">There are no score records for the selected criteria.</p>
      </div>
    <?php else: ?>
      <div class="form-container text-center py-4">
        <i class="fas fa-edit fa-3x mb-2" style="color: var(--primary-blue);"></i>
        <h5 class="text-muted">Edit Subject Scores</h5>
        <p class="mb-0">Select a class, term, year, and subject to edit scores.</p>
      </div>
    <?php endif; ?>
  </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="powered-by">
            <a href="<?php echo $developerWebsite; ?>" target="_blank" rel="noopener noreferrer" class="powered-by-link">
              <span>Powered by <?php echo $developerName; ?></span>
              <img src="datalogo.png" alt="<?php echo $developerName; ?> Logo" 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>
  
  <!-- 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.querySelector('.footer').classList.toggle('active');
    });
    
    // Close sidebar when clicking outside on mobile
    document.addEventListener('click', function(event) {
      const sidebar = document.getElementById('sidebar');
      const sidebarToggle = document.getElementById('sidebarToggle');
      
      if (window.innerWidth < 992 && 
          !sidebar.contains(event.target) && 
          !sidebarToggle.contains(event.target) && 
          sidebar.classList.contains('active')) {
        sidebar.classList.remove('active');
        document.querySelector('.main-content').classList.remove('active');
        document.querySelector('.footer').classList.remove('active');
      }
    });
    
    // Auto-calculate total on input change
    document.querySelectorAll('input[type="number"]').forEach(input => {
      input.addEventListener('input', function() {
        const row = this.closest('tr');
        const test1 = parseFloat(row.querySelector('input[name="test1[]"]').value) || 0;
        const test2 = parseFloat(row.querySelector('input[name="test2[]"]').value) || 0;
        const exam = parseFloat(row.querySelector('input[name="exam[]"]').value) || 0;
        const totalCell = row.querySelector('.total-col');
        
        const total = test1 + test2 + exam;
        totalCell.innerHTML = '<strong>' + total.toFixed(1) + '</strong>';
      });
    });
    
    // Reset form function
    function resetForm() {
      if (confirm('Are you sure you want to reset all changes? Unsaved changes will be lost.')) {
        location.reload();
      }
    }
    
    // Focus first input field if records exist
    <?php if (!empty($score_records)): ?>
      document.addEventListener('DOMContentLoaded', function() {
        const firstInput = document.querySelector('input[type="number"]');
        if (firstInput) {
          firstInput.focus();
        }
        
        // Auto-hide alerts after 5 seconds
        setTimeout(function() {
          $('.alert').fadeOut('slow');
        }, 5000);
      });
    <?php endif; ?>
  </script>
</body>
</html>