<?php
// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

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

// Increase upload limits
ini_set('upload_max_filesize', '10M');
ini_set('post_max_size', '10M');
ini_set('max_execution_time', '300');
ini_set('max_input_time', '300');

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

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

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

// FIRST: Get the actual table structure to know what columns exist
try {
    $columns_query = "SHOW COLUMNS FROM tbl_student_results";
    $columns_stmt = $DBH->query($columns_query);
    $table_columns = [];
    $required_fields = [];
    
    while ($column = $columns_stmt->fetch(PDO::FETCH_ASSOC)) {
        $table_columns[] = $column['Field'];
        // Identify required fields without defaults
        if ($column['Null'] == 'NO' && $column['Default'] === null && $column['Field'] != 'id' && $column['Field'] != 'created_at' && $column['Field'] != 'updated_at') {
            $required_fields[] = $column['Field'];
        }
    }
    
    // Log for debugging
    error_log("Table columns: " . implode(', ', $table_columns));
    error_log("Required fields without defaults: " . implode(', ', $required_fields));
    
} catch (PDOException $e) {
    die("Error getting table structure: " . $e->getMessage());
}

// Define the fields we want to use (adjust this list based on your actual needs)
$standard_fields = [
    'name', 
    'registration_no', 
    'class', 
    'subject', 
    'year', 
    'term', 
    'teacher_no', 
    'csv_no',
    'test1', 
    'test2', 
    'exam', 
    'total'
];

// Filter to only include fields that actually exist in the table
$insert_fields = [];
$update_fields = [];
$field_defaults = [];

foreach ($standard_fields as $field) {
    if (in_array($field, $table_columns)) {
        $insert_fields[] = $field;
        $update_fields[] = "$field = ?";
    }
}

// Add any required fields that we might have missed
foreach ($required_fields as $field) {
    if (!in_array($field, $insert_fields) && $field != 'id' && $field != 'created_at' && $field != 'updated_at') {
        $insert_fields[] = $field;
        $update_fields[] = "$field = ?";
        
        // Set appropriate default values based on field name
        if (strpos($field, 'score') !== false || strpos($field, 'mark') !== false || strpos($field, 'total') !== false || strpos($field, 'test') !== false || strpos($field, 'exam') !== false) {
            $field_defaults[$field] = 0; // Numeric fields
        } elseif (strpos($field, 'date') !== false) {
            $field_defaults[$field] = date('Y-m-d'); // Date fields
        } elseif (strpos($field, 'comment') !== false || strpos($field, 'remark') !== false) {
            $field_defaults[$field] = ''; // Text fields
        } elseif (strpos($field, 'project') !== false) {
            $field_defaults[$field] = 0; // Project field - set to 0 as default
        } else {
            $field_defaults[$field] = ''; // Default empty string
        }
    }
}

// Add timestamp fields if they exist
if (in_array('created_at', $table_columns)) {
    $insert_fields[] = 'created_at';
}
if (in_array('updated_at', $table_columns)) {
    $insert_fields[] = 'updated_at';
}

error_log("Insert fields: " . implode(', ', $insert_fields));

// Process form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['upload_results'])) {
    
    $class_id = $_POST['class'];
    $term = $_POST['term'];
    $session_id = $_POST['session'];
    
    // Log the submission for debugging
    error_log("Upload Results - Class ID: $class_id, Term: $term, Session ID: $session_id");
    
    // Validate inputs
    if (empty($class_id) || empty($term) || empty($session_id)) {
        $_SESSION['error_message'] = "Please select class, term, and session";
        header("Location: ".$_SERVER['PHP_SELF'] . ($branchCode ? "?branch=" . $branchCode : ""));
        exit();
    }
    
    // Get class details
    try {
        $class_stmt = $DBH->prepare("SELECT id, class FROM tbl_class WHERE id = ?");
        $class_stmt->execute([$class_id]);
        $class_data = $class_stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$class_data) {
            throw new Exception("Class not found with ID: $class_id");
        }
        $class = $class_data['class'];
        error_log("Class found: $class");
    } catch (Exception $e) {
        $_SESSION['error_message'] = "Error getting class information: " . $e->getMessage();
        header("Location: ".$_SERVER['PHP_SELF'] . ($branchCode ? "?branch=" . $branchCode : ""));
        exit();
    }
    
    // Get teacher for this class
    try {
        $teacher_stmt = $DBH->prepare("SELECT hash, fullname FROM tbl_user WHERE class = ? AND teacher = 'true' LIMIT 1");
        $teacher_stmt->execute([$class]);
        $teacher_data = $teacher_stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$teacher_data) {
            // If no teacher assigned, use the current admin user as fallback
            $teacher_no = $_SESSION['hash'] ?? 'admin';
            $teacher_name = $_SESSION['fullname'] ?? 'Admin';
            error_log("No teacher found for class $class, using admin as fallback");
        } else {
            $teacher_no = $teacher_data['hash'];
            $teacher_name = $teacher_data['fullname'];
            error_log("Teacher found: $teacher_name");
        }
    } catch (PDOException $e) {
        $_SESSION['error_message'] = "Error getting teacher information: " . $e->getMessage();
        header("Location: ".$_SERVER['PHP_SELF'] . ($branchCode ? "?branch=" . $branchCode : ""));
        exit();
    }
    
    // Get session name
    try {
        $session_stmt = $DBH->prepare("SELECT session FROM tbl_session WHERE id = ?");
        $session_stmt->execute([$session_id]);
        $session = $session_stmt->fetchColumn();
        error_log("Session found: $session");
    } catch (PDOException $e) {
        $_SESSION['error_message'] = "Error getting session: " . $e->getMessage();
        header("Location: ".$_SERVER['PHP_SELF'] . ($branchCode ? "?branch=" . $branchCode : ""));
        exit();
    }
    
    // Check if subjects are posted
    if (!isset($_POST['subjects']) || empty($_POST['subjects'])) {
        $_SESSION['error_message'] = "No subjects selected for upload";
        header("Location: ".$_SERVER['PHP_SELF'] . ($branchCode ? "?branch=" . $branchCode : ""));
        exit();
    }
    
    $success_count = 0;
    $error_count = 0;
    $error_details = [];
    $csv_numbers = [];
    
    foreach ($_POST['subjects'] as $index => $subject_data) {
        $subject_id = $subject_data['subject_id'];
        $csv_no = mt_rand(100000, 999999);
        $csv_numbers[$subject_id] = $csv_no;
        
        error_log("Processing subject index $index, subject_id: $subject_id");
        
        // Check if file was uploaded
        if (!isset($_FILES['subjects']['tmp_name'][$index]['file']) || 
            empty($_FILES['subjects']['tmp_name'][$index]['file']) ||
            !is_uploaded_file($_FILES['subjects']['tmp_name'][$index]['file'])) {
            
            $error_details[] = "No file uploaded or upload failed for subject row " . ($index + 1);
            $error_count++;
            continue;
        }
        
        $file_tmp = $_FILES['subjects']['tmp_name'][$index]['file'];
        $file_name = $_FILES['subjects']['name'][$index]['file'];
        $file_size = $_FILES['subjects']['size'][$index]['file'];
        $file_error = $_FILES['subjects']['error'][$index]['file'];
        
        error_log("File: $file_name, Size: $file_size, Error: $file_error");
        
        // Check for upload errors
        if ($file_error !== UPLOAD_ERR_OK) {
            $upload_errors = [
                UPLOAD_ERR_INI_SIZE => "File exceeds upload_max_filesize",
                UPLOAD_ERR_FORM_SIZE => "File exceeds MAX_FILE_SIZE directive",
                UPLOAD_ERR_PARTIAL => "File was only partially uploaded",
                UPLOAD_ERR_NO_FILE => "No file was uploaded",
                UPLOAD_ERR_NO_TMP_DIR => "Missing temporary folder",
                UPLOAD_ERR_CANT_WRITE => "Failed to write file to disk",
                UPLOAD_ERR_EXTENSION => "File upload stopped by extension"
            ];
            $error_msg = $upload_errors[$file_error] ?? "Unknown upload error";
            $error_details[] = "Upload error for subject " . ($index + 1) . ": $error_msg";
            $error_count++;
            continue;
        }
        
        // Get subject name
        try {
            $subject_stmt = $DBH->prepare("SELECT subject FROM tbl_subject WHERE id = ?");
            $subject_stmt->execute([$subject_id]);
            $subject = $subject_stmt->fetchColumn();
            
            if (!$subject) {
                throw new Exception("Subject not found with ID: $subject_id");
            }
            error_log("Subject found: $subject");
        } catch (PDOException $e) {
            $error_details[] = "Error getting subject name for row " . ($index + 1) . ": " . $e->getMessage();
            $error_count++;
            continue;
        }
        
        // Process the file
        try {
            $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
            error_log("File extension: $file_ext");
            
            if (!in_array($file_ext, ['csv', 'tsv', 'txt'])) {
                $error_details[] = "Unsupported file type for subject " . ($index + 1) . ": $file_ext. Only CSV and TSV files are supported.";
                $error_count++;
                continue;
            }
            
            $delimiter = ($file_ext === 'tsv') ? "\t" : ",";
            
            if (($handle = fopen($file_tmp, "r")) !== FALSE) {
                $row_num = 0;
                $records_processed = 0;
                
                while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
                    $row_num++;
                    
                    // Skip header row if needed
                    if ($row_num == 1 && (strtolower(trim($data[0])) == 'name' || strtolower(trim($data[0])) == 'student name')) {
                        continue;
                    }
                    
                    // Clean and validate data
                    if (count($data) < 5) {
                        $error_details[] = "Row $row_num in '$file_name' has insufficient columns. Found " . count($data) . ", expected at least 5.";
                        continue;
                    }
                    
                    $name = trim($data[0] ?? '');
                    $registration_no = trim($data[1] ?? '');
                    $test1 = isset($data[2]) && is_numeric(trim($data[2])) ? floatval(trim($data[2])) : 0;
                    $test2 = isset($data[3]) && is_numeric(trim($data[3])) ? floatval(trim($data[3])) : 0;
                    $exam = isset($data[4]) && is_numeric(trim($data[4])) ? floatval(trim($data[4])) : 0;
                    
                    if (empty($name) || empty($registration_no)) {
                        $error_details[] = "Row $row_num in '$file_name' has missing name or registration number";
                        continue;
                    }
                    
                    // Validate scores (adjust max values as needed)
                    if ($test1 > 40 || $test2 > 40 || $exam > 100) {
                        $error_details[] = "Row $row_num in '$file_name' has scores exceeding maximum limits (Test max: 40, Exam max: 100)";
                        continue;
                    }
                    
                    try {
                        // Check if record exists
                        $check_stmt = $DBH->prepare("SELECT id FROM tbl_student_results 
                                                    WHERE registration_no = ? 
                                                    AND class = ? 
                                                    AND subject = ? 
                                                    AND term = ? 
                                                    AND year = ?");
                        $check_stmt->execute([$registration_no, $class, $subject, $term, $session]);
                        $existing_record = $check_stmt->fetch(PDO::FETCH_ASSOC);
                        
                        $total = $test1 + $test2 + $exam;
                        
                        if ($existing_record) {
                            // Build dynamic UPDATE query
                            $update_values = [];
                            $update_parts = [];
                            
                            // Add standard fields
                            if (in_array('name', $table_columns)) {
                                $update_parts[] = "name = ?";
                                $update_values[] = $name;
                            }
                            if (in_array('test1', $table_columns)) {
                                $update_parts[] = "test1 = ?";
                                $update_values[] = $test1;
                            }
                            if (in_array('test2', $table_columns)) {
                                $update_parts[] = "test2 = ?";
                                $update_values[] = $test2;
                            }
                            if (in_array('exam', $table_columns)) {
                                $update_parts[] = "exam = ?";
                                $update_values[] = $exam;
                            }
                            if (in_array('total', $table_columns)) {
                                $update_parts[] = "total = ?";
                                $update_values[] = $total;
                            }
                            if (in_array('teacher_no', $table_columns)) {
                                $update_parts[] = "teacher_no = ?";
                                $update_values[] = $teacher_no;
                            }
                            if (in_array('csv_no', $table_columns)) {
                                $update_parts[] = "csv_no = ?";
                                $update_values[] = $csv_no;
                            }
                            
                            // Add required fields with defaults
                            foreach ($required_fields as $field) {
                                if (!in_array($field, ['id', 'created_at', 'updated_at']) && !in_array($field, ['name', 'test1', 'test2', 'exam', 'total', 'teacher_no', 'csv_no'])) {
                                    $update_parts[] = "$field = ?";
                                    $update_values[] = $field_defaults[$field] ?? 0;
                                }
                            }
                            
                            if (in_array('updated_at', $table_columns)) {
                                $update_parts[] = "updated_at = NOW()";
                            }
                            
                            // Add ID for WHERE clause
                            $update_values[] = $existing_record['id'];
                            
                            $update_query = "UPDATE tbl_student_results SET " . implode(", ", $update_parts) . " WHERE id = ?";
                            
                            error_log("Update query: $update_query");
                            
                            $stmt = $DBH->prepare($update_query);
                            $stmt->execute($update_values);
                            error_log("Updated record for $registration_no");
                            
                        } else {
                            // Build dynamic INSERT query
                            $insert_fields_list = [];
                            $insert_placeholders = [];
                            $insert_values = [];
                            
                            // Add standard fields
                            if (in_array('name', $table_columns)) {
                                $insert_fields_list[] = 'name';
                                $insert_placeholders[] = '?';
                                $insert_values[] = $name;
                            }
                            if (in_array('registration_no', $table_columns)) {
                                $insert_fields_list[] = 'registration_no';
                                $insert_placeholders[] = '?';
                                $insert_values[] = $registration_no;
                            }
                            if (in_array('class', $table_columns)) {
                                $insert_fields_list[] = 'class';
                                $insert_placeholders[] = '?';
                                $insert_values[] = $class;
                            }
                            if (in_array('subject', $table_columns)) {
                                $insert_fields_list[] = 'subject';
                                $insert_placeholders[] = '?';
                                $insert_values[] = $subject;
                            }
                            if (in_array('year', $table_columns)) {
                                $insert_fields_list[] = 'year';
                                $insert_placeholders[] = '?';
                                $insert_values[] = $session;
                            }
                            if (in_array('term', $table_columns)) {
                                $insert_fields_list[] = 'term';
                                $insert_placeholders[] = '?';
                                $insert_values[] = $term;
                            }
                            if (in_array('teacher_no', $table_columns)) {
                                $insert_fields_list[] = 'teacher_no';
                                $insert_placeholders[] = '?';
                                $insert_values[] = $teacher_no;
                            }
                            if (in_array('csv_no', $table_columns)) {
                                $insert_fields_list[] = 'csv_no';
                                $insert_placeholders[] = '?';
                                $insert_values[] = $csv_no;
                            }
                            if (in_array('test1', $table_columns)) {
                                $insert_fields_list[] = 'test1';
                                $insert_placeholders[] = '?';
                                $insert_values[] = $test1;
                            }
                            if (in_array('test2', $table_columns)) {
                                $insert_fields_list[] = 'test2';
                                $insert_placeholders[] = '?';
                                $insert_values[] = $test2;
                            }
                            if (in_array('exam', $table_columns)) {
                                $insert_fields_list[] = 'exam';
                                $insert_placeholders[] = '?';
                                $insert_values[] = $exam;
                            }
                            if (in_array('total', $table_columns)) {
                                $insert_fields_list[] = 'total';
                                $insert_placeholders[] = '?';
                                $insert_values[] = $total;
                            }
                            
                            // Add required fields with defaults
                            foreach ($required_fields as $field) {
                                if (!in_array($field, $insert_fields_list) && $field != 'id' && $field != 'created_at' && $field != 'updated_at') {
                                    $insert_fields_list[] = $field;
                                    $insert_placeholders[] = '?';
                                    $insert_values[] = $field_defaults[$field] ?? 0;
                                }
                            }
                            
                            // Add timestamp fields
                            if (in_array('created_at', $table_columns)) {
                                $insert_fields_list[] = 'created_at';
                                $insert_placeholders[] = 'NOW()';
                            }
                            if (in_array('updated_at', $table_columns)) {
                                $insert_fields_list[] = 'updated_at';
                                $insert_placeholders[] = 'NOW()';
                            }
                            
                            $insert_query = "INSERT INTO tbl_student_results (" . implode(", ", $insert_fields_list) . ") 
                                           VALUES (" . implode(", ", $insert_placeholders) . ")";
                            
                            error_log("Insert query: $insert_query");
                            
                            $stmt = $DBH->prepare($insert_query);
                            $stmt->execute($insert_values);
                            error_log("Inserted record for $registration_no");
                        }
                        
                        $records_processed++;
                        $success_count++;
                        
                    } catch (PDOException $e) {
                        $error_details[] = "Database error on row $row_num: " . $e->getMessage();
                        error_log("Database error: " . $e->getMessage());
                    }
                }
                fclose($handle);
                
                error_log("Processed $records_processed records for subject $subject");
                
            } else {
                $error_details[] = "Could not open file for subject " . ($index + 1);
                $error_count++;
            }
        } catch (Exception $e) {
            $error_details[] = "Error processing file for subject " . ($index + 1) . ": " . $e->getMessage();
            $error_count++;
        }
    }
    
    if ($success_count > 0) {
        $_SESSION['success_message'] = "Successfully processed {$success_count} records for {$class} ({$term})";
        if ($error_count > 0) {
            $_SESSION['warning_message'] = "{$error_count} records had errors. Check details below.";
            $_SESSION['error_details'] = $error_details;
        }
    } else {
        $_SESSION['error_message'] = "No records were processed. Please check your file format and try again.";
        $_SESSION['error_details'] = $error_details;
    }
    
    header("Location: ".$_SERVER['PHP_SELF'] . ($branchCode ? "?branch=" . $branchCode : ""));
    exit();
}

// Get classes with their assigned teachers for dropdown
try {
    $classes = $DBH->query("
        SELECT 
            c.id, 
            c.class,
            u.hash as teacher_hash,
            u.fullname as teacher_name
        FROM tbl_class c
        LEFT JOIN tbl_user u ON (c.class = u.class AND u.teacher = 'true')
        ORDER BY c.class
    ")->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    die("Error fetching classes: " . $e->getMessage());
}
?>

<!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>Upload Results - <?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">
  
  <!-- 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);
      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;
    }
    
    .card-header h6 i {
      color: var(--secondary-gold);
    }
    
    /* 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-outline-primary {
      border-color: var(--primary-blue);
      color: var(--primary-blue);
    }
    
    .btn-outline-primary:hover {
      background-color: var(--primary-blue);
      color: white;
    }
    
    .btn-outline-success {
      border-color: #28a745;
      color: #28a745;
    }
    
    .btn-outline-success:hover {
      background-color: #28a745;
      color: white;
    }
    
    .btn-outline-danger {
      border-color: #dc3545;
      color: #dc3545;
    }
    
    .btn-outline-danger:hover {
      background-color: #dc3545;
      color: white;
    }
    
    .btn-outline-secondary {
      border-color: var(--secondary-gold);
      color: var(--dark-blue);
    }
    
    .btn-outline-secondary:hover {
      background-color: var(--secondary-gold);
      border-color: var(--dark-blue);
      color: var(--dark-blue);
    }
    
    /* 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);
    }
    
    /* 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;
    }
    
    /* 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);
    }
    
    .powered-by {
      display: flex;
      align-items: center;
      justify-content: flex-end;
      color: white;
    }
    
    .powered-by img {
      height: 30px;
      margin-left: 10px;
      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;
    }
    
    .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);
    }
    
    /* Form Styles */
    .form-control, .form-select {
      height: 50px;
      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);
    }
    
    /* Subject row */
    .subject-row {
      background-color: var(--bg-light);
      padding: 15px;
      border-radius: 8px;
      margin-bottom: 15px;
      border: 1px solid var(--secondary-gold);
    }
    
    /* Alert styles */
    .alert-success {
      background-color: #d4edda;
      border-color: #c3e6cb;
      color: #155724;
    }
    
    .alert-danger {
      background-color: #f8d7da;
      border-color: #f5c6cb;
      color: #721c24;
    }
    
    .alert-warning {
      background-color: var(--light-gold);
      border-color: var(--secondary-gold);
      color: var(--dark-blue);
    }
    
    .alert-warning ul {
      margin-top: 10px;
    }
    
    /* Page heading */
    .text-gray-800 {
      color: var(--dark-blue);
      font-weight: 700;
    }
    
    /* Responsive adjustments */
    @media (max-width: 768px) {
      .card-body {
        padding: 1.5rem;
      }
      
      .admin-info {
        padding: 6px 10px;
      }
      
      .admin-name, .admin-access {
        font-size: 0.8rem;
      }
      
      .subject-row .col-md-1 {
        margin-top: 10px;
      }
    }
  </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="upload_results.php<?php echo $branchCode ? '?branch='.$branchCode : ''; ?>">
            <i class="fas fa-fw fa-upload"></i>
            Upload 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">
    <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-upload me-2" style="color: var(--secondary-gold);"></i>
                Upload Student Results
                <?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 (visible only on mobile) -->
        <?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">Upload Results</li>
                </ol>
            </nav>
        </div>

        <!-- Messages -->
        <?php if (isset($_SESSION['success_message'])): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <i class="fas fa-check-circle me-2"></i>
                <?php echo $_SESSION['success_message']; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
            <?php unset($_SESSION['success_message']); ?>
        <?php endif; ?>
        
        <?php if (isset($_SESSION['warning_message'])): ?>
            <div class="alert alert-warning alert-dismissible fade show" role="alert">
                <i class="fas fa-exclamation-triangle me-2"></i>
                <?php echo $_SESSION['warning_message']; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
            <?php unset($_SESSION['warning_message']); ?>
        <?php endif; ?>
        
        <?php if (isset($_SESSION['error_message'])): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <i class="fas fa-exclamation-circle me-2"></i>
                <?php echo $_SESSION['error_message']; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
            <?php unset($_SESSION['error_message']); ?>
        <?php endif; ?>
        
        <?php if (isset($_SESSION['error_details']) && !empty($_SESSION['error_details'])): ?>
            <div class="alert alert-warning alert-dismissible fade show" role="alert">
                <h5 class="alert-heading"><i class="fas fa-exclamation-triangle me-2" style="color: var(--secondary-gold);"></i>Detailed Errors:</h5>
                <ul class="mb-0" style="max-height: 200px; overflow-y: auto;">
                    <?php foreach ($_SESSION['error_details'] as $error): ?>
                        <li><?php echo htmlspecialchars($error); ?></li>
                    <?php endforeach; ?>
                </ul>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
            <?php unset($_SESSION['error_details']); ?>
        <?php endif; ?>

        <!-- Upload Form -->
        <div class="row">
            <div class="col-lg-12">
                <div class="card shadow mb-4">
                    <div class="card-header py-3">
                        <h6 class="m-0 font-weight-bold">
                            <i class="fas fa-upload me-2" style="color: var(--secondary-gold);"></i>
                            Upload Results
                        </h6>
                    </div>
                    <div class="card-body">
                        <form id="uploadForm" method="post" enctype="multipart/form-data">
                            <?php if ($branchCode): ?>
                            <input type="hidden" name="branch" value="<?php echo $branchCode; ?>">
                            <?php endif; ?>
                            
                            <div class="row g-3">
                                <div class="col-md-4">
                                    <label for="classSelect" class="form-label">
                                        <i class="fas fa-building me-2"></i>Class
                                    </label>
                                    <select name="class" class="form-select" id="classSelect" required>
                                        <option value="">Select Class</option>
                                        <?php foreach($classes as $class): ?>
                                            <option value="<?php echo $class['id']; ?>">
                                                <?php echo $class['class']; ?>
                                                <?php if (!empty($class['teacher_name'])): ?>
                                                    - (Teacher: <?php echo $class['teacher_name']; ?>)
                                                <?php else: ?>
                                                    - (No teacher assigned)
                                                <?php endif; ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <?php if (empty($classes)): ?>
                                        <div class="text-danger small mt-1">No classes found. Please create classes first.</div>
                                    <?php endif; ?>
                                </div>
                                
                                <div class="col-md-4">
                                    <label for="termSelect" class="form-label">
                                        <i class="fas fa-calendar-alt me-2"></i>Term
                                    </label>
                                    <select name="term" class="form-select" id="termSelect" required>
                                        <option value="">Select Term</option>
                                        <option value="1st Term">1st Term</option>
                                        <option value="2nd Term">2nd Term</option>
                                        <option value="3rd Term">3rd Term</option>
                                    </select>
                                </div>
                                
                                <div class="col-md-4">
                                    <label for="sessionSelect" class="form-label">
                                        <i class="fas fa-calendar me-2"></i>Session
                                    </label>
                                    <select name="session" class="form-select" id="sessionSelect" required>
                                        <option value="">Select Session</option>
                                        <?php
                                        $sessions = sql($DBH, "SELECT * FROM tbl_session ORDER BY session DESC", [], "rows");
                                        foreach($sessions as $session) {
                                            echo "<option value='{$session['id']}'>{$session['session']}</option>";
                                        }
                                        ?>
                                    </select>
                                </div>
                            </div>
                            
                            <div id="subjectsContainer" class="mt-4">
                                <!-- Subject rows will be added here dynamically -->
                            </div>
                            
                            <div class="mt-3">
                                <button type="button" id="addSubjectBtn" class="btn btn-outline-primary">
                                    <i class="fas fa-plus me-1"></i> Add Subject
                                </button>
                            </div>
                            
                            <div class="mt-4">
                                <button type="submit" name="upload_results" class="btn btn-primary">
                                    <i class="fas fa-upload me-1"></i> Upload All Subjects
                                </button>
                                <a href="main.php<?php echo $branchCode ? '?branch='.$branchCode : ''; ?>" class="btn btn-outline-secondary ms-2">
                                    <i class="fas fa-arrow-left me-1"></i> Back to Dashboard
                                </a>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <!-- Download Sample Section -->
        <div class="row">
            <div class="col-lg-12">
                <div class="card shadow mb-4">
                    <div class="card-header py-3">
                        <h6 class="m-0 font-weight-bold">
                            <i class="fas fa-download me-2" style="color: var(--secondary-gold);"></i>
                            Upload Skills, Attendance & Comments
                        </h6>
                    </div>
                    <div class="card-body">
                        <div class="row g-3">
                            <div class="col-md-4">
                                <a href="post_attendance.php<?php echo $branchCode ? '?branch='.$branchCode : ''; ?>" class="btn btn-outline-success w-100">
                                    <i class="fas fa-file-csv me-1"></i> Upload Attendance & Teacher's Comment
                                </a>
                            </div>
                            <div class="col-md-4">
                                <a href="post_skills.php<?php echo $branchCode ? '?branch='.$branchCode : ''; ?>" class="btn btn-outline-success w-100">
                                    <i class="fas fa-file-csv me-1"></i> Upload Psychomotor & Other Skills
                                </a>
                            </div>
                        </div>
                        <hr class="my-4" style="border-color: var(--secondary-gold);">
                        <div class="row g-3">
                            <div class="col-md-4">
                                <a href="https://bkms.com.ng/portal/coll_admin/SAMPLE_CA1_CA2_EXAM.csv" class="btn btn-outline-success w-100" target="_blank">
                                    <i class="fas fa-file-csv me-1"></i> Download CSV Sample
                                </a>
                            </div>
                            <div class="col-md-4">
                                <a href="https://bkms.com.ng/portal/coll_admin/SAMPLE_PSYCHOMOTOR_AND_OTHER_SKILLS.csv" class="btn btn-outline-primary w-100" target="_blank">
                                    <i class="fas fa-file-csv me-1"></i> Download Skills Sample
                                </a>
                            </div>
                            <div class="col-md-4">
                                <a href="https://bkms.com.ng/portal/coll_admin/SAMPLE_ATTENDANCE_SHEET.csv" class="btn btn-outline-danger w-100" target="_blank">
                                    <i class="fas fa-file-csv me-1"></i> Download Attendance Sample
                                </a>
                            </div>
                        </div>
                        <div class="mt-3">
                            <p class="text-muted small">
                                <strong>Note:</strong> Your file should contain the following columns in order: 
                                <strong>Name, Admission No, Test1, Test2, Exam</strong>. The system will automatically calculate the total.
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Uploaded Result Section -->
        <div class="card shadow mb-4">
            <div class="card-header py-3">
                <h6 class="m-0 font-weight-bold">
                    <i class="fas fa-history me-2" style="color: var(--secondary-gold);"></i>
                    Uploaded Results by Session
                </h6>
            </div>
            <div class="card-body">
                <div class="row">
                    <?php
                    $STH = $DBH->prepare("SELECT count(*) FROM tbl_student_results WHERE id >= ?");
                    $result = $STH->execute(array(1));
                    $count = $STH->fetchColumn();
                    
                    if($count >= 1) {
                        $rows = sql($DBH, "SELECT MIN(id) AS id, year FROM tbl_student_results WHERE id >= ? GROUP BY year", 
                        array(1), "rows");
                        foreach($rows as $row) {  
                            $t_year = $row['year'];
                            echo '
                            <div class="col-md-3 mb-3">
                                <a href="main_term.php?id='.$t_year.'" target="_blank" class="btn btn-outline-secondary w-100">
                                    <i class="fas fa-calendar-alt me-1"></i> '.$t_year.'
                                </a>
                            </div>';
                        }
                    } else {
                        echo '<div class="col-12 text-center py-4">
                            <i class="fas fa-info-circle fa-2x mb-3" style="color: var(--primary-blue);"></i>
                            <p class="text-muted">No academic records found yet</p>
                        </div>';
                    }
                    ?>
                </div>
            </div>
        </div>
    </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="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>

<!-- JavaScript -->
<script>
// Toggle sidebar on mobile
document.getElementById('sidebarToggle').addEventListener('click', function() {
    document.getElementById('sidebar').classList.toggle('active');
    document.querySelector('.main-content').classList.toggle('active');
});

// Add subject row
let subjectIndex = 0;
$('#addSubjectBtn').click(function() {
    const classSelected = $('#classSelect').val();
    const termSelected = $('#termSelect').val();
    const sessionSelected = $('#sessionSelect').val();
    
    if (!classSelected || !termSelected || !sessionSelected) {
        alert('Please select Class, Term and Session first');
        return;
    }
    
    const subjectRow = `
        <div class="subject-row" id="subjectRow${subjectIndex}">
            <div class="row g-3">
                <div class="col-md-6">
                    <label class="form-label">
                        <i class="fas fa-book me-2"></i>Subject
                    </label>
                    <select name="subjects[${subjectIndex}][subject_id]" class="form-select" required>
                        <option value="">Select Subject</option>
                        <?php
                        $subjects = sql($DBH, "SELECT * FROM tbl_subject ORDER BY subject", [], "rows");
                        foreach($subjects as $subject) {
                            echo "<option value='{$subject['id']}'>{$subject['subject']}</option>";
                        }
                        ?>
                    </select>
                </div>
                <div class="col-md-5">
                    <label class="form-label">
                        <i class="fas fa-file-csv me-2"></i>Result File
                    </label>
                    <input type="file" name="subjects[${subjectIndex}][file]" class="form-control" accept=".csv,.tsv,.txt" required>
                    <small class="text-muted">CSV or TSV file only</small>
                </div>
                <div class="col-md-1 d-flex align-items-end">
                    <button type="button" class="btn btn-danger btn-sm" onclick="removeSubjectRow(${subjectIndex})">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            </div>
        </div>
    `;
    
    $('#subjectsContainer').append(subjectRow);
    subjectIndex++;
});

// Remove subject row
function removeSubjectRow(index) {
    if (confirm('Are you sure you want to remove this subject?')) {
        $(`#subjectRow${index}`).remove();
    }
}

// Form validation
$('#uploadForm').submit(function(e) {
    if ($('.subject-row').length === 0) {
        e.preventDefault();
        alert('Please add at least one subject to upload');
        return false;
    }
    return true;
});

// Auto-hide alerts after 10 seconds (increased time for error details)
$(document).ready(function() {
    setTimeout(function() {
        $('.alert').fadeOut('slow');
    }, 10000);
});
</script>
</body>
</html>