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

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

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

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

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

// Get admin info
$admin_name = "";
$rows = sql($DBH, "SELECT * FROM tbl_admin where status = ?", array("Active"), "rows");
foreach($rows as $row) {
    $admin_name = $row['username'];
}

// Handle query messages for UI
if(isset($_GET['msg'])) {
    if($_GET['msg'] == "refered") {
        $_SESSION['success_message'] = "Referred successfully";
    } else if($_GET['msg'] == "failed") {
        $_SESSION['error_message'] = "Something went wrong, please try again";
    }
}

/*
 * CSV import handler
 * Matches existing records by registration_no + year + term
 * If a matching record exists -> update it (and set csv_no to current import key)
 * Otherwise -> insert new record
 */
if(isset($_POST['importSubmit'])) {
    $teacher_no = strip_tags($_POST['teacher_no']);
    $s_term = strip_tags($_POST['term']);
    $s_year = strip_tags($_POST['year']);

    try {
        // Get teacher's class and subclass
        $stmt = $DBH->prepare("SELECT class, subclass FROM tbl_user WHERE hash = ?");
        $stmt->execute([$teacher_no]);
        $teacher_data = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($teacher_data) {
            $s_class = $teacher_data['class'];
            $s_subclass = $teacher_data['subclass'];
        } else {
            throw new Exception("Teacher not found");
        }

        // Unique import identifier for this upload (applied to all rows in this import)
        $key = mt_rand(100000, 999999);

        // Allowed CSV MIME types
        $csvMimes = array(
            'text/x-comma-separated-values','text/comma-separated-values',
            'application/octet-stream','application/vnd.ms-excel',
            'application/x-csv','text/x-csv','text/csv',
            'application/csv','application/excel','application/vnd.msexcel',
            'text/plain'
        );

        if(!empty($_FILES['file']['name']) && in_array($_FILES['file']['type'], $csvMimes)) {
            if(is_uploaded_file($_FILES['file']['tmp_name'])) {
                $csvFile = fopen($_FILES['file']['tmp_name'], 'r');

                // Read header row (if present)
                $header = fgetcsv($csvFile);

                $success_count = 0;
                $error_count = 0;
                $error_details = [];
                $row_index = 1; // header is row 1

                while(($line = fgetcsv($csvFile)) !== FALSE) {
                    $row_index++;
                    try {
                        // Ensure sufficient columns (your expected format: 7 columns)
                        if(count($line) < 7) {
                            $error_details[] = "Row {$row_index}: Insufficient columns (expected 7, found " . count($line) . ")";
                            $error_count++;
                            continue;
                        }

                        // Map CSV columns
                        $name = trim($line[0]);
                        $registration_no = trim($line[1]);
                        $present = trim($line[2]);
                        $sch_open = trim($line[3]);
                        $date_of_report = trim($line[4]);
                        $next_term_begins = trim($line[5]);
                        $teachers_remarks = trim($line[6]);

                        // Minimal validation
                        if(empty($name) || empty($registration_no)) {
                            $error_details[] = "Row {$row_index}: Missing name or registration number";
                            $error_count++;
                            continue;
                        }

                        // Normalize dates (if present) to YYYY-MM-DD or keep as-is if empty
                        if(!empty($date_of_report)) {
                            $d = date_create($date_of_report);
                            if($d) $date_of_report = $d->format('Y-m-d');
                        }
                        if(!empty($next_term_begins)) {
                            $d2 = date_create($next_term_begins);
                            if($d2) $next_term_begins = $d2->format('Y-m-d');
                        }

                        // Check if a record exists for this student in same year & term
                        $check_stmt = $DBH->prepare("SELECT id FROM attendance WHERE registration_no = ? AND year = ? AND term = ? LIMIT 1");
                        $check_stmt->execute([$registration_no, $s_year, $s_term]);
                        $existing = $check_stmt->fetch(PDO::FETCH_ASSOC);

                        if ($existing && isset($existing['id'])) {
                            // Update existing record (also update csv_no to current import key)
                            $update_stmt = $DBH->prepare("
                                UPDATE attendance SET
                                    name = ?, Present = ?, SchOpen = ?, DateOfReport = ?, NextTermBegins = ?, TeachersRemarks = ?,
                                    class = ?, subclass = ?, year = ?, teacher_no = ?, term = ?, csv_no = ?
                                WHERE id = ?
                            ");
                            $update_stmt->execute([
                                $name, $present, $sch_open, $date_of_report, $next_term_begins, $teachers_remarks,
                                $s_class, $s_subclass, $s_year, $teacher_no, $s_term, $key,
                                $existing['id']
                            ]);
                        } else {
                            // Insert new record
                            $insert_stmt = $DBH->prepare("
                                INSERT INTO attendance
                                    (name, registration_no, Present, SchOpen, DateOfReport, NextTermBegins, TeachersRemarks,
                                     class, subclass, year, teacher_no, csv_no, term)
                                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                            ");
                            $insert_stmt->execute([
                                $name, $registration_no, $present, $sch_open, $date_of_report, $next_term_begins, $teachers_remarks,
                                $s_class, $s_subclass, $s_year, $teacher_no, $key, $s_term
                            ]);
                        }

                        $success_count++;
                    } catch(PDOException $e) {
                        $error_details[] = "Row {$row_index}: Database error - " . $e->getMessage();
                        $error_count++;
                    }
                }

                fclose($csvFile);

                // Prepare session messages and redirect query string
                if($success_count > 0) {
                    $_SESSION['success_message'] = "Successfully processed {$success_count} attendance records";

                    if($error_count > 0) {
                        $_SESSION['warning_message'] = "{$error_count} records had errors";
                        $_SESSION['error_details'] = $error_details;
                    }

                    // Store key in session for reference
                    $_SESSION['last_csv_no'] = $key;

                    $qstring = "?status=success&val=" . $key . "&records=" . $success_count . ($branchCode ? "&branch=" . $branchCode : "");
                } else {
                    $_SESSION['error_message'] = "No records were imported. Please check your CSV file format.";
                    $_SESSION['error_details'] = $error_details;
                    $qstring = "?status=error&type=no_records" . ($branchCode ? "&branch=" . $branchCode : "");
                }
            } else {
                $_SESSION['error_message'] = "File upload failed";
                $qstring = "?status=error&type=upload_failed" . ($branchCode ? "&branch=" . $branchCode : "");
            }
        } else {
            $_SESSION['error_message'] = "Invalid file type. Please upload a CSV file.";
            $qstring = "?status=error&type=invalid_file" . ($branchCode ? "&branch=" . $branchCode : "");
        }
    } catch(Exception $e) {
        $_SESSION['error_message'] = "Error: " . $e->getMessage();
        $qstring = "?status=error&type=exception" . ($branchCode ? "&branch=" . $branchCode : "");
    }

    header("Location: post_attendance.php" . $qstring);
    exit();
}
?>
<!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 Attendance - <?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;
    }
    
    /* 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;
    }
    
    /* 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-danger {
      border-color: #dc3545;
      color: #dc3545;
    }
    
    .btn-outline-danger:hover {
      background-color: #dc3545;
      color: white;
    }
    
    .btn-outline-light {
      border-color: var(--secondary-gold);
      color: var(--secondary-gold);
    }
    
    .btn-outline-light: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);
    }
    
    /* 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);
    }
    
    /* Import form */
    #importFrm {
      display: none;
      animation: slideDown 0.3s ease;
      background: linear-gradient(135deg, var(--light-gold) 0%, #ffffff 100%);
      padding: 25px;
      border-radius: 12px;
      border: 2px solid var(--secondary-gold);
      margin-top: 15px;
    }
    
    @keyframes slideDown {
      from { opacity: 0; transform: translateY(-10px); }
      to { opacity: 1; transform: translateY(0); }
    }
    
    /* Uploaded year cards */
    .uploaded-year {
      background: linear-gradient(135deg, var(--primary-blue), var(--dark-blue));
      color: white;
      padding: 20px;
      border-radius: 12px;
      text-align: center;
      transition: all 0.3s ease;
      text-decoration: none;
      display: block;
      border: 2px solid var(--secondary-gold);
      height: 100%;
    }
    
    .uploaded-year:hover {
      transform: translateY(-5px);
      box-shadow: 0 5px 20px rgba(255, 215, 0, 0.4);
      background: linear-gradient(135deg, var(--dark-blue), var(--primary-blue));
      color: var(--secondary-gold);
    }
    
    .uploaded-year i {
      font-size: 2.5rem;
      margin-bottom: 10px;
    }
    
    /* 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);
    }
    
    /* Page heading */
    .text-gray-800 {
      color: var(--dark-blue);
      font-weight: 700;
    }
    
    /* List group */
    .list-group-item {
      border: none;
      background-color: transparent;
      color: var(--dark-blue);
      padding: 0.5rem 1rem;
    }
    
    .list-group-item i.fa-check {
      color: var(--secondary-gold);
    }
    
    /* Feature list */
    .feature-list {
      background: linear-gradient(135deg, #f8f9fa, #ffffff);
      padding: 15px;
      border-radius: 8px;
      border-left: 4px solid var(--secondary-gold);
    }
    
    /* Responsive adjustments */
    @media (max-width: 768px) {
      .card-body {
        padding: 1.5rem;
      }
      
      .admin-info {
        padding: 6px 10px;
      }
      
      .admin-name, .admin-access {
        font-size: 0.8rem;
      }
    }
  </style>
</head>

<body>
  <!-- Top Navigation -->
  <nav class="navbar navbar-expand-lg navbar-dark">
    <div class="container-fluid">
      <button id="sidebarToggle" class="btn btn-link d-lg-none me-2">
        <i class="fas fa-bars" style="color: white;"></i>
      </button>
      <a class="navbar-brand d-none d-lg-block" href="#">
        <img src="../<?php echo $schoolLogo; ?>" alt="<?php echo $schoolName; ?>" height="35" style="border-radius: 4px;" onerror="this.src='coll_logo.png';">
        <?php echo $schoolShortName ?: substr($schoolName, 0, 20); ?>
      </a>
      
      <!-- Branch Switcher (visible on desktop) -->
      <?php if (count($allBranches) > 1): ?>
      <div class="d-none d-lg-block branch-switcher">
        <form method="get" class="d-flex align-items-center">
          <span class="text-white me-2 small">Branch:</span>
          <select name="branch" class="form-select form-select-sm" style="width: auto;" onchange="this.form.submit()">
            <option value="" style="color: #333;">Select</option>
            <?php foreach ($allBranches as $branch): ?>
            <option value="<?php echo $branch['branch_code']; ?>" style="color: #333;" 
                    <?php echo ($branchCode == $branch['branch_code']) ? 'selected' : ''; ?>>
              <?php echo $branch['branch_code']; ?> - <?php echo substr($branch['branch_name'], 0, 10); ?>
            </option>
            <?php endforeach; ?>
          </select>
        </form>
      </div>
      <?php endif; ?>
      
      <div class="ms-auto d-flex align-items-center">
        <div class="admin-info me-3">
          <span class="admin-name"><?php echo htmlspecialchars($admin_name ?: '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="post_attendance.php<?php echo $branchCode ? '?branch='.$branchCode : ''; ?>"><i class="fas fa-fw fa-calendar-check"></i> Upload Attendance</a></li>
        <li class="nav-item"><a class="nav-link" href="post_skills.php<?php echo $branchCode ? '?branch='.$branchCode : ''; ?>"><i class="fas fa-fw fa-chart-bar"></i> Upload Skills</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-calendar-check me-2" style="color: var(--secondary-gold);"></i>
          Upload Student's Attendance
          <?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 Attendance</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" style="color: var(--secondary-gold);"></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 Card -->
      <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 Student's Attendance, Closing Date, Resumption Date, Teacher's Comment, etc.
                <button type="button" id="toggleImportBtn" class="btn btn-sm btn-outline-light float-end">
                  <i class="fas fa-upload me-1"></i> Click Here to Import Data
                </button>
              </h6>
            </div>
            <div class="card-body">
              <!-- Import Form -->
              <form action="post_attendance.php<?php echo $branchCode ? '?branch='.$branchCode : ''; ?>" method="post" enctype="multipart/form-data" id="importFrm">
                <?php if ($branchCode): ?>
                <input type="hidden" name="branch" value="<?php echo $branchCode; ?>">
                <?php endif; ?>
                
                <div class="mb-4">
                  <label for="file" class="form-label">
                    <i class="fas fa-file-csv me-2"></i>Choose CSV File
                  </label>
                  <input type="file" name="file" class="form-control" id="file" accept=".csv" required>
                  <div class="form-text">Upload a CSV file with student attendance data</div>
                </div>

                <div class="row g-3">
                  <div class="col-md-3">
                    <label for="term" class="form-label">
                      <i class="fas fa-calendar-alt me-2"></i>Term
                    </label>
                    <select name="term" class="form-select" id="term" required>
                      <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-3">
                    <label for="year" class="form-label">
                      <i class="fas fa-calendar me-2"></i>Academic Year
                    </label>
                    <select name="year" class="form-select" id="year" required>
                      <?php
                      $rows1 = sql($DBH, "SELECT * FROM tbl_session where id >= ?", array(1), "rows");
                      foreach($rows1 as $row1) {
                        $sch_session = $row1['session'];
                        echo "<option value='".htmlspecialchars($sch_session)."'>".htmlspecialchars($sch_session)."</option>";
                      }
                      ?>
                    </select>
                  </div>

                  <div class="col-md-4">
                    <label for="teacher_no" class="form-label">
                      <i class="fas fa-chalkboard-teacher me-2"></i>Class Teacher
                    </label>
                    <select name="teacher_no" class="form-select" id="teacher_no" required>
                      <?php
                      $rows1 = sql($DBH, "SELECT * FROM tbl_user where teacher = ?", array("true"), "rows");
                      foreach($rows1 as $row1) {
                        $sch_hash = $row1['hash'];
                        $sch_name = $row1['fullname'];
                        $sc_class = $row1['class'];
                        echo "<option value='".htmlspecialchars($sch_hash)."'>".htmlspecialchars($sc_class . " - " . $sch_name)."</option>";
                      }
                      ?>
                    </select>
                  </div>

                  <div class="col-md-2 d-flex align-items-end">
                    <button type="submit" class="btn btn-primary w-100" name="importSubmit">
                      <i class="fas fa-upload me-1"></i> UPLOAD
                    </button>
                  </div>
                </div>
              </form>

              <div class="mt-4">
                <a href="https://rportal.lahs.com.ng/admin/SAMPLE_ATTENDANCE_SHEET.csv" class="btn btn-outline-danger" target="_blank">
                  <i class="fas fa-download me-1"></i> Download Sample CSV Format
                </a>
              </div>

              <div class="feature-list mt-4">
                <h6 class="text-primary mb-3"><i class="fas fa-info-circle me-2" style="color: var(--secondary-gold);"></i>What You Can Upload:</h6>
                <div class="row">
                  <div class="col-md-6">
                    <ul class="list-group list-group-flush">
                      <li class="list-group-item"><i class="fas fa-check-circle me-2" style="color: var(--secondary-gold);"></i> Student Attendance Records</li>
                      <li class="list-group-item"><i class="fas fa-check-circle me-2" style="color: var(--secondary-gold);"></i> School Closing Dates</li>
                      <li class="list-group-item"><i class="fas fa-check-circle me-2" style="color: var(--secondary-gold);"></i> School Resumption Dates</li>
                    </ul>
                  </div>
                  <div class="col-md-6">
                    <ul class="list-group list-group-flush">
                      <li class="list-group-item"><i class="fas fa-check-circle me-2" style="color: var(--secondary-gold);"></i> Next Term Information</li>
                      <li class="list-group-item"><i class="fas fa-check-circle me-2" style="color: var(--secondary-gold);"></i> Teacher's Comments</li>
                      <li class="list-group-item"><i class="fas fa-check-circle me-2" style="color: var(--secondary-gold);"></i> Report Generation Date</li>
                    </ul>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Uploaded Attendance 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>
            Previously Uploaded Attendance Records
          </h6>
        </div>
        <div class="card-body">
          <div class="row">
            <?php
            $STH = $DBH->prepare("SELECT count(*) FROM attendance WHERE id >= ?");
            $STH->execute(array(1));
            $count = $STH->fetchColumn();

            if($count >= 1) {
              $rows = sql($DBH, "SELECT MIN(id) AS id, year FROM attendance 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='.htmlspecialchars($t_year).($branchCode ? '&branch='.$branchCode : '').'" target="_blank" class="uploaded-year">
                    <i class="fas fa-calendar-alt"></i><br>
                    <strong>'.htmlspecialchars($t_year).'</strong><br>
                    <small class="opacity-75">Click to view details</small>
                  </a>
                </div>';
              }
            } else {
              echo '<div class="col-12 text-center py-5">
                <i class="fas fa-calendar-times fa-4x mb-3" style="color: var(--primary-blue);"></i>
                <h5 class="text-muted">No Attendance Records Found</h5>
                <p class="text-muted">Upload your first attendance record using the form above.</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');
  });

  // Toggle import form with animation
  $(document).ready(function() {
    // Show/hide import form
    $('#toggleImportBtn').click(function() {
      $('#importFrm').slideToggle();
    });

    // File input styling
    $('#file').change(function() {
      var fileName = $(this).val().split('\\').pop();
      if(fileName) {
        $(this).next('.form-text').html('Selected: <strong>' + fileName + '</strong>');
      }
    });

    // Auto-hide alerts after 5 seconds
    setTimeout(function() {
      $('.alert').fadeOut('slow');
    }, 5000);
  });
  </script>
</body>
</html>