<?php
try {
    require_once('source/session.php');
    require_once('source/error.php');
    require_once('source/dbconfig.php');
    require_once('source/function.php');
    require_once('source/restrict_admin.php');
    session_start();

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

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

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

    // School information
    $schoolName = "Henzy Royal International School";
    $schoolAddress = "No 17 Amadi Street, Amakohia, Uratta Owerri Imo State Nigeria";
    $supportPhone = "+234 803 292 9756";
    $supportEmail = "support@hris.com.ng";

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

    // Initialize variables
    $class = $_POST['class'] ?? '';
    $term = $_POST['term'] ?? '';
    $year = $_POST['year'] ?? '';
    $page_title = '';
    $total_results_count = 0;
    $comments_results = [];

    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        // Extract search data from the form
        $class = strip_tags($_POST['class']);
        $term = strip_tags($_POST['term']);
        $year = strip_tags($_POST['year']);

        // Retrieve attendance records from the database based on the search criteria
        $comments_results = sql($DBH, 
            "SELECT id, name, registration_no, class, year, term, 
                    Present, SchOpen, DateOfReport, NextTermBegins, 
                    TeachersRemarks, Absent 
             FROM attendance 
             WHERE class = ? AND term = ? AND year = ? 
             ORDER BY name",
            [$class, $term, $year], 
            "rows"
        );

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

        // Count of total records
        $total_results_count = count($comments_results);

        // Handle form submissions for saving all fields
        if (isset($_POST['save_all'])) {
            $ids = $_POST['id'];
            $present_values = $_POST['present'];
            $schopen_values = $_POST['schopen'];
            $dateofreport_values = $_POST['dateofreport'];
            $nexttermbegins_values = $_POST['nexttermbegins'];
            $teachersremarks_values = $_POST['teachersremarks'];
            $absent_values = $_POST['absent'];

            $success_count = 0;
            $error_messages = [];
            
            foreach ($ids as $index => $id) {
                $present = intval($present_values[$index]);
                $schopen = intval($schopen_values[$index]);
                $absent = intval($absent_values[$index]);
                $dateofreport = $dateofreport_values[$index];
                $nexttermbegins = $nexttermbegins_values[$index];
                $teachersremarks = strip_tags($teachersremarks_values[$index]);
                
                // Validate numeric fields
                if ($present >= 0 && $schopen >= 0 && $absent >= 0) {
                    $update_query = "UPDATE attendance SET 
                                    Present = ?, 
                                    SchOpen = ?, 
                                    DateOfReport = ?, 
                                    NextTermBegins = ?, 
                                    TeachersRemarks = ?, 
                                    Absent = ? 
                                    WHERE id = ?";
                    
                    $stmt = $DBH->prepare($update_query);
                    if ($stmt->execute([$present, $schopen, $dateofreport, $nexttermbegins, $teachersremarks, $absent, $id])) {
                        $success_count++;
                    } else {
                        $error_messages[] = "Failed to update record ID: $id";
                    }
                } else {
                    $error_messages[] = "Invalid numeric values for record ID: $id";
                }
            }

            if ($success_count > 0 && empty($error_messages)) {
                $success_message = "Successfully updated $success_count records";
                
                // Refresh the results
                $comments_results = sql($DBH, 
                    "SELECT id, name, registration_no, class, year, term, 
                            Present, SchOpen, DateOfReport, NextTermBegins, 
                            TeachersRemarks, Absent 
                     FROM attendance 
                     WHERE class = ? AND term = ? AND year = ? 
                     ORDER BY name",
                    [$class, $term, $year], 
                    "rows"
                );
            } elseif (!empty($error_messages)) {
                $error_message = implode("<br>", $error_messages);
            }
        }

        // Handle form submissions for deleting a record
        if (isset($_POST['delete']) && isset($_POST['delete_id'])) {
            $delete_id = strip_tags($_POST['delete_id']);
            
            // Get student name for confirmation message
            $student_info = sql($DBH, 
                "SELECT name FROM attendance WHERE id = ?", 
                [$delete_id], 
                "row"
            );
            
            $delete_query = "DELETE FROM attendance WHERE id = ?";
            $stmt = $DBH->prepare($delete_query);
            
            if ($stmt->execute([$delete_id])) {
                $success_message = "Successfully deleted record for: " . ($student_info['name'] ?? 'Unknown Student');
                
                // Refresh the results
                $comments_results = sql($DBH, 
                    "SELECT id, name, registration_no, class, year, term, 
                            Present, SchOpen, DateOfReport, NextTermBegins, 
                            TeachersRemarks, Absent 
                     FROM attendance 
                     WHERE class = ? AND term = ? AND year = ? 
                     ORDER BY name",
                    [$class, $term, $year], 
                    "rows"
                );
                $total_results_count = count($comments_results);
            } else {
                $error_message = "Failed to delete record";
            }
        }
    }
} catch (PDOException $e) {
    $error_message = "Database Error: " . $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>Attendance & Comments - Henzy Royal International School</title>
  <link rel="icon" type="image/png" href="coll_logo.png">
  
  <!-- Bootstrap 5 CSS -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  
  <!-- Font Awesome -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
  
  <!-- Google Fonts - Poppins -->
  <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
  
  <!-- Custom CSS -->
  <style>
    :root {
      --primary-blue: #1a4b8c;    /* Royal Blue */
      --secondary-gold: #FFD700;    /* Gold */
      --dark-blue: #0f2b4f;         /* Dark Blue */
      --light-blue: #4a7db5;         /* Medium Blue */
      --light-gold: #FFF1B8;          /* Light Gold */
      --bg-light: #f5f9ff;
    }
    
    body {
      font-family: 'Poppins', sans-serif;
      background-color: var(--bg-light);
      padding-top: 56px;
      color: #333;
      font-size: 0.9rem;
    }
    
    /* Navbar Styles */
    .navbar {
      background: linear-gradient(135deg, var(--primary-blue), var(--dark-blue));
      box-shadow: 0 0.15rem 1.75rem 0 rgba(26, 75, 140, 0.2);
      position: fixed;
      top: 0;
      width: 100%;
      z-index: 1030;
      color: white;
      border-bottom: 2px solid var(--secondary-gold);
    }
    
    .navbar-brand {
      font-weight: 800;
      font-size: 1.2rem;
      color: white;
      display: flex;
      align-items: center;
    }
    
    .navbar-brand img {
      border-radius: 4px;
      margin-right: 10px;
    }
    
    /* Sidebar Styles */
    .sidebar {
      background: linear-gradient(180deg, var(--dark-blue) 0%, var(--primary-blue) 100%);
      position: fixed;
      top: 56px;
      left: 0;
      width: 250px;
      height: calc(100vh - 56px);
      transition: all 0.3s;
      z-index: 1000;
      overflow-y: auto;
      border-right: 3px solid var(--secondary-gold);
    }
    
    .sidebar .nav-link {
      color: rgba(255, 255, 255, 0.9);
      font-weight: 500;
      padding: 0.75rem 1rem;
      margin-bottom: 0.2rem;
      transition: all 0.2s;
      border-left: 3px solid transparent;
    }
    
    .sidebar .nav-link:hover {
      color: white;
      background-color: rgba(255, 215, 0, 0.15);
      border-left-color: var(--secondary-gold);
    }
    
    .sidebar .nav-link.active {
      color: var(--dark-blue);
      background-color: var(--secondary-gold);
      border-left-color: var(--dark-blue);
      font-weight: 600;
    }
    
    .sidebar .nav-link i {
      margin-right: 0.5rem;
      width: 20px;
      text-align: center;
    }
    
    .sidebar-logo {
      text-align: center;
      margin-bottom: 1rem;
      padding: 1rem;
    }
    
    .logo-text {
      font-size: 1.5rem;
      font-weight: 900;
      color: white;
      letter-spacing: 2px;
      line-height: 1.2;
    }
    
    .logo-text span {
      color: var(--secondary-gold);
    }
    
    .logo-tagline {
      font-size: 0.65rem;
      color: var(--secondary-gold);
      letter-spacing: 1px;
    }
    
    /* Main Content Styles */
    .main-content {
      margin-left: 250px;
      width: calc(100% - 250px);
      transition: all 0.3s;
      min-height: calc(100vh - 56px);
      padding-bottom: 60px;
    }
    
    @media (max-width: 991.98px) {
      .sidebar {
        left: -250px;
      }
      .main-content {
        margin-left: 0;
        width: 100%;
      }
      body {
        padding-top: 56px;
      }
    }
    
    /* Welcome banner */
    .welcome-banner {
      background: linear-gradient(135deg, var(--primary-blue), var(--light-blue));
      color: white;
      border-radius: 0.5rem;
      padding: 0.75rem 1rem;
      margin: 1rem;
      box-shadow: 0 4px 6px rgba(0,0,0,0.1);
      border-left: 5px solid var(--secondary-gold);
    }
    
    /* Form Styles */
    .form-container {
      background-color: white;
      border-radius: 0.5rem;
      padding: 1rem;
      margin: 1rem;
      box-shadow: 0 0.15rem 1.75rem 0 rgba(26, 75, 140, 0.1);
      border: 1px solid rgba(255, 215, 0, 0.2);
    }
    
    /* Table Styles */
    .table-container {
      background-color: white;
      border-radius: 0.5rem;
      padding: 1rem;
      margin: 1rem;
      box-shadow: 0 0.15rem 1.75rem 0 rgba(26, 75, 140, 0.1);
      overflow-x: auto;
      border: 1px solid rgba(255, 215, 0, 0.2);
    }
    
    .attendance-table {
      width: 100%;
      border-collapse: collapse;
      font-size: 0.85rem;
    }
    
    .attendance-table th,
    .attendance-table td {
      padding: 0.75rem;
      border: 1px solid #dee2e6;
      text-align: center;
      vertical-align: middle;
    }
    
    .attendance-table th {
      background: linear-gradient(135deg, var(--primary-blue), var(--dark-blue));
      color: white;
      font-weight: 600;
      position: sticky;
      top: 0;
      z-index: 10;
    }
    
    .attendance-table th i {
      color: var(--secondary-gold);
    }
    
    .attendance-table input,
    .attendance-table textarea {
      width: 100%;
      padding: 0.5rem;
      border: 1px solid #ced4da;
      border-radius: 0.25rem;
      font-size: 0.85rem;
    }
    
    .attendance-table input:focus,
    .attendance-table textarea:focus {
      border-color: var(--secondary-gold);
      box-shadow: 0 0 0 0.25rem rgba(255, 215, 0, 0.25);
      outline: none;
    }
    
    .attendance-table .student-name {
      text-align: left;
      font-weight: 600;
      background-color: var(--light-gold);
      position: sticky;
      left: 0;
      z-index: 5;
      min-width: 150px;
    }
    
    .attendance-table .attendance-col {
      background-color: #e8f5e9;
      min-width: 80px;
    }
    
    .attendance-table .date-col {
      background-color: #fff3e0;
      min-width: 120px;
    }
    
    .attendance-table .comment-col {
      background-color: #f3e5f5;
      min-width: 250px;
    }
    
    .attendance-table tr:nth-child(even) {
      background-color: #f9f9f9;
    }
    
    .attendance-table tr:hover {
      background-color: var(--light-gold);
    }
    
    /* Badge styles */
    .badge-count {
      background: linear-gradient(135deg, var(--secondary-gold), #e6b800);
      color: var(--dark-blue);
      font-size: 0.75rem;
      padding: 0.2rem 0.5rem;
      border-radius: 0.25rem;
      font-weight: 600;
    }
    
    /* Admin Info Styles */
    .admin-info {
      display: flex;
      align-items: center;
      background-color: rgba(255, 215, 0, 0.2);
      padding: 8px 12px;
      border-radius: 8px;
      color: white;
    }
    
    .admin-name {
      margin-right: 5px;
      font-weight: 600;
    }
    
    .admin-access {
      font-style: italic;
      opacity: 0.8;
      margin-right: 10px;
      font-size: 0.9rem;
    }
    
    .admin-icon {
      font-size: 1.5rem;
      color: var(--secondary-gold);
    }
    
    /* Footer styles */
    .footer {
      background: linear-gradient(135deg, var(--dark-blue), var(--primary-blue));
      color: white;
      padding: 12px 0;
      position: fixed;
      bottom: 0;
      width: 100%;
      z-index: 100;
      font-size: 0.8rem;
      border-top: 2px solid var(--secondary-gold);
    }
    
    @media (min-width: 992px) {
      .footer {
        margin-left: 250px;
        width: calc(100% - 250px);
      }
    }
    
    @media (max-width: 991.98px) {
      .footer {
        margin-left: 0;
        width: 100%;
      }
    }
    
    .copyright-text {
      font-weight: 600;
    }
    
    .copyright-text i {
      color: var(--secondary-gold);
    }
    
    .powered-by {
      display: flex;
      align-items: center;
      justify-content: flex-end;
      color: white;
    }
    
    .powered-by img {
      height: 18px;
      margin-left: 6px;
      filter: brightness(0) invert(1);
    }
    
    .powered-by-link {
      display: flex;
      align-items: center;
      text-decoration: none;
      color: var(--secondary-gold);
      transition: opacity 0.3s ease;
    }
    
    .powered-by-link:hover {
      opacity: 0.8;
      color: white;
    }
    
    /* Support badge */
    .support-badge {
      background: linear-gradient(135deg, var(--secondary-gold), #e6b800);
      color: var(--dark-blue);
      font-weight: 600;
      padding: 0.5rem 1rem;
      border: 1px solid var(--dark-blue);
    }
    
    /* Breadcrumbs */
    .breadcrumb-custom .breadcrumb {
      background-color: transparent;
      padding: 0;
      margin: 1rem 1rem 0;
    }
    
    .breadcrumb-custom .breadcrumb-item a {
      color: var(--primary-blue);
      text-decoration: none;
      font-weight: 500;
    }
    
    .breadcrumb-custom .breadcrumb-item a:hover {
      color: var(--secondary-gold);
    }
    
    .breadcrumb-custom .breadcrumb-item.active {
      color: var(--dark-blue);
      font-weight: 600;
    }
    
    .breadcrumb-item + .breadcrumb-item::before {
      color: var(--secondary-gold);
    }
    
    /* Action buttons */
    .action-buttons {
      display: flex;
      gap: 0.5rem;
    }
    
    .btn-sm {
      padding: 0.25rem 0.5rem;
      font-size: 0.8rem;
      border-radius: 0.25rem;
    }
    
    .btn-edit {
      background: linear-gradient(135deg, #28a745, #218838);
      color: white;
      border: none;
    }
    
    .btn-edit:hover {
      background: linear-gradient(135deg, #218838, #1e7e34);
      transform: translateY(-2px);
    }
    
    .btn-delete {
      background: linear-gradient(135deg, #dc3545, #c82333);
      color: white;
      border: none;
    }
    
    .btn-delete:hover {
      background: linear-gradient(135deg, #c82333, #bd2130);
      transform: translateY(-2px);
    }
    
    .btn-view {
      background: linear-gradient(135deg, #17a2b8, #138496);
      color: white;
      border: none;
    }
    
    .btn-view:hover {
      background: linear-gradient(135deg, #138496, #117a8b);
      transform: translateY(-2px);
    }
    
    .btn-primary {
      background: linear-gradient(135deg, var(--primary-blue), var(--dark-blue));
      border-color: var(--secondary-gold);
      color: white;
    }
    
    .btn-primary:hover {
      background: linear-gradient(135deg, var(--secondary-gold), #e6b800);
      border-color: var(--dark-blue);
      color: var(--dark-blue);
    }
    
    .btn-success {
      background: linear-gradient(135deg, #28a745, #218838);
      border: none;
    }
    
    .btn-success:hover {
      background: linear-gradient(135deg, #218838, #1e7e34);
    }
    
    .btn-secondary {
      background: linear-gradient(135deg, #6c757d, #545b62);
      border: none;
    }
    
    .btn-secondary:hover {
      background: linear-gradient(135deg, #545b62, #3d4247);
    }
    
    .btn-action {
      padding: 0.5rem 1rem;
      border-radius: 0.25rem;
      font-weight: 600;
      transition: all 0.3s;
      font-size: 0.85rem;
    }
    
    /* Alert styles */
    .alert {
      padding: 0.75rem 1rem;
      border-radius: 0.25rem;
      margin: 1rem;
    }
    
    .alert-success {
      background-color: #d4edda;
      border-color: #c3e6cb;
      color: #155724;
    }
    
    .alert-danger {
      background-color: #f8d7da;
      border-color: #f5c6cb;
      color: #721c24;
    }
    
    .alert-info {
      background-color: var(--light-gold);
      border-color: var(--secondary-gold);
      color: var(--dark-blue);
    }
    
    /* Info cards */
    .info-card {
      background: linear-gradient(135deg, var(--light-gold) 0%, #ffffff 100%);
      border-left: 4px solid var(--secondary-gold);
      padding: 0.75rem;
      margin-bottom: 0.5rem;
      border-radius: 0 0.25rem 0.25rem 0;
      color: var(--dark-blue);
    }
    
    .info-card i {
      color: var(--primary-blue);
    }
    
    /* Form elements */
    .form-select, .form-label {
      font-size: 0.85rem;
    }
    
    .form-select:focus {
      border-color: var(--secondary-gold);
      box-shadow: 0 0 0 0.25rem rgba(255, 215, 0, 0.25);
    }
    
    .form-label i {
      color: var(--secondary-gold);
    }
    
    /* Empty state */
    .empty-state {
      text-align: center;
      padding: 2rem;
      color: #6c757d;
    }
    
    .empty-state i {
      font-size: 3rem;
      margin-bottom: 1rem;
      color: var(--primary-blue);
    }
    
    .empty-state h5 {
      color: var(--dark-blue);
    }
    
    /* Attendance stats */
    .attendance-stats {
      display: flex;
      gap: 1rem;
      margin-bottom: 1rem;
    }
    
    .stat-card {
      background: linear-gradient(135deg, var(--light-gold) 0%, #ffffff 100%);
      padding: 0.5rem 1rem;
      border-radius: 0.25rem;
      text-align: center;
      flex: 1;
      border: 1px solid var(--secondary-gold);
    }
    
    .stat-value {
      font-size: 1.5rem;
      font-weight: bold;
      color: var(--primary-blue);
    }
    
    .stat-label {
      font-size: 0.75rem;
      color: var(--dark-blue);
    }
    
    /* Code style */
    code {
      background-color: var(--light-gold);
      color: var(--dark-blue);
      padding: 0.2rem 0.4rem;
      border-radius: 0.25rem;
      font-weight: 600;
    }
    
    /* Page heading */
    .text-gray-800 {
      color: var(--dark-blue);
      font-weight: 700;
    }
    
    /* Responsive */
    @media (max-width: 768px) {
      .row {
        flex-direction: column;
      }
      
      .btn-primary {
        width: 100%;
        margin-top: 0.5rem;
      }
      
      .attendance-stats {
        flex-direction: column;
      }
      
      .attendance-table th, .attendance-table td {
        font-size: 0.8rem;
        padding: 0.5rem;
      }
    }
  </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="coll_logo.png" alt="Henzy Royal International School" height="35" style="border-radius: 4px;">
        HENZY ROYAL INT'L SCHOOL
      </a>
      <div class="ms-auto d-flex align-items-center">
        <div class="admin-info me-3">
          <span class="admin-name"><?php echo htmlspecialchars($adminName ?? 'Admin'); ?></span>
          <span class="admin-access">(Administrator)</span>
          <i class="fas fa-user-circle admin-icon"></i>
        </div>
        <a href="logout.php" class="btn btn-sm btn-outline-light">
          <i class="fas fa-sign-out-alt"></i> Logout
        </a>
      </div>
    </div>
  </nav>

  <!-- Sidebar -->
  <nav id="sidebar" class="sidebar">
    <div class="position-sticky pt-3">
      <div class="sidebar-logo d-none d-lg-block">
        <div class="logo-text">
          H.R.<span>I.S</span>
        </div>
        <div class="logo-tagline">
          THE PRIDE OF EXCELLENCE
        </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">
            <i class="fas fa-fw fa-tachometer-alt"></i>
            Admin Dashboard
          </a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="edit_scores_subject.php">
            <i class="fas fa-fw fa-edit"></i>
            Edit Subject Scores
          </a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="download_broadsheet.php">
            <i class="fas fa-fw fa-file-pdf"></i>
            Result Broadsheet
          </a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="list_uploaded_results.php">
            <i class="fas fa-fw fa-list"></i>
            Uploaded Results
          </a>
        </li>
        <li class="nav-item">
          <a class="nav-link active" href="edit_comments_attendance.php">
            <i class="fas fa-fw fa-comments"></i>
            Attendance & Comments
          </a>
        </li>
      </ul>
    </div>
  </nav>

  <!-- Main Content -->
  <main class="main-content">
    <!-- Welcome Banner -->
    <div class="welcome-banner">
      <div class="d-flex justify-content-between align-items-center">
        <div>
          <h4 class="mb-1"><i class="fas fa-crown me-2" style="color: var(--secondary-gold);"></i>Attendance & Comments Management</h4>
          <p class="mb-0 small">Henzy Royal International School - Admin Dashboard</p>
        </div>
        <div class="d-none d-sm-inline-block">
          <span class="badge support-badge p-1">
            <i class="fas fa-calendar-alt me-1"></i> Attendance System
          </span>
        </div>
      </div>
    </div>

    <!-- Breadcrumbs -->
    <div class="breadcrumb-custom">
      <nav aria-label="breadcrumb">
        <ol class="breadcrumb">
          <li class="breadcrumb-item"><a href="main.php">Admin Dashboard</a></li>
          <li class="breadcrumb-item active">Attendance & Comments</li>
        </ol>
      </nav>
    </div>

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

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

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

    <?php if (!empty($page_title) && !empty($class) && !empty($term) && !empty($year)): ?>
      <div class="form-container">
        <div class="row">
          <div class="col-md-8">
            <div class="info-card">
              <h6 class="mb-1"><i class="fas fa-edit me-2"></i>Modifying Attendance & Comments For:</h6>
              <p class="mb-0"><?php echo htmlspecialchars($page_title); ?></p>
            </div>
          </div>
          <div class="col-md-4">
            <div class="info-card">
              <h6 class="mb-1"><i class="fas fa-users me-2"></i>Total Records: <?php echo $total_results_count; ?></h6>
              <p class="mb-0 small">Number of student records found</p>
            </div>
          </div>
        </div>
        
        <?php if (!empty($comments_results)): 
          // Calculate attendance statistics
          $total_present = 0;
          $total_absent = 0;
          $total_schopen = 0;
          
          foreach ($comments_results as $record) {
            $total_present += intval($record['Present']);
            $total_absent += intval($record['Absent']);
            $total_schopen += intval($record['SchOpen']);
          }
        ?>
          <div class="attendance-stats">
            <div class="stat-card">
              <div class="stat-value"><?php echo $total_present; ?></div>
              <div class="stat-label">Total Present</div>
            </div>
            <div class="stat-card">
              <div class="stat-value"><?php echo $total_absent; ?></div>
              <div class="stat-label">Total Absent</div>
            </div>
            <div class="stat-card">
              <div class="stat-value"><?php echo $total_schopen; ?></div>
              <div class="stat-label">School Opening Days</div>
            </div>
          </div>
        <?php endif; ?>
      </div>
    <?php endif; ?>

    <?php if (!empty($comments_results)): ?>
      <div class="table-container">
        <form method="POST">
          <input type="hidden" name="class" value="<?php echo htmlspecialchars($class); ?>">
          <input type="hidden" name="term" value="<?php echo htmlspecialchars($term); ?>">
          <input type="hidden" name="year" value="<?php echo htmlspecialchars($year); ?>">
          
          <div class="d-flex justify-content-between align-items-center mb-3">
            <h5 class="mb-0">
              <i class="fas fa-list me-2" style="color: var(--secondary-gold);"></i>
              Student Attendance & Comments
              <small class="text-muted">(<?php echo $total_results_count; ?> records)</small>
            </h5>
            <div>
              <button type="submit" name="save_all" class="btn btn-success btn-sm">
                <i class="fas fa-save me-1"></i> Save All Changes
              </button>
              <a href="main.php" class="btn btn-primary btn-sm ms-2">
                <i class="fas fa-arrow-left me-1"></i> Back to Dashboard
              </a>
            </div>
          </div>
          
          <div class="table-responsive">
            <table class="attendance-table">
              <thead>
                <tr>
                  <th width="5%">S/N</th>
                  <th class="student-name"><i class="fas fa-user me-1"></i>Student Name</th>
                  <th><i class="fas fa-id-card me-1"></i>Reg No</th>
                  <th class="attendance-col"><i class="fas fa-check-circle me-1"></i>Present</th>
                  <th class="attendance-col"><i class="fas fa-times-circle me-1"></i>Absent</th>
                  <th class="attendance-col"><i class="fas fa-door-open me-1"></i>School Open Days</th>
                  <th class="date-col"><i class="fas fa-calendar-day me-1"></i>Date of Report</th>
                  <th class="date-col"><i class="fas fa-calendar-week me-1"></i>Next Term Begins</th>
                  <th class="comment-col"><i class="fas fa-comment me-1"></i>Teacher's Remarks</th>
                  <th width="10%"><i class="fas fa-cog me-1"></i>Actions</th>
                </tr>
              </thead>
              <tbody>
                <?php foreach ($comments_results as $index => $record): ?>
                  <tr>
                    <td><?php echo $index + 1; ?></td>
                    <td class="student-name"><?php echo htmlspecialchars($record['name']); ?></td>
                    <td><?php echo htmlspecialchars($record['registration_no']); ?></td>
                    <td class="attendance-col">
                      <input type="number" name="present[]" 
                             value="<?php echo htmlspecialchars($record['Present']); ?>" 
                             min="0" max="365" class="present-input" data-row="<?php echo $index; ?>">
                    </td>
                    <td class="attendance-col">
                      <input type="number" name="absent[]" 
                             value="<?php echo htmlspecialchars($record['Absent']); ?>" 
                             min="0" max="365" class="absent-input" data-row="<?php echo $index; ?>">
                    </td>
                    <td class="attendance-col">
                      <input type="number" name="schopen[]" 
                             value="<?php echo htmlspecialchars($record['SchOpen']); ?>" 
                             min="0" max="365" class="schopen-input" data-row="<?php echo $index; ?>" required>
                    </td>
                    <td class="date-col">
                      <input type="date" name="dateofreport[]" 
                             value="<?php echo htmlspecialchars($record['DateOfReport']); ?>"
                             class="date-input">
                    </td>
                    <td class="date-col">
                      <input type="date" name="nexttermbegins[]" 
                             value="<?php echo htmlspecialchars($record['NextTermBegins']); ?>"
                             class="date-input">
                    </td>
                    <td class="comment-col">
                      <textarea name="teachersremarks[]" rows="2" 
                                placeholder="Enter teacher's remarks..." 
                                class="remarks-input"><?php echo htmlspecialchars($record['TeachersRemarks']); ?></textarea>
                    </td>
                    <td>
                      <input type="hidden" name="id[]" value="<?php echo $record['id']; ?>">
                      <div class="action-buttons">
                        <button type="button" class="btn btn-delete btn-sm" 
                                onclick="confirmDelete(<?php echo $record['id']; ?>, '<?php echo addslashes($record['name']); ?>')"
                                title="Delete Record">
                          <i class="fas fa-trash-alt"></i>
                        </button>
                      </div>
                    </td>
                  </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
          </div>
          
          <div class="mt-3">
            <button type="submit" name="save_all" class="btn btn-success btn-action">
              <i class="fas fa-save me-1"></i> Save All Changes
            </button>
            <button type="button" class="btn btn-secondary btn-action ms-2" onclick="resetForm()">
              <i class="fas fa-undo me-1"></i> Reset Changes
            </button>
            <button type="button" class="btn btn-primary btn-action ms-2" onclick="exportToCSV()">
              <i class="fas fa-download me-1"></i> Export to CSV
            </button>
          </div>
          
          <!-- Hidden delete form -->
          <input type="hidden" name="delete_id" id="delete_id" value="">
          <input type="hidden" name="delete" id="delete" value="">
        </form>
        
        <div class="mt-3">
          <div class="alert alert-info py-2">
            <h6 class="mb-1"><i class="fas fa-info-circle me-1" style="color: var(--secondary-gold);"></i> Instructions</h6>
            <div class="row small">
              <div class="col-md-6">
                <i class="fas fa-check-circle text-success me-1"></i> Present, Absent, and School Open Days must be numeric values<br>
                <i class="fas fa-exclamation-triangle text-warning me-1"></i> Present + Absent cannot exceed School Open Days
              </div>
              <div class="col-md-6">
                <i class="fas fa-calendar-alt text-info me-1"></i> Date fields should be in YYYY-MM-DD format<br>
                <i class="fas fa-save text-success me-1"></i> Click "Save All Changes" to update all records at once
              </div>
            </div>
          </div>
        </div>
      </div>
    <?php elseif ($_SERVER["REQUEST_METHOD"] == "POST" && empty($comments_results)): ?>
      <div class="form-container text-center py-4">
        <i class="fas fa-search fa-3x mb-2" style="color: var(--primary-blue);"></i>
        <h5 class="text-muted">No Records Found</h5>
        <p class="mb-0">There are no attendance records for the selected criteria.</p>
      </div>
    <?php else: ?>
      <div class="form-container text-center py-4">
        <i class="fas fa-comments fa-3x mb-2" style="color: var(--primary-blue);"></i>
        <h5 class="text-muted">Attendance & Comments Management</h5>
        <p class="mb-0">Select a class, term, and academic year to edit attendance and comments.</p>
      </div>
    <?php endif; ?>
  </main>

  <!-- Footer -->
  <footer class="footer">
    <div class="container-fluid">
      <div class="row align-items-center">
        <div class="col-md-6">
          <span class="copyright-text">
            <i class="fas fa-copyright me-1"></i> <?php echo date("Y"); ?> Henzy Royal International School
          </span>
        </div>
        <div class="col-md-6">
          <div class="powered-by">
            <a href="https://dataswift.com.ng" target="_blank" rel="noopener noreferrer" class="powered-by-link">
              <span>Powered by DataSwift Coders</span>
              <img src="datalogo.png" alt="DataSwift Logo">
            </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>
  
  <!-- Custom Scripts -->
  <script>
    // Toggle sidebar on mobile
    document.getElementById('sidebarToggle').addEventListener('click', function() {
      document.getElementById('sidebar').classList.toggle('active');
      document.querySelector('.main-content').classList.toggle('active');
      document.querySelector('.footer').classList.toggle('active');
    });
    
    // Close sidebar when clicking outside on mobile
    document.addEventListener('click', function(event) {
      const sidebar = document.getElementById('sidebar');
      const sidebarToggle = document.getElementById('sidebarToggle');
      
      if (window.innerWidth < 992 && 
          !sidebar.contains(event.target) && 
          !sidebarToggle.contains(event.target) && 
          sidebar.classList.contains('active')) {
        sidebar.classList.remove('active');
        document.querySelector('.main-content').classList.remove('active');
        document.querySelector('.footer').classList.remove('active');
      }
    });
    
    // Delete confirmation function
    function confirmDelete(id, name) {
      if (confirm(`Are you sure you want to delete the record for:\n\n${name}?\n\nThis action cannot be undone!`)) {
        document.getElementById('delete_id').value = id;
        document.getElementById('delete').value = '1';
        
        // Submit the form
        document.forms[0].submit();
      }
    }
    
    // Reset form function
    function resetForm() {
      if (confirm('Are you sure you want to reset all changes?')) {
        location.reload();
      }
    }
    
    // Export to CSV function
    function exportToCSV() {
      const table = document.querySelector('.attendance-table');
      let csv = [];
      
      // Get headers
      const headers = [];
      table.querySelectorAll('thead th').forEach(header => {
        if (!header.textContent.includes('Actions')) {
          headers.push(header.textContent.replace(/[^\w\s]/gi, '').trim());
        }
      });
      csv.push(headers.join(','));
      
      // Get data rows (skip action column)
      table.querySelectorAll('tbody tr').forEach(row => {
        const rowData = [];
        row.querySelectorAll('td').forEach((cell, index) => {
          // Skip the last column (Actions)
          if (index < row.cells.length - 1) {
            let text = cell.textContent.trim();
            // Handle input values
            const input = cell.querySelector('input, textarea');
            if (input) {
              text = input.value.trim();
            }
            // Handle CSV formatting
            if (text.includes(',') || text.includes('"') || text.includes('\n')) {
              text = '"' + text.replace(/"/g, '""') + '"';
            }
            rowData.push(text);
          }
        });
        csv.push(rowData.join(','));
      });
      
      // Create and download CSV file
      const csvContent = csv.join('\n');
      const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
      const link = document.createElement('a');
      const url = URL.createObjectURL(blob);
      
      link.setAttribute('href', url);
      link.setAttribute('download', `attendance_${new Date().toISOString().slice(0,10)}.csv`);
      link.style.visibility = 'hidden';
      
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }
    
    // Auto-calculate attendance percentage
    document.querySelectorAll('.present-input, .absent-input, .schopen-input').forEach(input => {
      input.addEventListener('input', function() {
        const row = this.closest('tr');
        const present = parseInt(row.querySelector('.present-input').value) || 0;
        const absent = parseInt(row.querySelector('.absent-input').value) || 0;
        const schopen = parseInt(row.querySelector('.schopen-input').value) || 0;
        
        // Validate that present + absent doesn't exceed school open days
        if (schopen > 0 && (present + absent) > schopen) {
          row.querySelector('.present-input').classList.add('is-invalid');
          row.querySelector('.absent-input').classList.add('is-invalid');
          row.querySelector('.schopen-input').classList.add('is-invalid');
          alert('Present + Absent cannot exceed School Open Days');
        } else {
          row.querySelector('.present-input').classList.remove('is-invalid');
          row.querySelector('.absent-input').classList.remove('is-invalid');
          row.querySelector('.schopen-input').classList.remove('is-invalid');
        }
      });
    });
    
    // Focus first input field if records exist
    <?php if (!empty($comments_results)): ?>
      document.addEventListener('DOMContentLoaded', function() {
        const firstInput = document.querySelector('.present-input');
        if (firstInput) {
          firstInput.focus();
        }
      });
    <?php endif; ?>
    
    // Set today's date as default for empty date fields
    document.addEventListener('DOMContentLoaded', function() {
      const today = new Date().toISOString().split('T')[0];
      document.querySelectorAll('.date-input').forEach(input => {
        if (!input.value) {
          input.value = today;
        }
      });
    });
    
    // Auto-hide alerts after 5 seconds
    setTimeout(() => {
      const alerts = document.querySelectorAll('.alert');
      alerts.forEach(alert => {
        alert.style.transition = 'opacity 0.5s';
        alert.style.opacity = '0';
        setTimeout(() => {
          alert.remove();
        }, 500);
      });
    }, 5000);
  </script>
</body>
</html>