<?php
include('session_validator.php');
include("includes/db.php");

$classIds = [];
$sectionIds = [];
$academicYear = '';
$reportRows = [];
$studentsPerPage = 50; // Default value

// Get school details
$school = [];
$school_query = "SELECT * FROM schools LIMIT 1";
$school_result = $conn->query($school_query);
if ($school_result) {
    $school = $school_result->fetch_assoc();
}

// Get all active academic years from studentsub table
$academicYears = [];
$yearQuery = $conn->query("SELECT DISTINCT academic_year FROM studentsub WHERE academic_year IS NOT NULL AND academic_year != '' ORDER BY academic_year DESC");
while ($year = $yearQuery->fetch_assoc()) {
    $academicYears[] = $year['academic_year'];
}

// Get subject reference data
$subjects = [];
$subjectQuery = $conn->query("SELECT subject_code, subject_name FROM subjects WHERE status = 1 ORDER BY subject_code");
while ($subject = $subjectQuery->fetch_assoc()) {
    $subjects[] = $subject;
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Get form data
    $academicYear = isset($_POST['academic_year']) ? $conn->real_escape_string($_POST['academic_year']) : '';
    $classIds = isset($_POST['class_ids']) ? array_map('intval', $_POST['class_ids']) : [];
    $sectionIds = isset($_POST['section_ids']) ? array_map('intval', $_POST['section_ids']) : [];
    $studentsPerPage = isset($_POST['students_per_page']) ? intval($_POST['students_per_page']) : 50;
    
    // Build WHERE conditions
    $whereConditions = [];
    $params = [];
    
    if (!empty($academicYear)) {
        $whereConditions[] = "ss.academic_year = ?";
        $params[] = $academicYear;
    }
    
    if (!empty($classIds)) {
        $classPlaceholders = implode(',', array_fill(0, count($classIds), '?'));
        $whereConditions[] = "s.Class_id IN ($classPlaceholders)";
        $params = array_merge($params, $classIds);
    }
    
    if (!empty($sectionIds)) {
        $sectionPlaceholders = implode(',', array_fill(0, count($sectionIds), '?'));
        $whereConditions[] = "ss.section_id IN ($sectionPlaceholders)";
        $params = array_merge($params, $sectionIds);
    }
    
    // Only query if we have at least academic year and class selection
    if (!empty($academicYear) && !empty($classIds)) {
        $whereClause = !empty($whereConditions) ? "WHERE " . implode(' AND ', $whereConditions) : "";
        
        // Prepare the query with parameter binding for security
        $studentQuery = "
            SELECT s.student_id, s.name AS student_name, s.regd_id, s.Class_id, 
                   c.class, c.class_numeric, ss.section_id, sec.section_name,
                   ss.academic_year,
                   ss.sub1, ss.sub2, ss.sub3, ss.sub4, ss.sub5, ss.sub6, ss.sub7
            FROM students s
            JOIN studentsub ss ON s.student_id = ss.student_id
            JOIN classes c ON s.Class_id = c.class_id
            LEFT JOIN sections sec ON ss.section_id = sec.section_id
            $whereClause
            ORDER BY ss.academic_year DESC, c.class_numeric, sec.section_name, s.name";
        
        $stmt = $conn->prepare($studentQuery);
        
        if ($stmt) {
            // Bind parameters if we have any
            if (!empty($params)) {
                $types = str_repeat('s', count($params)); // All parameters are strings
                $stmt->bind_param($types, ...$params);
            }
            
            $stmt->execute();
            $result = $stmt->get_result();
            
            while ($row = $result->fetch_assoc()) {
                $reportRows[] = [
                    'academic_year' => $row['academic_year'],
                    'class' => $row['class'],
                    'section' => $row['section_name'],
                    'student_id' => $row['student_id'],
                    'name' => $row['student_name'],
                    'regd_no' => $row['regd_id'],
                    'subjects' => [
                        $row['sub1'], $row['sub2'], $row['sub3'], $row['sub4'],
                        $row['sub5'], $row['sub6'], $row['sub7']
                    ]
                ];
            }
            $stmt->close();
        }
    }
    
    // Export CSV if requested
    if (isset($_POST['export_csv'])) {
        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename=student_subject_report_' . date('Y-m-d') . '.csv');
        $output = fopen("php://output", "w");
        fputcsv($output, ['Academic Year', 'Class', 'Section', 'Student ID', 'Name', 'Regd No', 'Sub1', 'Sub2', 'Sub3', 'Sub4', 'Sub5', 'Sub6', 'Sub7']);
        foreach ($reportRows as $row) {
            fputcsv($output, array_merge([
                $row['academic_year'],
                $row['class'],
                $row['section'],
                $row['student_id'],
                $row['name'],
                $row['regd_no']
            ], $row['subjects']));
        }
        fclose($output);
        exit;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>SRMS Admin - Student Subject Report</title>
        <link rel="stylesheet" href="css/bootstrap.min.css" media="screen">
        <link rel="stylesheet" href="css/font-awesome.min.css" media="screen">
        <link rel="stylesheet" href="css/animate-css/animate.min.css" media="screen">
        <link rel="stylesheet" href="css/lobipanel/lobipanel.min.css" media="screen">
        <link rel="stylesheet" href="css/prism/prism.css" media="screen">
        <link rel="stylesheet" href="css/select2/select2.min.css">
        <link rel="stylesheet" href="css/main.css" media="screen">
        <script src="js/modernizr/modernizr.min.js"></script>
        <style>
            .filter-section {
                background: #f8f9fa;
                padding: 15px;
                border-radius: 5px;
                margin-bottom: 15px;
                border: 1px solid #dee2e6;
            }
            
            .export-buttons {
                margin-top: 15px;
                padding-top: 10px;
                border-top: 1px solid #dee2e6;
            }
            
            .selected-filters {
                background: #d1ecf1;
                padding: 8px 12px;
                border-radius: 4px;
                margin-bottom: 12px;
                border-left: 4px solid #0c5460;
                font-size: 13px;
            }
            
            .compact-table {
                font-size: 12px;
            }
            
            .compact-table th,
            .compact-table td {
                padding: 6px 8px !important;
                vertical-align: middle;
            }
            
            .compact-table .btn-sm {
                padding: 2px 6px;
                font-size: 11px;
            }
            
            .subject-cell {
                min-width: 90px;
                max-width: 120px;
                word-break: break-word;
            }
            
            .subject-reference {
                background: #f8f9fa;
                padding: 8px 10px;
                border-radius: 4px;
                margin-bottom: 15px;
                border: 1px solid #dee2e6;
                font-size: 11px;
            }
            
            .subject-reference table {
                margin-bottom: 0;
                font-size: 10px;
            }
            
            .subject-reference th {
                padding: 3px 6px !important;
                background-color: #e9ecef;
            }
            
            .subject-reference td {
                padding: 3px 6px !important;
            }
            
            /* School header styles */
            .school-header {
                text-align: center;
                padding: 15px;
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: white;
                border-radius: 5px;
                margin-bottom: 20px;
                box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            }
            
            .school-name {
                font-size: 24px;
                font-weight: bold;
                margin-bottom: 5px;
            }
            
            .school-address {
                font-size: 14px;
                margin-bottom: 5px;
                opacity: 0.9;
            }
            
            .school-contact {
                font-size: 12px;
                margin-bottom: 10px;
            }
            
            .school-code {
                font-size: 11px;
                background: rgba(255,255,255,0.2);
                padding: 3px 10px;
                border-radius: 15px;
                display: inline-block;
            }
            
            .students-per-page-input {
                max-width: 100px;
            }
            
            .page-info {
                background: #e9ecef;
                padding: 5px 10px;
                border-radius: 4px;
                font-size: 12px;
                margin-right: 10px;
            }
            
            /* Print-specific styles */
            @media print {
                body * {
                    visibility: hidden;
                    margin: 0 !important;
                    padding: 0 !important;
                }
                
                .printable-area, 
                .printable-area * {
                    visibility: visible !important;
                }
                
                .printable-area {
                    position: absolute;
                    left: 0;
                    top: 0;
                    width: 100%;
                    padding: 20px;
                }
                
                .no-print {
                    display: none !important;
                }
                
                /* Print header */
                .print-school-header {
                    text-align: center;
                    margin-bottom: 20px;
                    padding-bottom: 15px;
                    border-bottom: 2px solid #333;
                }
                
                .print-school-name {
                    font-size: 22px;
                    font-weight: bold;
                    margin-bottom: 5px;
                    color: #000;
                }
                
                .print-school-address {
                    font-size: 12px;
                    margin-bottom: 5px;
                    color: #333;
                }
                
                .print-school-contact {
                    font-size: 11px;
                    color: #666;
                    margin-bottom: 10px;
                }
                
                .print-report-title {
                    text-align: center;
                    font-size: 18px;
                    font-weight: bold;
                    margin: 15px 0;
                    color: #000;
                }
                
                .print-report-info {
                    background: #f5f5f5;
                    padding: 10px;
                    border-radius: 4px;
                    margin-bottom: 15px;
                    font-size: 11px;
                }
                
                .print-info-row {
                    display: flex;
                    justify-content: space-between;
                    margin-bottom: 5px;
                }
                
                /* Print table */
                .print-table {
                    width: 100%;
                    border-collapse: collapse;
                    font-size: 11px;
                }
                
                .print-table th {
                    background: #333 !important;
                    color: white !important;
                    padding: 8px 5px !important;
                    border: 1px solid #000 !important;
                    text-align: center;
                    font-weight: bold;
                }
                
                .print-table td {
                    padding: 6px 5px !important;
                    border: 1px solid #000 !important;
                    text-align: left;
                }
                
                .print-table tr:nth-child(even) {
                    background: #f9f9f9 !important;
                }
                
                /* Page footer */
                .print-footer {
                    margin-top: 20px;
                    padding-top: 10px;
                    border-top: 1px solid #ccc;
                    font-size: 10px;
                    color: #666;
                    text-align: center;
                }
                
                .page-number {
                    float: right;
                    font-weight: bold;
                }
            }
            
            /* Hidden print area */
            .printable-area {
                display: none;
            }
        </style>
    </head>
    <body class="top-navbar-fixed">
        <div class="main-wrapper">
            <!-- ========== TOP NAVBAR ========== -->
            <?php include('includes/topbar.php');?>
            
            <!-- ========== WRAPPER FOR BOTH SIDEBARS & MAIN CONTENT ========== -->
            <div class="content-wrapper">
                <div class="content-container">
                    <!-- ========== LEFT SIDEBAR ========== -->
                    <?php include('includes/leftbar.php');?>
                    
                    <div class="main-page">
                        <div class="container-fluid">
                            <div class="row page-title-div">
                                <div class="col-md-6">
                                    <h2 class="title">Student Subject Report</h2>
                                </div>
                            </div>
                            
                            <div class="row breadcrumb-div">
                                <div class="col-md-6">
                                    <ul class="breadcrumb">
                                        <li><a href="dashboard.php"><i class="fa fa-home"></i> Home</a></li>
                                        <li>Reports</li>
                                        <li class="active">Student Subject Report</li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                        
                        <div class="container-fluid">
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="panel">
                                        <div class="panel-heading">
                                            <div class="panel-title">
                                                <h5>Generate Student Subject Report</h5>
                                            </div>
                                        </div>
                                        <div class="panel-body">
                                            <!-- School Header -->
                                            <div class="school-header no-print">
                                                <div class="school-name"><?= htmlspecialchars($school['school_name'] ?? 'SCHOOL NAME') ?></div>
                                                <div class="school-address"><?= htmlspecialchars($school['address'] ?? 'School Address') ?></div>
                                                <div class="school-contact">
                                                    <?php if (!empty($school['phone'])): ?>
                                                        <i class="fa fa-phone"></i> <?= htmlspecialchars($school['phone']) ?> 
                                                    <?php endif; ?>
                                                    <?php if (!empty($school['email'])): ?>
                                                        <span class="mx-2">|</span> <i class="fa fa-envelope"></i> <?= htmlspecialchars($school['email']) ?>
                                                    <?php endif; ?>
                                                </div>
                                                <?php if (!empty($school['school_code'])): ?>
                                                    <div class="school-code">
                                                        <i class="fa fa-id-card"></i> School Code: <?= htmlspecialchars($school['school_code']) ?>
                                                        <?php if (!empty($school['neb_code'])): ?>
                                                             | NEB: <?= htmlspecialchars($school['neb_code']) ?>
                                                        <?php endif; ?>
                                                    </div>
                                                <?php endif; ?>
                                            </div>
                                            
                                            <!-- Subject Reference Table -->
                                            <?php if (!empty($subjects)): ?>
                                            <div class="subject-reference no-print">
                                                <strong>Subject Reference:</strong>
                                                <div class="table-responsive mt-2">
                                                    <table class="table table-sm table-bordered mb-0">
                                                        <thead>
                                                            <tr>
                                                                <th>Code</th>
                                                                <th>Subject Name</th>
                                                            </tr>
                                                        </thead>
                                                        <tbody>
                                                            <?php foreach ($subjects as $subject): ?>
                                                            <tr>
                                                                <td><strong><?= htmlspecialchars($subject['subject_code']) ?></strong></td>
                                                                <td><?= htmlspecialchars($subject['subject_name']) ?></td>
                                                            </tr>
                                                            <?php endforeach; ?>
                                                        </tbody>
                                                    </table>
                                                </div>
                                            </div>
                                            <?php endif; ?>
                                            
                                            <!-- Filter Form -->
                                            <div class="no-print">
                                                <form method="POST" id="reportForm">
                                                    <div class="filter-section">
                                                        <div class="row">
                                                            <div class="col-md-3">
                                                                <div class="form-group">
                                                                    <label for="academic_year" class="font-weight-bold">Academic Year *</label>
                                                                    <select name="academic_year" id="academic_year" class="form-control form-control-sm" required>
                                                                        <option value="">-- Select Academic Year --</option>
                                                                        <?php foreach ($academicYears as $year): ?>
                                                                            <option value="<?= htmlspecialchars($year) ?>" <?= $academicYear == $year ? 'selected' : '' ?>>
                                                                                <?= htmlspecialchars($year) ?>
                                                                            </option>
                                                                        <?php endforeach; ?>
                                                                    </select>
                                                                </div>
                                                            </div>
                                                            
                                                            <div class="col-md-3">
                                                                <div class="form-group">
                                                                    <label for="class_ids" class="font-weight-bold">Class(es) *</label>
                                                                    <select name="class_ids[]" id="class_ids" class="form-control form-control-sm select2-multiple" multiple required>
                                                                        <?php
                                                                        $classQuery = $conn->query("SELECT * FROM classes WHERE status=1 ORDER BY class_numeric");
                                                                        while ($class = $classQuery->fetch_assoc()) {
                                                                            $selected = in_array($class['class_id'], $classIds) ? 'selected' : '';
                                                                            echo "<option value='{$class['class_id']}' $selected>{$class['class']}</option>";
                                                                        }
                                                                        ?>
                                                                    </select>
                                                                    <small class="form-text text-muted">Select one or multiple classes</small>
                                                                </div>
                                                            </div>
                                                            
                                                            <div class="col-md-3">
                                                                <div class="form-group">
                                                                    <label for="section_ids" class="font-weight-bold">Section(s)</label>
                                                                    <select name="section_ids[]" id="section_ids" class="form-control form-control-sm select2-multiple" multiple>
                                                                        <?php
                                                                        $sectionQuery = $conn->query("SELECT * FROM sections WHERE status=1 ORDER BY section_name");
                                                                        while ($section = $sectionQuery->fetch_assoc()) {
                                                                            $selected = in_array($section['section_id'], $sectionIds) ? 'selected' : '';
                                                                            echo "<option value='{$section['section_id']}' $selected>{$section['section_name']}</option>";
                                                                        }
                                                                        ?>
                                                                    </select>
                                                                    <small class="form-text text-muted">Optional: Filter by specific sections</small>
                                                                </div>
                                                            </div>
                                                            
                                                            <div class="col-md-3">
                                                                <div class="form-group">
                                                                    <label for="students_per_page" class="font-weight-bold">Students per Page (Print)</label>
                                                                    <input type="number" name="students_per_page" id="students_per_page" 
                                                                           class="form-control form-control-sm" 
                                                                           min="10" max="100" 
                                                                           value="<?= $studentsPerPage ?>"
                                                                           title="Number of students to show per printed page">
                                                                    <small class="form-text text-muted">Controls pagination for printing</small>
                                                                </div>
                                                            </div>
                                                        </div>
                                                        
                                                        <div class="row mt-2">
                                                            <div class="col-md-12 text-center">
                                                                <button type="submit" name="preview" class="btn btn-primary btn-sm">
                                                                    <i class="fa fa-search"></i> Generate Report
                                                                </button>
                                                                <button type="reset" class="btn btn-secondary btn-sm">
                                                                    <i class="fa fa-refresh"></i> Reset
                                                                </button>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </form>
                                            </div>
                                            
                                            <!-- Selected Filters Display -->
                                            <?php if (!empty($academicYear) || !empty($classIds) || !empty($sectionIds)): ?>
                                                <div class="selected-filters no-print">
                                                    <div class="row">
                                                        <div class="col-12">
                                                            <strong class="mr-2">Filters:</strong>
                                                            <?php if (!empty($academicYear)): ?>
                                                                <span class="badge badge-info mr-2">Year: <?= htmlspecialchars($academicYear) ?></span>
                                                            <?php endif; ?>
                                                            
                                                            <?php if (!empty($classIds)): ?>
                                                                <?php
                                                                $selectedClassNames = [];
                                                                $classQuery = $conn->query("SELECT class FROM classes WHERE class_id IN (" . implode(',', $classIds) . ")");
                                                                while ($class = $classQuery->fetch_assoc()) {
                                                                    $selectedClassNames[] = $class['class'];
                                                                }
                                                                ?>
                                                                <span class="badge badge-success mr-2">Classes: <?= implode(', ', $selectedClassNames) ?></span>
                                                            <?php endif; ?>
                                                            
                                                            <?php if (!empty($sectionIds)): ?>
                                                                <?php
                                                                $selectedSectionNames = [];
                                                                $sectionQuery = $conn->query("SELECT section_name FROM sections WHERE section_id IN (" . implode(',', $sectionIds) . ")");
                                                                while ($section = $sectionQuery->fetch_assoc()) {
                                                                    $selectedSectionNames[] = $section['section_name'];
                                                                }
                                                                ?>
                                                                <span class="badge badge-warning mr-2">Sections: <?= implode(', ', $selectedSectionNames) ?></span>
                                                            <?php endif; ?>
                                                            
                                                            <span class="badge badge-dark mr-2">Total Students: <?= count($reportRows) ?></span>
                                                            <span class="badge badge-secondary">Students/Page: <?= $studentsPerPage ?></span>
                                                        </div>
                                                    </div>
                                                </div>
                                            <?php endif; ?>
                                            
                                            <!-- Main Report Section -->
                                            <?php if (!empty($reportRows)): ?>
                                            <div>
                                                <!-- Export Buttons -->
                                                <div class="export-buttons text-right no-print">
                                                    <span class="page-info">
                                                        <i class="fa fa-users"></i> <?= count($reportRows) ?> Students | 
                                                        <i class="fa fa-file"></i> <?= ceil(count($reportRows) / $studentsPerPage) ?> Pages
                                                    </span>
                                                    <button type="submit" name="export_csv" form="reportForm" class="btn btn-success btn-sm">
                                                        <i class="fa fa-file-excel-o"></i> CSV
                                                    </button>
                                                    <button type="button" id="printReport" class="btn btn-info btn-sm">
                                                        <i class="fa fa-print"></i> Print Report
                                                    </button>
                                                </div>
                                                
                                                <!-- Report Table (On Screen) -->
                                                <div class="table-responsive">
                                                    <table class="table table-bordered table-striped table-hover compact-table">
                                                        <thead class="thead-dark">
                                                            <tr>
                                                                <th width="30">#</th>
                                                                <th width="80">Year</th>
                                                                <th width="80">Class</th>
                                                                <th width="60">Section</th>
                                                                <th width="70">Stud ID</th>
                                                                <th>Name</th>
                                                                <th width="100">Regd No</th>
                                                                <th class="subject-cell">Sub1</th>
                                                                <th class="subject-cell">Sub2</th>
                                                                <th class="subject-cell">Sub3</th>
                                                                <th class="subject-cell">Sub4</th>
                                                                <th class="subject-cell">Sub5</th>
                                                                <th class="subject-cell">Sub6</th>
                                                                <th class="subject-cell">Sub7</th>
                                                            </tr>
                                                        </thead>
                                                        <tbody>
                                                            <?php foreach ($reportRows as $index => $row): ?>
                                                                <tr>
                                                                    <td><?= $index + 1 ?></td>
                                                                    <td><?= htmlspecialchars($row['academic_year']) ?></td>
                                                                    <td><?= htmlspecialchars($row['class']) ?></td>
                                                                    <td><?= htmlspecialchars($row['section']) ?></td>
                                                                    <td><?= $row['student_id'] ?></td>
                                                                    <td><?= htmlspecialchars($row['name']) ?></td>
                                                                    <td><?= htmlspecialchars($row['regd_no']) ?></td>
                                                                    <?php foreach ($row['subjects'] as $sub): ?>
                                                                        <td class="subject-cell"><?= htmlspecialchars($sub) ?></td>
                                                                    <?php endforeach; ?>
                                                                </tr>
                                                            <?php endforeach; ?>
                                                        </tbody>
                                                    </table>
                                                </div>
                                            </div>
                                            <?php elseif ($_SERVER['REQUEST_METHOD'] === 'POST'): ?>
                                                <div class="alert alert-warning text-center">
                                                    <i class="fa fa-exclamation-triangle"></i> No students found with the selected criteria.
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Hidden Printable Area (for printing) -->
        <div class="printable-area" id="printableArea"></div>
        
        <script src="js/jquery/jquery-2.2.4.min.js"></script>
        <script src="js/bootstrap/bootstrap.min.js"></script>
        <script src="js/pace/pace.min.js"></script>
        <script src="js/lobipanel/lobipanel.min.js"></script>
        <script src="js/iscroll/iscroll.js"></script>
        <script src="js/prism/prism.js"></script>
        <script src="js/select2/select2.min.js"></script>
        <script src="js/main.js"></script>
        
        <script>
            $(document).ready(function() {
                // Initialize Select2 for multiple select boxes
                $('.select2-multiple').select2({
                    placeholder: "Select options",
                    allowClear: true
                });
                
                // Form validation
                $('#reportForm').on('submit', function(e) {
                    var academicYear = $('#academic_year').val();
                    var classIds = $('#class_ids').val();
                    
                    if (!academicYear) {
                        alert('Please select an academic year.');
                        e.preventDefault();
                        return false;
                    }
                    
                    if (!classIds || classIds.length === 0) {
                        alert('Please select at least one class.');
                        e.preventDefault();
                        return false;
                    }
                    
                    return true;
                });
                
                // Print functionality
                $('#printReport').click(function() {
                    // Get all data
                    var reportRows = <?= json_encode($reportRows) ?>;
                    var academicYear = '<?= htmlspecialchars($academicYear) ?>';
                    var studentsPerPage = parseInt($('#students_per_page').val()) || 50;
                    var school = <?= json_encode($school) ?>;
                    
                    // Get selected class names
                    <?php
                    $selectedClassNames = [];
                    if (!empty($classIds)) {
                        $classQuery = $conn->query("SELECT class FROM classes WHERE class_id IN (" . implode(',', $classIds) . ")");
                        while ($class = $classQuery->fetch_assoc()) {
                            $selectedClassNames[] = $class['class'];
                        }
                    }
                    ?>
                    var selectedClassNames = <?= json_encode($selectedClassNames) ?>;
                    
                    // Get selected section names
                    <?php
                    $selectedSectionNames = [];
                    if (!empty($sectionIds)) {
                        $sectionQuery = $conn->query("SELECT section_name FROM sections WHERE section_id IN (" . implode(',', $sectionIds) . ")");
                        while ($section = $sectionQuery->fetch_assoc()) {
                            $selectedSectionNames[] = $section['section_name'];
                        }
                    }
                    ?>
                    var selectedSectionNames = <?= json_encode($selectedSectionNames) ?>;
                    
                    // Calculate total pages
                    var totalPages = studentsPerPage > 0 ? Math.ceil(reportRows.length / studentsPerPage) : 1;
                    
                    // Build printable HTML
                    var printableHTML = '';
                    
                    for (var page = 0; page < totalPages; page++) {
                        var startIndex = page * studentsPerPage;
                        var endIndex = studentsPerPage > 0 ? Math.min(startIndex + studentsPerPage, reportRows.length) : reportRows.length;
                        var pageStudents = reportRows.slice(startIndex, endIndex);
                        
                        // Page header with school info
                        printableHTML += '<div class="print-school-header">';
                        printableHTML += '<div class="print-school-name">' + (school.school_name || 'SCHOOL NAME') + '</div>';
                        printableHTML += '<div class="print-school-address">' + (school.address || 'School Address') + '</div>';
                        printableHTML += '<div class="print-school-contact">';
                        if (school.phone) printableHTML += 'Phone: ' + school.phone;
                        if (school.email) printableHTML += ' | Email: ' + school.email;
                        if (school.school_code) printableHTML += ' | School Code: ' + school.school_code;
                        printableHTML += '</div>';
                        printableHTML += '</div>';
                        
                        // Report title
                        printableHTML += '<div class="print-report-title">STUDENT SUBJECT ASSIGNMENT REPORT</div>';
                        
                        // Report info
                        printableHTML += '<div class="print-report-info">';
                        printableHTML += '<div class="print-info-row">';
                        printableHTML += '<div><strong>Academic Year:</strong> ' + academicYear + '</div>';
                        printableHTML += '<div><strong>Page:</strong> ' + (page + 1) + ' of ' + totalPages + '</div>';
                        printableHTML += '</div>';
                        printableHTML += '<div class="print-info-row">';
                        printableHTML += '<div><strong>Classes:</strong> ' + (selectedClassNames.length > 0 ? selectedClassNames.join(', ') : 'All Classes') + '</div>';
                        printableHTML += '<div><strong>Sections:</strong> ' + (selectedSectionNames.length > 0 ? selectedSectionNames.join(', ') : 'All Sections') + '</div>';
                        printableHTML += '</div>';
                        printableHTML += '<div class="print-info-row">';
                        printableHTML += '<div><strong>Students on Page:</strong> ' + pageStudents.length + '</div>';
                        printableHTML += '<div><strong>Total Students:</strong> ' + reportRows.length + '</div>';
                        printableHTML += '</div>';
                        printableHTML += '<div class="print-info-row">';
                        printableHTML += '<div><strong>Generated On:</strong> ' + new Date().toLocaleDateString() + ' ' + new Date().toLocaleTimeString() + '</div>';
                        printableHTML += '<div><strong>Generated By:</strong> Student Report Management System</div>';
                        printableHTML += '</div>';
                        printableHTML += '</div>';
                        
                        // Table
                        printableHTML += '<table class="print-table">';
                        printableHTML += '<thead>';
                        printableHTML += '<tr>';
                        printableHTML += '<th width="30">#</th>';
                        printableHTML += '<th width="80">Year</th>';
                        printableHTML += '<th width="80">Class</th>';
                        printableHTML += '<th width="60">Section</th>';
                        printableHTML += '<th width="70">Stud ID</th>';
                        printableHTML += '<th>Name</th>';
                        printableHTML += '<th width="100">Regd No</th>';
                        printableHTML += '<th>Sub1</th>';
                        printableHTML += '<th>Sub2</th>';
                        printableHTML += '<th>Sub3</th>';
                        printableHTML += '<th>Sub4</th>';
                        printableHTML += '<th>Sub5</th>';
                        printableHTML += '<th>Sub6</th>';
                        printableHTML += '<th>Sub7</th>';
                        printableHTML += '</tr>';
                        printableHTML += '</thead>';
                        printableHTML += '<tbody>';
                        
                        for (var i = 0; i < pageStudents.length; i++) {
                            var student = pageStudents[i];
                            var studentNumber = startIndex + i + 1;
                            
                            printableHTML += '<tr>';
                            printableHTML += '<td style="text-align: center;">' + studentNumber + '</td>';
                            printableHTML += '<td style="text-align: center;">' + student.academic_year + '</td>';
                            printableHTML += '<td style="text-align: center;">' + student.class + '</td>';
                            printableHTML += '<td style="text-align: center;">' + student.section + '</td>';
                            printableHTML += '<td style="text-align: center;">' + student.student_id + '</td>';
                            printableHTML += '<td>' + student.name + '</td>';
                            printableHTML += '<td style="text-align: center;">' + student.regd_no + '</td>';
                            
                            // Subjects
                            for (var j = 0; j < student.subjects.length; j++) {
                                printableHTML += '<td style="text-align: center;">' + (student.subjects[j] || '') + '</td>';
                            }
                            
                            printableHTML += '</tr>';
                        }
                        
                        printableHTML += '</tbody>';
                        printableHTML += '</table>';
                        
                        // Page footer
                        printableHTML += '<div class="print-footer">';
                        printableHTML += '<div style="float: left;">Official Document - Do Not Duplicate</div>';
                        printableHTML += '<div class="page-number">Page ' + (page + 1) + ' of ' + totalPages + '</div>';
                        printableHTML += '<div style="clear: both;"></div>';
                        printableHTML += '</div>';
                        
                        // Add page break if not last page
                        if (page < totalPages - 1) {
                            printableHTML += '<div style="page-break-after: always;"></div>';
                        }
                    }
                    
                    // Set printable HTML
                    $('#printableArea').html(printableHTML);
                    
                    // Show printable area and trigger print
                    $('#printableArea').show();
                    
                    // Give a small delay for rendering
                    setTimeout(function() {
                        window.print();
                        // Hide printable area after printing
                        setTimeout(function() {
                            $('#printableArea').hide().html('');
                        }, 100);
                    }, 100);
                });
                
                // Handle print dialog close
                window.addEventListener('afterprint', function() {
                    $('#printableArea').hide().html('');
                });
            });
        </script>
    </body>
</html>

<?php
$conn->close();
?>