<?php
require_once('source/session.php');
require_once('source/error.php');
require_once('source/dbconfig.php');
require_once('source/function.php');
require_once('source/restrict_user.php');

// Restrict access to teachers only
if (!isTeacherLoggedIn()) {
    $_SESSION['msg'] = 'access_denied';
    header("Location: index.php");
    exit();
}

// Get current teacher information
$teacher_id = getTeacherId();
$teacher_name = getTeacherName();

// Check if teacher_id is provided in URL for viewing specific teacher's results
$view_teacher_id = isset($_GET['teacher_id']) ? $_GET['teacher_id'] : $teacher_id;

// Verify that the teacher can only view their own results unless admin
if ($view_teacher_id != $teacher_id) {
    if ($_SESSION['SESS_ACCESS_LEVEL'] != 'Admin') {
        $_SESSION['error_message'] = "You can only view your own results.";
        header("Location: main.php");
        exit();
    }
}

if (isset($_GET['year']) && isset($_GET['term']) && isset($_GET['class'])) {
    $year = $_GET['year'];
    $term = $_GET['term'];
    $class = $_GET['class'];
} else {
    // Set default values to most recent data for this teacher
    $recent_data = sql($DBH, 
        "SELECT year, term, class FROM tbl_student_results 
         WHERE teacher_no = ? 
         ORDER BY year DESC, term DESC, class ASC 
         LIMIT 1", 
        [$view_teacher_id], 
        "rows"
    );
    
    if (!empty($recent_data)) {
        $year = $recent_data[0]['year'];
        $term = $recent_data[0]['term'];
        $class = $recent_data[0]['class'];
    } else {
        $year = date('Y');
        $term = '1st Term';
        $class = 'SS1';
    }
}

// Fetch all subjects for the given year, term, class, and teacher
$subjectsQuery = "SELECT DISTINCT subject 
                  FROM tbl_student_results 
                  WHERE year = ? AND term = ? AND class = ? AND teacher_no = ?";
$subjectsStmt = $DBH->prepare($subjectsQuery);
$subjectsStmt->execute([$year, $term, $class, $view_teacher_id]);
$subjects = $subjectsStmt->fetchAll(PDO::FETCH_COLUMN); 

// Fetch students with their totals and average for the given year, term, class, and teacher
$studentsQuery = "SELECT DISTINCT registration_no, name,
                        SUM(total) AS total,
                        COUNT(subject) AS total_subjects,
                        ROUND(AVG(total), 2) AS average
                  FROM tbl_student_results
                  WHERE year = ? AND term = ? AND class = ? AND teacher_no = ?
                  GROUP BY registration_no, name
                  ORDER BY average DESC";
$studentsStmt = $DBH->prepare($studentsQuery);
$studentsStmt->execute([$year, $term, $class, $view_teacher_id]);
$students = $studentsStmt->fetchAll(PDO::FETCH_ASSOC); 

// Fetch distinct classes for this teacher
$classesQuery = "SELECT DISTINCT class FROM tbl_student_results WHERE teacher_no = ?";
$classesStmt = $DBH->prepare($classesQuery);
$classesStmt->execute([$view_teacher_id]);
$classes = $classesStmt->fetchAll(PDO::FETCH_ASSOC);

// Fetch distinct years for this teacher
$yearsQuery = "SELECT DISTINCT year FROM tbl_student_results WHERE teacher_no = ? ORDER BY year DESC";
$yearsStmt = $DBH->prepare($yearsQuery);
$yearsStmt->execute([$view_teacher_id]);
$years = $yearsStmt->fetchAll(PDO::FETCH_ASSOC);

// Fetch distinct terms for this teacher
$termsQuery = "SELECT DISTINCT term FROM tbl_student_results WHERE teacher_no = ?";
$termsStmt = $DBH->prepare($termsQuery);
$termsStmt->execute([$view_teacher_id]);
$terms = $termsStmt->fetchAll(PDO::FETCH_ASSOC);
?>

<!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>Class Broadsheet - VERBUM DEI INT'L COLLEGE</title>
  <link rel="icon" type="image/png" href="https://portal.vda.com.ng/coll_admin/coll_logo.jpg">
  
  <!-- 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">
  
  <!-- Custom CSS -->
  <style>
    :root {
      --primary-color: #1976d2;
      --secondary-color: #64b5f6;
      --accent-color: #bbdefb;
      --dark-color: #0d47a1;
      --light-color: #e3f2fd;
    }
    
    body {
      font-family: 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
      background-color: var(--light-color);
      padding-top: 20px;
    }
    
    .navbar {
      background-color: var(--primary-color);
      box-shadow: 0 0.15rem 1.75rem 0 rgba(33, 37, 41, 0.1);
      color: white;
      margin-bottom: 20px;
    }
    
    .card {
      border: none;
      border-radius: 0.5rem;
      box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.1);
      margin-bottom: 1.5rem;
    }
    
    .card-header {
      background-color: var(--accent-color);
      border-bottom: 1px solid var(--secondary-color);
      font-weight: 700;
      color: var(--dark-color);
    }
    
    .teacher-info {
      display: flex;
      align-items: center;
      background-color: rgba(255,255,255,0.2);
      padding: 8px 12px;
      border-radius: 0.5rem;
      color: white;
    }
    
    .teacher-name {
      margin-right: 5px;
      font-weight: 600;
    }
    
    .teacher-badge {
      font-style: italic;
      opacity: 0.8;
      margin-right: 10px;
      font-size: 0.9rem;
    }
    
    .teacher-icon {
      font-size: 1.5rem;
      color: white;
    }
    
    .footer {
      background-color: var(--dark-color);
      color: white;
      padding: 20px 0;
      margin-top: 30px;
    }
    
    /* Broadsheet specific styles */
    th.vertical-header {
        writing-mode: vertical-rl;
        transform: rotate(180deg);
        white-space: nowrap;
        font-size: 10px;
        padding: 5px 3px;
    }
    
    .table {
        font-size: 11px;
        border-collapse: separate;
        border-spacing: 0;
    }
    
    .student-name {
        text-transform: capitalize;
        font-weight: 600;
    }
    
    .broadsheet-header {
        background: linear-gradient(135deg, var(--primary-color) 0%, var(--dark-color) 100%);
        color: white;
        padding: 1rem;
        border-radius: 0.5rem;
        margin-bottom: 1rem;
    }
    
    .print-btn {
        background: var(--primary-color);
        color: white;
        border: none;
        padding: 10px 20px;
        border-radius: 0.3rem;
        cursor: pointer;
        transition: background 0.3s;
    }
    
    .print-btn:hover {
        background: var(--dark-color);
    }
    
    .stats-card {
        background: white;
        border-radius: 0.5rem;
        padding: 1rem;
        text-align: center;
        box-shadow: 0 2px 5px rgba(0,0,0,0.1);
    }
    
    .stats-number {
        font-size: 2rem;
        font-weight: bold;
        color: var(--primary-color);
    }
    
    /* Colorful alternating subject columns */
    .subject-group {
        border-left: 2px solid #dee2e6;
        border-right: 2px solid #dee2e6;
    }
    
    /* Subject header colors */
    .subject-header-0 {
        background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%) !important;
        color: #0d47a1 !important;
    }
    
    .subject-header-1 {
        background: linear-gradient(135deg, #e8f5e9 0%, #c8e6c9 100%) !important;
        color: #1b5e20 !important;
    }
    
    .subject-header-2 {
        background: linear-gradient(135deg, #fff3e0 0%, #ffcc80 100%) !important;
        color: #e65100 !important;
    }
    
    .subject-header-3 {
        background: linear-gradient(135deg, #fce4ec 0%, #f8bbd9 100%) !important;
        color: #880e4f !important;
    }
    
    .subject-header-4 {
        background: linear-gradient(135deg, #f3e5f5 0%, #e1bee7 100%) !important;
        color: #4a148c !important;
    }
    
    .subject-header-5 {
        background: linear-gradient(135deg, #e0f2f1 0%, #b2dfdb 100%) !important;
        color: #004d40 !important;
    }
    
    .subject-header-6 {
        background: linear-gradient(135deg, #fff8e1 0%, #ffecb3 100%) !important;
        color: #ff6f00 !important;
    }
    
    .subject-header-7 {
        background: linear-gradient(135deg, #e8eaf6 0%, #c5cae9 100%) !important;
        color: #1a237e !important;
    }
    
    /* Subject column colors */
    .subject-col-0 {
        background-color: #f8fbff !important;
        border-left: 2px solid #bbdefb;
        border-right: 2px solid #bbdefb;
    }
    
    .subject-col-1 {
        background-color: #f8fff8 !important;
        border-left: 2px solid #c8e6c9;
        border-right: 2px solid #c8e6c9;
    }
    
    .subject-col-2 {
        background-color: #fffbf0 !important;
        border-left: 2px solid #ffcc80;
        border-right: 2px solid #ffcc80;
    }
    
    .subject-col-3 {
        background-color: #fff5f9 !important;
        border-left: 2px solid #f8bbd9;
        border-right: 2px solid #f8bbd9;
    }
    
    .subject-col-4 {
        background-color: #faf5fc !important;
        border-left: 2px solid #e1bee7;
        border-right: 2px solid #e1bee7;
    }
    
    .subject-col-5 {
        background-color: #f0f9f8 !important;
        border-left: 2px solid #b2dfdb;
        border-right: 2px solid #b2dfdb;
    }
    
    .subject-col-6 {
        background-color: #fffef5 !important;
        border-left: 2px solid #ffecb3;
        border-right: 2px solid #ffecb3;
    }
    
    .subject-col-7 {
        background-color: #f5f6ff !important;
        border-left: 2px solid #c5cae9;
        border-right: 2px solid #c5cae9;
    }
    
    /* Subject total column colors (darker) */
    .subject-total-0 {
        background: linear-gradient(135deg, #bbdefb 0%, #90caf9 100%) !important;
        color: #0d47a1 !important;
        font-weight: bold !important;
        border-left: 2px solid #64b5f6;
        border-right: 2px solid #64b5f6;
    }
    
    .subject-total-1 {
        background: linear-gradient(135deg, #c8e6c9 0%, #a5d6a7 100%) !important;
        color: #1b5e20 !important;
        font-weight: bold !important;
        border-left: 2px solid #81c784;
        border-right: 2px solid #81c784;
    }
    
    .subject-total-2 {
        background: linear-gradient(135deg, #ffcc80 0%, #ffb74d 100%) !important;
        color: #e65100 !important;
        font-weight: bold !important;
        border-left: 2px solid #ff9800;
        border-right: 2px solid #ff9800;
    }
    
    .subject-total-3 {
        background: linear-gradient(135deg, #f8bbd9 0%, #f48fb1 100%) !important;
        color: #880e4f !important;
        font-weight: bold !important;
        border-left: 2px solid #ec407a;
        border-right: 2px solid #ec407a;
    }
    
    .subject-total-4 {
        background: linear-gradient(135deg, #e1bee7 0%, #ce93d8 100%) !important;
        color: #4a148c !important;
        font-weight: bold !important;
        border-left: 2px solid #ab47bc;
        border-right: 2px solid #ab47bc;
    }
    
    .subject-total-5 {
        background: linear-gradient(135deg, #b2dfdb 0%, #80cbc4 100%) !important;
        color: #004d40 !important;
        font-weight: bold !important;
        border-left: 2px solid #26a69a;
        border-right: 2px solid #26a69a;
    }
    
    .subject-total-6 {
        background: linear-gradient(135deg, #ffecb3 0%, #ffe082 100%) !important;
        color: #ff6f00 !important;
        font-weight: bold !important;
        border-left: 2px solid #ffca28;
        border-right: 2px solid #ffca28;
    }
    
    .subject-total-7 {
        background: linear-gradient(135deg, #c5cae9 0%, #9fa8da 100%) !important;
        color: #1a237e !important;
        font-weight: bold !important;
        border-left: 2px solid #5c6bc0;
        border-right: 2px solid #5c6bc0;
    }
    
    /* Student info columns */
    .student-info {
        background: linear-gradient(135deg, #f5f5f5 0%, #e0e0e0 100%) !important;
        font-weight: bold;
        color: #333;
    }
    
    /* Summary columns */
    .summary-col {
        background: linear-gradient(135deg, #fff3cd 0%, #ffeaa7 100%) !important;
        font-weight: bold;
        color: #856404;
    }
    
    .position-col {
        background: linear-gradient(135deg, #d4edda 0%, #c3e6cb 100%) !important;
        font-weight: bold;
        color: #155724;
    }
    
    /* Print styles */
    @media print {
        .sidebar, .navbar, .no-print, .card, .footer, .stats-card, .broadsheet-header {
            display: none !important;
        }
        
        body {
            padding-top: 0 !important;
            background: white !important;
            font-size: 10px !important;
            margin: 0 !important;
        }
        
        .table {
            font-size: 8px !important;
            border-collapse: collapse !important;
            width: 100% !important;
        }
        
        .table th, .table td {
            border: 1px solid #000 !important;
            padding: 2px !important;
        }
        
        #broadsheet-table {
            margin: 0 !important;
            padding: 0 !important;
        }
        
        /* Print header */
        .print-header {
            display: block !important;
            text-align: center;
            margin-bottom: 10px;
            font-size: 12px !important;
            font-weight: bold;
        }
        
        /* Remove colors for print */
        .subject-header-0, .subject-header-1, .subject-header-2, .subject-header-3,
        .subject-header-4, .subject-header-5, .subject-header-6, .subject-header-7,
        .subject-col-0, .subject-col-1, .subject-col-2, .subject-col-3,
        .subject-col-4, .subject-col-5, .subject-col-6, .subject-col-7,
        .subject-total-0, .subject-total-1, .subject-total-2, .subject-total-3,
        .subject-total-4, .subject-total-5, .subject-total-6, .subject-total-7,
        .student-info, .summary-col, .position-col {
            background: white !important;
            color: black !important;
            border: 1px solid #000 !important;
        }
        
        /* Ensure proper page breaks */
        table { page-break-inside:auto; }
        tr    { page-break-inside:avoid; page-break-after:auto; }
    }
    
    .dashboard-btn {
        background: var(--dark-color);
        color: white;
        border: none;
        padding: 10px 20px;
        border-radius: 0.3rem;
        text-decoration: none;
        display: inline-block;
        transition: background 0.3s;
    }
    
    .dashboard-btn:hover {
        background: var(--primary-color);
        color: white;
    }
    
    .table th {
        border-bottom: 2px solid #dee2e6;
    }
  </style>
</head>

<body>
  <!-- Top Navigation (Simplified for this page) -->
  <nav class="navbar">
    <div class="container-fluid">
      <a class="navbar-brand" href="#">
        VERBUM DEI INT'L COLLEGE - Broadsheet
      </a>
      <div class="ms-auto d-flex align-items-center">
        <div class="teacher-info me-3">
          <span class="teacher-name"><?php echo htmlspecialchars($teacher_name); ?></span>
          <span class="teacher-badge">(Teacher)</span>
          <i class="fas fa-chalkboard-teacher teacher-icon"></i>
        </div>
        <a href="main.php" class="dashboard-btn me-2">
          <i class="fas fa-arrow-left me-1"></i> Back to Dashboard
        </a>
        <div class="dropdown">
          <button class="btn btn-outline-light dropdown-toggle" type="button" id="profileDropdown" data-bs-toggle="dropdown">
            <i class="fas fa-user"></i>
          </button>
          <ul class="dropdown-menu dropdown-menu-end">
            <li><a class="dropdown-item" href="edit_profile.php"><i class="fas fa-user-edit me-2"></i>Edit Profile</a></li>
            <li><hr class="dropdown-divider"></li>
            <li><a class="dropdown-item" href="logout.php"><i class="fas fa-sign-out-alt me-2"></i>Logout</a></li>
          </ul>
        </div>
      </div>
    </div>
  </nav>

  <!-- Main Content -->
  <main>
    <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-file-alt me-2"></i>Class Broadsheet
            </h1>
            <div class="d-none d-sm-inline-block">
                <span class="badge bg-light text-dark p-2">
                    <i class="fas fa-phone-alt me-1"></i> Support: MENDOH - 08032929756
                </span>
            </div>
        </div>

        <!-- Search Form -->
        <div class="card shadow mb-4">
            <div class="card-header">
                <h6 class="m-0 font-weight-bold text-primary">
                    <i class="fas fa-search me-2"></i>Select Class and Term
                </h6>
            </div>
            <div class="card-body">
                <form method="GET" class="row g-3">
                    <?php if (isset($_GET['teacher_id'])): ?>
                        <input type="hidden" name="teacher_id" value="<?php echo htmlspecialchars($_GET['teacher_id']); ?>">
                    <?php endif; ?>
                    
                    <div class="col-md-4">
                        <label for="class" class="form-label">Class</label>
                        <select class="form-select" name="class" id="class" required>
                            <?php foreach ($classes as $classItem) : ?>
                                <option value="<?php echo htmlspecialchars($classItem['class']); ?>" 
                                    <?php echo ($class == $classItem['class']) ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($classItem['class']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="col-md-4">
                        <label for="year" class="form-label">Academic Year</label>
                        <select class="form-select" name="year" id="year" required>
                            <?php foreach ($years as $yearItem) : ?>
                                <option value="<?php echo htmlspecialchars($yearItem['year']); ?>" 
                                    <?php echo ($year == $yearItem['year']) ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($yearItem['year']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="col-md-4">
                        <label for="term" class="form-label">Term</label>
                        <select class="form-select" name="term" id="term" required>
                            <?php foreach ($terms as $termItem) : ?>
                                <option value="<?php echo htmlspecialchars($termItem['term']); ?>" 
                                    <?php echo ($term == $termItem['term']) ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($termItem['term']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="col-12">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-table me-1"></i> Generate Broadsheet
                        </button>
                        <a href="main.php" class="btn btn-outline-secondary">
                            <i class="fas fa-arrow-left me-1"></i> Back to Dashboard
                        </a>
                    </div>
                </form>
            </div>
        </div>

        <?php if (isset($_GET['class']) && isset($_GET['year']) && isset($_GET['term'])): ?>
        
        <!-- Statistics Cards -->
        <div class="row mb-4 no-print">
            <div class="col-md-3">
                <div class="stats-card">
                    <div class="stats-number"><?php echo count($students); ?></div>
                    <div>Total Students</div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stats-card">
                    <div class="stats-number"><?php echo count($subjects); ?></div>
                    <div>Subjects</div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stats-card">
                    <div class="stats-number">
                        <?php 
                        $total_records = count($students) * count($subjects);
                        echo $total_records; 
                        ?>
                    </div>
                    <div>Result Records</div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stats-card">
                    <div class="stats-number">
                        <?php 
                        $avg_score = $students ? round(array_sum(array_column($students, 'average')) / count($students), 1) : 0;
                        echo $avg_score; 
                        ?>
                    </div>
                    <div>Class Average</div>
                </div>
            </div>
        </div>

        <!-- Print Button -->
        <div class="text-center mb-3 no-print">
            <button onclick="printBroadsheet()" class="print-btn">
                <i class="fas fa-print me-1"></i> Print/Save Broadsheet
            </button>
        </div>

        <!-- Broadsheet Table -->
        <div class="table-responsive" id="broadsheet-table">
            <!-- Print Header (hidden by default) -->
            <div class="print-header" style="display: none;">
                <h3>VERBUM DEI INT'L COLLEGE</h3>
                <h4>Class Broadsheet - <?php echo htmlspecialchars("$class, $term, $year"); ?></h4>
                <p>Generated by: <?php echo htmlspecialchars($teacher_name); ?> | Date: <?php echo date('F j, Y'); ?></p>
                <hr>
            </div>
            
            <table class="table table-bordered table-sm">
                <thead class="table-dark">
                    <tr>
                        <th rowspan="2" style="font-size:10px" class="student-info">S/N</th>
                        <th rowspan="2" style="font-size:10px; width:200px" class="student-info student-name">Student Name</th>
                        <th rowspan="2" style="font-size:10px; width:80px" class="student-info">Adm No</th>
                        
                        <?php foreach ($subjects as $index => $subject) : 
                            $subjectIndex = $index % 8; // Cycle through 8 colors
                        ?>
                            <th colspan="4" style="font-size:10px" class="text-center subject-header-<?php echo $subjectIndex; ?>">
                                <?php echo htmlspecialchars($subject); ?>
                            </th>
                        <?php endforeach; ?>
                        
                        <th rowspan="2" style="font-size:10px" class="summary-col">Total</th>
                        <th rowspan="2" style="font-size:10px" class="summary-col">Average</th>
                        <th rowspan="2" style="font-size:10px" class="position-col">Position</th>
                    </tr>
                    <tr>
                        <?php foreach ($subjects as $index => $subject) : 
                            $subjectIndex = $index % 8; // Cycle through 8 colors
                        ?>
                            <th style="font-size:8px" class="subject-col-<?php echo $subjectIndex; ?>">CA1</th>
                            <th style="font-size:8px" class="subject-col-<?php echo $subjectIndex; ?>">CA2</th>
                            <th style="font-size:8px" class="subject-col-<?php echo $subjectIndex; ?>">Exam</th>
                            <th style="font-size:8px" class="subject-total-<?php echo $subjectIndex; ?>"><b>Total</b></th>
                        <?php endforeach; ?>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $serialNumber = 1;
                    foreach ($students as $student) : 
                    ?>
                        <tr>
                            <td style="font-size:10px" class="student-info"><?php echo $serialNumber++; ?></td>
                            <td style="font-size:10px" class="student-info student-name">
                                <b><?php echo ucwords(strtolower($student['name'])); ?></b>
                            </td>
                            <td style="font-size:10px" class="student-info"><b><?php echo htmlspecialchars($student['registration_no']); ?></b></td>
                            
                            <?php
                            $studentTotal = 0;
                            foreach ($subjects as $index => $subject) :
                                $subjectIndex = $index % 8; // Cycle through 8 colors
                                $subjectQuery = "SELECT test1 AS ca1, test2 AS ca2, exam
                                             FROM tbl_student_results 
                                             WHERE registration_no = ? AND subject = ? AND class = ? AND term = ? AND year = ? AND teacher_no = ?";
                                $subjectStmt = $DBH->prepare($subjectQuery);
                                $subjectStmt->execute([$student['registration_no'], $subject, $class, $term, $year, $view_teacher_id]);
                                $subjectData = $subjectStmt->fetch(PDO::FETCH_ASSOC);
                                
                                $ca1 = $subjectData['ca1'] ?? 0;
                                $ca2 = $subjectData['ca2'] ?? 0;
                                $exam = $subjectData['exam'] ?? 0;
                                $subjectTotal = $ca1 + $ca2 + $exam;
                                $studentTotal += $subjectTotal;
                                ?>
                                
                                <td style="font-size:10px" class="subject-col-<?php echo $subjectIndex; ?>"><?php echo $ca1; ?></td>
                                <td style="font-size:10px" class="subject-col-<?php echo $subjectIndex; ?>"><?php echo $ca2; ?></td>
                                <td style="font-size:10px" class="subject-col-<?php echo $subjectIndex; ?>"><?php echo $exam; ?></td>
                                <td style="font-size:10px" class="subject-total-<?php echo $subjectIndex; ?>"><b><?php echo $subjectTotal; ?></b></td>
                            <?php endforeach; ?>
                            
                            <td style="font-size:10px" class="summary-col"><b><?php echo $studentTotal; ?></b></td>
                            <td style="font-size:10px" class="summary-col"><?php echo $student['average']; ?></td>
                            <td style="font-size:10px" class="position-col"><b><?php echo $serialNumber - 1; ?></b></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <!-- Analysis Section -->
        <div class="row mt-4 no-print">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h6 class="mb-0"><i class="fas fa-chart-bar me-2"></i>Performance Analysis</h6>
                    </div>
                    <div class="card-body">
                        <ul class="list-group list-group-flush">
                            <li class="list-group-item">
                                Students scoring above 75%: 
                                <span class="badge bg-success float-end">
                                    <?php echo getPerformanceCount($students, 75, 100); ?>
                                </span>
                            </li>
                            <li class="list-group-item">
                                Students scoring 50% - 75%: 
                                <span class="badge bg-warning float-end">
                                    <?php echo getPerformanceCount($students, 50, 75); ?>
                                </span>
                            </li>
                            <li class="list-group-item">
                                Students scoring below 50%: 
                                <span class="badge bg-danger float-end">
                                    <?php echo getPerformanceCount($students, 0, 49.99); ?>
                                </span>
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
            
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h6 class="mb-0"><i class="fas fa-info-circle me-2"></i>Broadsheet Information</h6>
                    </div>
                    <div class="card-body">
                        <p><strong>Generated:</strong> <?php echo date('F j, Y \a\t g:i A'); ?></p>
                        <p><strong>Teacher:</strong> <?php echo htmlspecialchars($teacher_name); ?></p>
                        <p><strong>Class:</strong> <?php echo htmlspecialchars($class); ?></p>
                        <p><strong>Term:</strong> <?php echo htmlspecialchars($term); ?></p>
                        <p><strong>Academic Year:</strong> <?php echo htmlspecialchars($year); ?></p>
                    </div>
                </div>
            </div>
        </div>

        <?php endif; ?>
    </div>
  </main>

  <!-- Footer -->
  <footer class="footer no-print">
      <div class="container-fluid">
          <div class="row align-items-center">
              <div class="col-md-6">
                  <span class="copyright-text">Copyright &copy; VERBUM DEI INT'L COLLEGE <?php echo date("Y"); ?></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</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>
  
  <script>
    // Custom print function for broadsheet
    function printBroadsheet() {
        // Show the print header
        document.querySelector('.print-header').style.display = 'block';
        
        // Print the page
        window.print();
        
        // Hide the print header again after printing (in case user cancels)
        setTimeout(function() {
            document.querySelector('.print-header').style.display = 'none';
        }, 1000);
    }

    // Auto-submit form when selections change (optional)
    document.getElementById('class').addEventListener('change', function() {
        if(document.getElementById('year').value && document.getElementById('term').value) {
            this.form.submit();
        }
    });
    
    document.getElementById('year').addEventListener('change', function() {
        if(document.getElementById('class').value && document.getElementById('term').value) {
            this.form.submit();
        }
    });
    
    document.getElementById('term').addEventListener('change', function() {
        if(document.getElementById('class').value && document.getElementById('year').value) {
            this.form.submit();
        }
    });
  </script>
</body>
</html>

<?php
// Function to get performance count
function getPerformanceCount($students, $min, $max) {
    $count = 0;
    foreach ($students as $student) {
        $average = $student['average'];
        if ($average >= $min && $average <= $max) {
            $count++;
        }
    }
    return $count;
}
?>