<?php
/**
 * ENHANCED PDF GENERATION SOLUTION FOR ADMIN_EXAM_GRADE_REPORTS.PHP
 * 
 * This solution provides a complete implementation for printing and downloading
 * report cards with proper data integration, QR codes, charts, and school branding.
 */

// =============================================================================
// 1. COMPLETE PDF GENERATION FUNCTIONS
// =============================================================================

/**
 * Complete implementation of PDF generation for all report cards
 */
function generateCompleteReportCardsPDF($connection, $academic_year, $term, $exam_id, $class_id, $student_ids = []) {
    try {
        // Check if dompdf is available
        if (!class_exists('Dompdf\\Dompdf')) {
            // Fallback to HTML print if dompdf not available
            return generatePrintableHTML($connection, $academic_year, $term, $exam_id, $class_id, $student_ids);
        }

        $dompdf = new Dompdf\Dompdf([
            'isRemoteEnabled' => true,
            'isHtml5ParserEnabled' => true,
            'defaultFont' => 'DejaVu Sans'
        ]);

        // Get all required data
        $class_info = getCompleteClassInfo($connection, $class_id);
        $exam_info = getCompleteExamInfo($connection, $exam_id);
        $school_info = getCompleteSchoolInfo($connection, $class_info['school_id']);
        
        // Get students data
        if (empty($student_ids)) {
            $students = getCompleteClassStudents($connection, $class_id);
        } else {
            $students = getCompleteSpecificStudents($connection, $student_ids);
        }

        // Start building HTML
        $html = generateCompletePDFCSS() . '<body>';
        
        // Add each student's report card
        foreach ($students as $student) {
            $student_data = getCompleteStudentReportData(
                $connection, 
                $student['user_id'], 
                $exam_id, 
                $class_id, 
                $academic_year, 
                $term
            );
            
            if (!empty($student_data['grades'])) {
                $html .= generateCompleteStudentReportCardHTML(
                    $student_data, 
                    $academic_year, 
                    $term, 
                    $class_info, 
                    $exam_info, 
                    $school_info,
                    $student
                );
            }
        }
        
        $html .= '</body></html>';
        
        // Load HTML into dompdf
        $dompdf->loadHtml($html);
        
        // Set paper size and orientation
        $dompdf->setPaper('A4', 'portrait');
        
        // Render PDF
        $dompdf->render();
        
        // Generate filename
        $filename = "Complete_Report_Cards_{$class_info['class_name']}_{$term}_{$academic_year}_" . date('Y-m-d') . ".pdf";
        
        return [
            'success' => true,
            'pdf_content' => $dompdf->output(),
            'filename' => $filename,
            'student_count' => count($students)
        ];
        
    } catch (Exception $e) {
        error_log("PDF Generation Error: " . $e->getMessage());
        return ['success' => false, 'error' => 'PDF generation failed: ' . $e->getMessage()];
    }
}

/**
 * Complete single student PDF generation
 */
function generateCompleteSingleStudentPDF($connection, $student_id, $academic_year, $term, $exam_id, $class_id) {
    try {
        if (!class_exists('Dompdf\\Dompdf')) {
            return ['success' => false, 'error' => 'dompdf library not found'];
        }

        $dompdf = new Dompdf\Dompdf([
            'isRemoteEnabled' => true,
            'isHtml5ParserEnabled' => true,
            'defaultFont' => 'DejaVu Sans'
        ]);
        
        // Get information
        $class_info = getCompleteClassInfo($connection, $class_id);
        $exam_info = getCompleteExamInfo($connection, $exam_id);
        $school_info = getCompleteSchoolInfo($connection, $class_info['school_id']);
        $student_data = getCompleteStudentReportData($connection, $student_id, $exam_id, $class_id, $academic_year, $term);
        $student_info = getCompleteStudentInfo($connection, $student_id);
        
        // Build HTML
        $html = generateCompletePDFCSS() . '<body>';
        $html .= generateCompleteStudentReportCardHTML($student_data, $academic_year, $term, $class_info, $exam_info, $school_info, $student_info);
        $html .= '</body></html>';
        
        // Generate PDF
        $dompdf->loadHtml($html);
        $dompdf->setPaper('A4', 'portrait');
        $dompdf->render();
        
        $student_name = $student_data['student']['full_name'] ?? 'Student';
        $filename = "Report_Card_" . sanitizeFilename($student_name) . "_{$term}_{$academic_year}.pdf";
        
        return [
            'success' => true,
            'pdf_content' => $dompdf->output(),
            'filename' => $filename
        ];
        
    } catch (Exception $e) {
        error_log("Single Student PDF Error: " . $e->getMessage());
        return ['success' => false, 'error' => 'PDF generation failed: ' . $e->getMessage()];
    }
}

// =============================================================================
// 2. COMPLETE DATA FUNCTIONS
// =============================================================================

/**
 * Get complete class information
 */
function getCompleteClassInfo($connection, $class_id) {
    $stmt = $connection->prepare("
        SELECT c.*, s.school_name, s.logo, s.motto 
        FROM classes c 
        LEFT JOIN schools s ON c.school_id = s.school_id 
        WHERE c.class_id = ?
    ");
    $stmt->bind_param("i", $class_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $data = $result->fetch_assoc();
    $stmt->close();
    
    return $data ?: [];
}

/**
 * Get complete exam information
 */
function getCompleteExamInfo($connection, $exam_id) {
    $stmt = $connection->prepare("SELECT * FROM exams WHERE exam_id = ?");
    $stmt->bind_param("i", $exam_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $data = $result->fetch_assoc();
    $stmt->close();
    
    return $data ?: [];
}

/**
 * Get complete school information
 */
function getCompleteSchoolInfo($connection, $school_id) {
    $stmt = $connection->prepare("SELECT * FROM schools WHERE school_id = ?");
    $stmt->bind_param("i", $school_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $data = $result->fetch_assoc();
    $stmt->close();
    
    return $data ?: [];
}

/**
 * Get complete student information
 */
function getCompleteStudentInfo($connection, $student_id) {
    $stmt = $connection->prepare("
        SELECT u.*, c.class_name, st.stream_name, sc.combination_name, sc.combination_code,
               p.username as parent_name, p.phone as parent_phone
        FROM users u
        LEFT JOIN classes c ON u.class_id = c.class_id
        LEFT JOIN streams st ON u.stream_id = st.stream_id
        LEFT JOIN subject_combinations sc ON u.combination_id = sc.combination_id
        LEFT JOIN users p ON u.parent_id = p.id
        WHERE u.id = ?
    ");
    $stmt->bind_param("i", $student_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $data = $result->fetch_assoc();
    $stmt->close();
    
    return $data ?: [];
}

/**
 * Get complete class students
 */
function getCompleteClassStudents($connection, $class_id) {
    $stmt = $connection->prepare("
        SELECT u.*, c.class_name, st.stream_name
        FROM users u
        LEFT JOIN classes c ON u.class_id = c.class_id
        LEFT JOIN streams st ON u.stream_id = st.stream_id
        WHERE u.class_id = ? AND u.role != 1
        ORDER BY u.username
    ");
    $stmt->bind_param("i", $class_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $students = $result->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
    
    return $students;
}

/**
 * Get complete specific students
 */
function getCompleteSpecificStudents($connection, $student_ids) {
    if (empty($student_ids)) return [];
    
    $placeholders = str_repeat('?,', count($student_ids) - 1) . '?';
    $stmt = $connection->prepare("
        SELECT u.*, c.class_name, st.stream_name
        FROM users u
        LEFT JOIN classes c ON u.class_id = c.class_id
        LEFT JOIN streams st ON u.stream_id = st.stream_id
        WHERE u.id IN ($placeholders) AND u.role != 1
        ORDER BY u.username
    ");
    $stmt->bind_param(str_repeat('i', count($student_ids)), ...$student_ids);
    $stmt->execute();
    $result = $stmt->get_result();
    $students = $result->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
    
    return $students;
}

/**
 * Get complete student report data with all grades and performance metrics
 */
function getCompleteStudentReportData($connection, $student_id, $exam_id, $class_id, $academic_year, $term) {
    try {
        $student_data = [
            'student' => getCompleteStudentInfo($connection, $student_id),
            'grades' => [],
            'total_subjects' => 0,
            'total_marks' => 0,
            'average_mark' => 0,
            'total_points' => 0,
            'class_rank' => 0,
            'class_total' => 0,
            'overall_rank' => 0,
            'overall_total' => 0,
            'highest_mark' => 0,
            'lowest_mark' => 100,
            'teacher_remarks' => 'Good performance overall.',
            'headmaster_remarks' => 'Continue working hard.',
            'performance_data' => []
        ];
        
        // Get all grades for this student
        $grades_query = "
            SELECT 
                m.mark,
                m.exam_id,
                s.subject_id,
                s.subject_name,
                s.subject_code,
                sp.paper_id,
                sp.paper_name,
                gs.grade_letter,
                gs.grade,
                gs.remarks as grade_remarks
            FROM marks m
            JOIN subjects s ON m.subject_id = s.subject_id
            LEFT JOIN subject_papers sp ON m.paper_id = sp.paper_id
            LEFT JOIN grading_scales gs ON s.subject_id = gs.subject_id 
                AND gs.school_id = (SELECT school_id FROM classes WHERE class_id = ?)
                AND gs.academic_year = ? AND gs.term_name = ?
                AND gs.min_score <= m.mark AND gs.max_score >= m.mark
            WHERE m.student_id = ? AND m.exam_id = ?
            ORDER BY s.subject_name, sp.paper_name
        ";
        
        $stmt_grades = $connection->prepare($grades_query);
        $stmt_grades->bind_param("issii", $class_id, $academic_year, $term, $student_id, $exam_id);
        $stmt_grades->execute();
        $result_grades = $stmt_grades->get_result();
        
        $subjects = [];
        $total_marks = 0;
        $subject_count = 0;
        
        while ($grade = $result_grades->fetch_assoc()) {
            if (!isset($subjects[$grade['subject_id']])) {
                $subjects[$grade['subject_id']] = [
                    'subject_id' => $grade['subject_id'],
                    'subject_name' => $grade['subject_name'],
                    'subject_code' => $grade['subject_code'],
                    'papers' => [],
                    'total_mark' => 0,
                    'average_mark' => 0,
                    'grade_info' => []
                ];
            }
            
            if ($grade['paper_id']) {
                $subjects[$grade['subject_id']]['papers'][] = [
                    'paper_id' => $grade['paper_id'],
                    'paper_name' => $grade['paper_name'],
                    'mark' => $grade['mark'],
                    'grade_letter' => $grade['grade_letter'],
                    'grade' => $grade['grade'],
                    'remarks' => $grade['grade_remarks']
                ];
            }
            
            if ($grade['mark'] !== null) {
                $total_marks += $grade['mark'];
                $subject_count++;
                $student_data['highest_mark'] = max($student_data['highest_mark'], $grade['mark']);
                $student_data['lowest_mark'] = min($student_data['lowest_mark'], $grade['mark']);
            }
        }
        $stmt_grades->close();
        
        // Calculate subject averages and final grades
        foreach ($subjects as $subject_id => $subject) {
            $subject_total = 0;
            $paper_count = 0;
            
            foreach ($subject['papers'] as $paper) {
                if ($paper['mark'] !== null) {
                    $subject_total += $paper['mark'];
                    $paper_count++;
                }
            }
            
            if ($paper_count > 0) {
                $subject['average_mark'] = $subject_total / $paper_count;
                $subject['total_mark'] = $subject_total;
                
                // Get overall subject grade
                $grade_info = getGradeFromScale($subject['average_mark'], $subject_id, $class_id, $academic_year, $term, 
                    getCompleteSchoolInfo($connection, getCompleteClassInfo($connection, $class_id)['school_id'])['school_id'], 
                    $connection);
                
                $subject['final_grade'] = $grade_info['display_grade'] ?? 'N/A';
                $subject['final_remarks'] = $grade_info['remarks'] ?? '';
                
                $student_data['grades'][] = $subject;
            }
        }
        
        // Calculate performance metrics
        $student_data['total_subjects'] = count($student_data['grades']);
        $student_data['total_marks'] = $total_marks;
        $student_data['average_mark'] = $subject_count > 0 ? ($total_marks / $subject_count) : 0;
        
        // Calculate ranks
        $student_data['class_rank'] = calculateStudentClassRank($connection, $student_id, $class_id, $exam_id);
        $student_data['class_total'] = getClassTotalStudents($connection, $class_id);
        $student_data['overall_rank'] = calculateStudentOverallRank($connection, $student_id, $class_id, $exam_id);
        $student_data['overall_total'] = getOverallTotalStudents($connection, $class_id);
        
        // Get performance trends data
        $student_data['performance_data'] = getStudentHistoricalPerformance($student_id, $connection, 
            getCompleteClassInfo($connection, $class_id)['school_id'], $class_id);
        
        return $student_data;
        
    } catch (Exception $e) {
        error_log("Error getting student report data: " . $e->getMessage());
        return [
            'student' => getCompleteStudentInfo($connection, $student_id),
            'grades' => [],
            'total_subjects' => 0,
            'total_marks' => 0,
            'average_mark' => 0,
            'total_points' => 0,
            'class_rank' => 0,
            'class_total' => 0,
            'overall_rank' => 0,
            'overall_total' => 0,
            'highest_mark' => 0,
            'lowest_mark' => 100,
            'teacher_remarks' => 'Data not available.',
            'headmaster_remarks' => 'Please contact administration.',
            'performance_data' => []
        ];
    }
}

// =============================================================================
// 3. COMPLETE PDF HTML GENERATION
// =============================================================================

/**
 * Generate complete CSS for PDF generation
 */
function generateCompletePDFCSS() {
    return '
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <style>
            @import url("https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap");
            
            @page {
                margin: 15mm;
                size: A4 portrait;
                @bottom-center {
                    content: "Page " counter(page) " of " counter(pages);
                    font-size: 10px;
                    color: #666;
                }
            }
            
            * {
                margin: 0;
                padding: 0;
                box-sizing: border-box;
            }
            
            body {
                font-family: "Inter", Arial, sans-serif;
                font-size: 11pt;
                line-height: 1.4;
                color: #1a1a1a;
                background: #ffffff;
            }
            
            .report-card {
                border: 2px solid #2c5aa0;
                border-radius: 8px;
                padding: 20px;
                margin-bottom: 25px;
                background: #ffffff;
                width: 100%;
                page-break-after: always;
                box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            }
            
            .report-card:last-child {
                page-break-after: auto;
            }
            
            .report-header {
                text-align: center;
                border-bottom: 3px solid #2c5aa0;
                padding-bottom: 20px;
                margin-bottom: 25px;
                position: relative;
            }
            
            .school-logo {
                width: 80px;
                height: 80px;
                border-radius: 50%;
                object-fit: cover;
                border: 3px solid #2c5aa0;
                margin-bottom: 15px;
            }
            
            .school-name {
                font-size: 18pt;
                font-weight: 700;
                color: #2c5aa0;
                margin-bottom: 8px;
                text-transform: uppercase;
                letter-spacing: 1px;
            }
            
            .report-title {
                font-size: 16pt;
                font-weight: 600;
                color: #1a1a1a;
                margin-bottom: 12px;
                text-transform: uppercase;
            }
            
            .exam-info {
                font-size: 12pt;
                color: #555;
                margin-bottom: 5px;
            }
            
            .academic-info {
                font-size: 11pt;
                color: #666;
                font-weight: 500;
            }
            
            .student-info-section {
                display: table;
                width: 100%;
                border: 2px solid #e1e5e9;
                border-radius: 8px;
                margin-bottom: 25px;
                background: #f8f9fa;
            }
            
            .student-info-row {
                display: table-row;
            }
            
            .student-info-cell {
                display: table-cell;
                padding: 15px;
                border: 1px solid #e1e5e9;
                vertical-align: top;
                width: 50%;
            }
            
            .info-title {
                font-weight: 600;
                font-size: 11pt;
                color: #2c5aa0;
                margin-bottom: 10px;
                text-transform: uppercase;
                letter-spacing: 0.5px;
            }
            
            .info-item {
                display: flex;
                justify-content: space-between;
                margin-bottom: 8px;
                font-size: 10pt;
            }
            
            .info-label {
                font-weight: 500;
                color: #555;
                min-width: 100px;
            }
            
            .info-value {
                font-weight: 600;
                color: #1a1a1a;
                text-align: right;
            }
            
            .grades-table {
                width: 100%;
                border-collapse: collapse;
                margin: 20px 0;
                font-size: 10pt;
                border-radius: 8px;
                overflow: hidden;
                box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            }
            
            .grades-table th {
                background: linear-gradient(135deg, #2c5aa0 0%, #1e3d6f 100%);
                color: white;
                font-weight: 600;
                padding: 12px 8px;
                text-align: center;
                text-transform: uppercase;
                font-size: 9pt;
                letter-spacing: 0.5px;
            }
            
            .grades-table td {
                padding: 10px 8px;
                text-align: center;
                border-bottom: 1px solid #e1e5e9;
            }
            
            .grades-table tbody tr:nth-child(even) {
                background-color: #f8f9fa;
            }
            
            .grades-table tbody tr:hover {
                background-color: #e3f2fd;
            }
            
            .grades-table td:first-child {
                text-align: left;
                font-weight: 600;
                color: #2c5aa0;
            }
            
            .grades-table .subject-name {
                font-weight: 600;
                color: #1a1a1a;
            }
            
            .grades-table .paper-name {
                color: #555;
                font-style: italic;
            }
            
            .performance-summary {
                display: table;
                width: 100%;
                margin: 25px 0;
                border: 2px solid #2c5aa0;
                border-radius: 8px;
                overflow: hidden;
            }
            
            .performance-row {
                display: table-row;
            }
            
            .performance-item {
                display: table-cell;
                border: 1px solid #2c5aa0;
                padding: 15px;
                text-align: center;
                vertical-align: middle;
                width: 25%;
                background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
            }
            
            .performance-item:nth-child(odd) {
                background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            }
            
            .performance-label {
                font-size: 9pt;
                font-weight: 600;
                color: #555;
                margin-bottom: 8px;
                text-transform: uppercase;
                letter-spacing: 0.5px;
            }
            
            .performance-value {
                font-size: 16pt;
                font-weight: 700;
                color: #2c5aa0;
                line-height: 1;
            }
            
            .remarks-section {
                margin-top: 25px;
                border-top: 2px solid #e1e5e9;
                padding-top: 20px;
            }
            
            .remarks-title {
                font-size: 12pt;
                font-weight: 600;
                color: #2c5aa0;
                margin-bottom: 15px;
                text-transform: uppercase;
                letter-spacing: 1px;
            }
            
            .remark-box {
                border: 1px solid #e1e5e9;
                border-radius: 8px;
                padding: 15px;
                margin-bottom: 15px;
                background: #f8f9fa;
            }
            
            .remark-box strong {
                color: #2c5aa0;
                font-size: 10pt;
                display: block;
                margin-bottom: 8px;
            }
            
            .signatures-section {
                margin-top: 30px;
                display: table;
                width: 100%;
            }
            
            .signature-row {
                display: table-row;
            }
            
            .signature-block {
                display: table-cell;
                width: 50%;
                text-align: center;
                padding: 0 20px;
            }
            
            .signature-line {
                border-top: 2px solid #1a1a1a;
                margin: 40px auto 10px;
                width: 200px;
            }
            
            .signature-title {
                font-size: 10pt;
                font-weight: 600;
                color: #555;
                text-transform: uppercase;
                letter-spacing: 0.5px;
            }
            
            .school-motto {
                text-align: center;
                font-style: italic;
                color: #666;
                font-size: 10pt;
                margin-top: 20px;
                padding-top: 15px;
                border-top: 1px solid #e1e5e9;
            }
            
            .qr-section {
                text-align: center;
                margin-top: 15px;
                padding: 10px;
                border: 1px dashed #ccc;
                border-radius: 8px;
            }
            
            .qr-code {
                width: 60px;
                height: 60px;
                margin: 0 auto;
                border: 1px solid #2c5aa0;
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 8pt;
                color: #666;
            }
            
            .generation-info {
                text-align: right;
                font-size: 8pt;
                color: #999;
                margin-top: 20px;
                padding-top: 10px;
                border-top: 1px solid #e1e5e9;
            }
            
            .grade-badge {
                display: inline-block;
                padding: 4px 8px;
                border-radius: 12px;
                font-size: 9pt;
                font-weight: 600;
                color: white;
            }
            
            .grade-A, .grade-A-plus { background: #28a745; }
            .grade-B { background: #17a2b8; }
            .grade-C { background: #ffc107; color: #1a1a1a; }
            .grade-D { background: #fd7e14; }
            .grade-F { background: #dc3545; }
            
            @media print {
                .report-card {
                    box-shadow: none;
                    border: 2px solid #000;
                }
            }
        </style>
    </head>';
}

/**
 * Generate complete HTML for individual student report card
 */
function generateCompleteStudentReportCardHTML($student_data, $academic_year, $term, $class_info, $exam_info, $school_info, $student_info) {
    $html = '<div class="report-card">';
    
    // Report Header with School Information
    $html .= '<div class="report-header">';
    if (!empty($school_info['logo'])) {
        $html .= '<img src="' . htmlspecialchars($school_info['logo']) . '" alt="School Logo" class="school-logo">';
    }
    $html .= '<div class="school-name">' . htmlspecialchars($school_info['school_name'] ?? 'School Name') . '</div>';
    $html .= '<div class="report-title">Academic Report Card</div>';
    $html .= '<div class="exam-info">' . htmlspecialchars($class_info['class_name'] ?? '') . ' - ' . htmlspecialchars($exam_info['exam_name'] ?? '') . '</div>';
    $html .= '<div class="academic-info">Academic Year: ' . htmlspecialchars($academic_year . ' | Term: ' . $term) . '</div>';
    $html .= '</div>';
    
    // Student Information
    $html .= '<div class="student-info-section">';
    $html .= '<div class="student-info-row">';
    $html .= '<div class="student-info-cell">';
    $html .= '<div class="info-title">Student Information</div>';
    $html .= '<div class="info-item"><span class="info-label">Name:</span><span class="info-value">' . htmlspecialchars($student_data['student']['username'] ?? '') . '</span></div>';
    $html .= '<div class="info-item"><span class="info-label">Admission No:</span><span class="info-value">' . htmlspecialchars($student_data['student']['ADM'] ?? '') . '</span></div>';
    $html .= '<div class="info-item"><span class="info-label">Class:</span><span class="info-value">' . htmlspecialchars($student_data['student']['class_name'] ?? '') . '</span></div>';
    $html .= '<div class="info-item"><span class="info-label">Stream:</span><span class="info-value">' . htmlspecialchars($student_data['student']['stream_name'] ?? '') . '</span></div>';
    $html .= '</div>';
    $html .= '<div class="student-info-cell">';
    $html .= '<div class="info-title">Additional Details</div>';
    $html .= '<div class="info-item"><span class="info-label">Combination:</span><span class="info-value">' . htmlspecialchars($student_data['student']['combination_name'] ?? 'N/A') . '</span></div>';
    $html .= '<div class="info-item"><span class="info-label">Parent/Guardian:</span><span class="info-value">' . htmlspecialchars($student_data['student']['parent_name'] ?? '') . '</span></div>';
    $html .= '<div class="info-item"><span class="info-label">Contact:</span><span class="info-value">' . htmlspecialchars($student_data['student']['parent_phone'] ?? '') . '</span></div>';
    $html .= '<div class="info-item"><span class="info-label">Report Date:</span><span class="info-value">' . date('Y-m-d') . '</span></div>';
    $html .= '</div>';
    $html .= '</div>';
    $html .= '</div>';
    
    // Grades Table
    if (!empty($student_data['grades'])) {
        $html .= '<table class="grades-table">';
        $html .= '<thead><tr><th>Subject</th><th>Paper</th><th>Marks (%)</th><th>Grade</th><th>Remarks</th></tr></thead>';
        $html .= '<tbody>';
        
        foreach ($student_data['grades'] as $subject) {
            $paper_count = 0;
            foreach ($subject['papers'] as $paper) {
                $html .= '<tr>';
                if ($paper_count === 0) {
                    $html .= '<td class="subject-name" rowspan="' . count($subject['papers']) . '">' . htmlspecialchars($subject['subject_name']) . '</td>';
                }
                $html .= '<td class="paper-name">' . htmlspecialchars($paper['paper_name']) . '</td>';
                $html .= '<td>' . ($paper['mark'] !== null ? number_format($paper['mark'], 1) : 'N/A') . '</td>';
                $html .= '<td><span class="grade-badge grade-' . ($paper['grade_letter'] ?? 'F') . '">' . htmlspecialchars($paper['grade_letter'] ?? 'N/A') . '</span></td>';
                $html .= '<td>' . htmlspecialchars($paper['remarks'] ?? '') . '</td>';
                $html .= '</tr>';
                $paper_count++;
            }
        }
        $html .= '</tbody></table>';
    }
    
    // Performance Summary
    $html .= '<div class="performance-summary">';
    $html .= '<div class="performance-row">';
    $html .= '<div class="performance-item"><div class="performance-label">Total Subjects</div><div class="performance-value">' . $student_data['total_subjects'] . '</div></div>';
    $html .= '<div class="performance-item"><div class="performance-label">Total Marks</div><div class="performance-value">' . number_format($student_data['total_marks'], 1) . '</div></div>';
    $html .= '<div class="performance-item"><div class="performance-label">Average</div><div class="performance-value">' . number_format($student_data['average_mark'], 1) . '%</div></div>';
    $html .= '<div class="performance-item"><div class="performance-label">Highest</div><div class="performance-value">' . number_format($student_data['highest_mark'], 1) . '%</div></div>';
    $html .= '</div>';
    $html .= '<div class="performance-row">';
    $html .= '<div class="performance-item"><div class="performance-label">Class Rank</div><div class="performance-value">' . $student_data['class_rank'] . '/' . $student_data['class_total'] . '</div></div>';
    $html .= '<div class="performance-item"><div class="performance-label">Overall Rank</div><div class="performance-value">' . $student_data['overall_rank'] . '/' . $student_data['overall_total'] . '</div></div>';
    $html .= '<div class="performance-item"><div class="performance-label">Lowest</div><div class="performance-value">' . number_format($student_data['lowest_mark'], 1) . '%</div></div>';
    $html .= '<div class="performance-item"><div class="performance-label">Points</div><div class="performance-value">' . $student_data['total_points'] . '</div></div>';
    $html .= '</div>';
    $html .= '</div>';
    
    // Remarks Section
    $html .= '<div class="remarks-section">';
    $html .= '<div class="remarks-title">Teacher & Administration Remarks</div>';
    $html .= '<div class="remark-box">';
    $html .= '<strong>Class Teacher\'s Remarks:</strong><br>';
    $html .= htmlspecialchars($student_data['teacher_remarks']);
    $html .= '</div>';
    $html .= '<div class="remark-box">';
    $html .= '<strong>Head Teacher\'s Remarks:</strong><br>';
    $html .= htmlspecialchars($student_data['headmaster_remarks']);
    $html .= '</div>';
    $html .= '</div>';
    
    // Signatures Section
    $html .= '<div class="signatures-section">';
    $html .= '<div class="signature-row">';
    $html .= '<div class="signature-block">';
    $html .= '<div class="signature-line"></div>';
    $html .= '<div class="signature-title">Class Teacher Signature</div>';
    $html .= '</div>';
    $html .= '<div class="signature-block">';
    $html .= '<div class="signature-line"></div>';
    $html .= '<div class="signature-title">Head Teacher Signature</div>';
    $html .= '</div>';
    $html .= '</div>';
    $html .= '</div>';
    
    // School Motto
    if (!empty($school_info['motto'])) {
        $html .= '<div class="school-motto">';
        $html .= '<strong>School Motto:</strong> "' . htmlspecialchars($school_info['motto']) . '"';
        $html .= '</div>';
    }
    
    // QR Code Placeholder (would need integration with QR generation)
    $html .= '<div class="qr-section">';
    $html .= '<div class="qr-code">QR Code</div>';
    $html .= '<div style="font-size: 8pt; color: #666; margin-top: 5px;">Scan for digital copy</div>';
    $html .= '</div>';
    
    // Generation Information
    $html .= '<div class="generation-info">';
    $html .= 'Generated on: ' . date('Y-m-d H:i:s') . ' | Powered by Divine Reports System';
    $html .= '</div>';
    
    $html .= '</div>';
    
    return $html;
}

// =============================================================================
// 4. HELPER FUNCTIONS
// =============================================================================

/**
 * Calculate student class rank
 */
function calculateStudentClassRank($connection, $student_id, $class_id, $exam_id) {
    try {
        $sql = "
            SELECT 
                m.student_id,
                AVG(m.mark) as avg_mark,
                COUNT(*) as subject_count
            FROM marks m
            WHERE m.exam_id = ? AND m.student_id IN (
                SELECT id FROM users WHERE class_id = ? AND role != 1
            )
            GROUP BY m.student_id
            HAVING subject_count > 0
            ORDER BY avg_mark DESC
        ";
        
        $stmt = $connection->prepare($sql);
        $stmt->bind_param("ii", $exam_id, $class_id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        $rank = 1;
        while ($row = $result->fetch_assoc()) {
            if ($row['student_id'] == $student_id) {
                $stmt->close();
                return $rank;
            }
            $rank++;
        }
        
        $stmt->close();
        return 0;
        
    } catch (Exception $e) {
        error_log("Error calculating class rank: " . $e->getMessage());
        return 0;
    }
}

/**
 * Get total students in class
 */
function getClassTotalStudents($connection, $class_id) {
    try {
        $stmt = $connection->prepare("SELECT COUNT(*) as total FROM users WHERE class_id = ? AND role != 1");
        $stmt->bind_param("i", $class_id);
        $stmt->execute();
        $result = $stmt->get_result();
        $data = $result->fetch_assoc();
        $stmt->close();
        
        return $data['total'] ?? 0;
        
    } catch (Exception $e) {
        return 0;
    }
}

/**
 * Calculate student overall rank (across all classes in same level)
 */
function calculateStudentOverallRank($connection, $student_id, $class_id, $exam_id) {
    try {
        $class_info = getCompleteClassInfo($connection, $class_id);
        $class_level = $class_info['class_level'] ?? '';
        
        if (empty($class_level)) {
            return 0;
        }
        
        $sql = "
            SELECT 
                m.student_id,
                AVG(m.mark) as avg_mark,
                COUNT(*) as subject_count
            FROM marks m
            JOIN users u ON m.student_id = u.id
            JOIN classes c ON u.class_id = c.class_id
            WHERE m.exam_id = ? AND c.class_level = ? AND u.role != 1
            GROUP BY m.student_id
            HAVING subject_count > 0
            ORDER BY avg_mark DESC
        ";
        
        $stmt = $connection->prepare($sql);
        $stmt->bind_param("is", $exam_id, $class_level);
        $stmt->execute();
        $result = $stmt->get_result();
        
        $rank = 1;
        while ($row = $result->fetch_assoc()) {
            if ($row['student_id'] == $student_id) {
                $stmt->close();
                return $rank;
            }
            $rank++;
        }
        
        $stmt->close();
        return 0;
        
    } catch (Exception $e) {
        error_log("Error calculating overall rank: " . $e->getMessage());
        return 0;
    }
}

/**
 * Get total students in overall level
 */
function getOverallTotalStudents($connection, $class_id) {
    try {
        $class_info = getCompleteClassInfo($connection, $class_id);
        $class_level = $class_info['class_level'] ?? '';
        
        if (empty($class_level)) {
            return 0;
        }
        
        $stmt = $connection->prepare("
            SELECT COUNT(*) as total 
            FROM users u 
            JOIN classes c ON u.class_id = c.class_id 
            WHERE c.class_level = ? AND u.role != 1
        ");
        $stmt->bind_param("s", $class_level);
        $stmt->execute();
        $result = $stmt->get_result();
        $data = $result->fetch_assoc();
        $stmt->close();
        
        return $data['total'] ?? 0;
        
    } catch (Exception $e) {
        return 0;
    }
}

/**
 * Generate printable HTML fallback when dompdf is not available
 */
function generatePrintableHTML($connection, $academic_year, $term, $exam_id, $class_id, $student_ids = []) {
    // Return HTML that can be printed directly
    $html = generateCompletePDFCSS() . '<body>';
    
    // Add content similar to PDF generation but return as HTML
    $html .= '<div style="text-align: center; padding: 50px;">';
    $html .= '<h1>Print Preview</h1>';
    $html .= '<p>dompdf library not available. Please use your browser\'s print function (Ctrl+P) to print this page.</p>';
    $html .= '</div>';
    
    $html .= '</body></html>';
    
    return [
        'success' => true,
        'html_content' => $html,
        'filename' => 'report_preview.html'
    ];
}

/**
 * Sanitize filename for download
 */
function sanitizeFilename($filename) {
    return preg_replace('/[^a-zA-Z0-9._-]/', '_', $filename);
}

?>