<?php
session_start();
include_once 'config.php';

// Fix variable name mismatch - make $connection available if config uses $conn
if (isset($conn) && !isset($connection)) {
    $connection = $conn;
}

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Include dompdf if available
$dompdf_loaded = false;
if (file_exists('vendor/autoload.php')) {
    require_once 'vendor/autoload.php';
    $dompdf_loaded = class_exists('Dompdf\Dompdf');
} elseif (file_exists('dompdf/autoload.inc.php')) {
    require_once 'dompdf/autoload.inc.php';
    $dompdf_loaded = class_exists('Dompdf\Dompdf');
}

// Debug function to log PDF generation issues
function logDebugInfo($message, $data = null) {
    error_log("PDF DEBUG: " . $message . ($data ? " | Data: " . print_r($data, true) : ""));
}

// PDF generation request handling commented out - buttons removed
/*
if (isset($_GET['generate_single_pdf']) && $_GET['generate_single_pdf'] == '1') {
    // Initialize variables needed for PDF generation
    $student_id = $_GET['student_id'] ?? '';
    $academic_year = $_GET['academic_year'] ?? '';
    $term = $_GET['term'] ?? '';
    $exam_id = $_GET['exam_id'] ?? '';
    $class_id = $_GET['class_id'] ?? '';
    $grading_scale_name = $_GET['grading_scale'] ?? '';
    
    // Validate required parameters
    if (empty($student_id) || empty($academic_year) || empty($term) || empty($exam_id) || empty($class_id)) {
        header('Content-Type: text/plain');
        echo "Missing required parameters for PDF generation";
        exit;
    }
    
    // Ensure connection is available
    if (!isset($connection)) {
        header('Content-Type: text/plain');
        echo "Database connection not available";
        exit;
    }
    
    logDebugInfo("PDF generation started", [
        'student_id' => $student_id,
        'academic_year' => $academic_year,
        'term' => $term,
        'exam_id' => $exam_id,
        'class_id' => $class_id,
        'dompdf_loaded' => $dompdf_loaded ?? false
    ]);
    
    // Generate the PDF and log the result data
    $pdf_result = generateSingleStudentPDF(
        $connection,
        $student_id,
        $academic_year,
        $term,
        $exam_id,
        $class_id
    );
    
    // Additional debug info about the generated data
    if ($pdf_result['success']) {
        // Get the data that was used to generate the PDF for debugging
        $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);
        
        logDebugInfo("PDF data debug", [
            'student_count' => count($student_data['student'] ?? []),
            'grades_count' => count($student_data['grades'] ?? []),
            'student_name' => $student_data['student']['username'] ?? 'NOT FOUND',
            'sample_grade' => !empty($student_data['grades']) ? $student_data['grades'][0] : 'NO GRADES'
        ]);
    }
    
    if (!isset($dompdf_loaded) || !$dompdf_loaded) {
        header('Content-Type: text/plain');
        echo "Dompdf library not loaded - cannot generate PDF";
        exit;
    }
    logDebugInfo("PDF generation result", $pdf_result);
    
    if ($pdf_result['success']) {
        header('Content-Type: application/pdf');
        header('Content-Disposition: attachment; filename="' . $pdf_result['filename'] . '"');
        header('Content-Length: ' . strlen($pdf_result['pdf_content']));
        echo $pdf_result['pdf_content'];
        exit;
    } else {
        header('Content-Type: text/plain');
        echo "Error generating PDF: " . $pdf_result['error'];
        exit;
    }
}
*/

// Note: Database connection should be created by config.php
// Using alias above to make $connection available from $conn

// Check authentication
if (!isset($_SESSION['id']) || !isset($_SESSION['loggedin']) || $_SESSION['loggedin'] != 1 || !isset($_SESSION['role']) || $_SESSION['role'] != 1) {
    header("Location: login.php");
    exit();
}

// Get parameters
$academic_year = $_GET['academic_year'] ?? '';
$term = $_GET['term'] ?? '';
$exam_id = $_GET['exam_id'] ?? '';
$class_id = $_GET['class_id'] ?? '';
$student_id = $_GET['student_id'] ?? ''; // For QR code access
$grading_scale_name = $_GET['grading_scale'] ?? ''; // Selected grading scale

// Check if this is a QR code access (single student view)
$is_qr_access = !empty($student_id);

if (empty($academic_year) || empty($term) || empty($exam_id) || empty($class_id)) {
    echo "<!DOCTYPE html><html><head><title>Error</title></head><body>";
    echo "<h2>Missing Parameters</h2>";
    if ($is_qr_access) {
        echo "<p>This link appears to be for a specific student report. Please contact the school for access.</p>";
    } else {
        echo "<a href='admin_reports_printouts.php'>← Back to Reports</a>";
    }
    echo "</body></html>";
    exit();
}

// Get class information
$sql_class = "SELECT class_name, school_id FROM classes WHERE class_id = ?";
$stmt_class = $connection->prepare($sql_class);
$stmt_class->bind_param("i", $class_id);
$stmt_class->execute();
$class_result = $stmt_class->get_result();
$class_info = $class_result->fetch_assoc();

if (!$class_info) {
    echo "<!DOCTYPE html><html><head><title>Error</title></head><body>";
    echo "<h2>Class Not Found</h2>";
    echo "<a href='admin_reports_printouts.php'>← Back to Reports</a>";
    echo "</body></html>";
    exit();
}

$class_name = $class_info['class_name'];
$class_school_id = $class_info['school_id'];

// Get school information
$sql_school = "SELECT school_name, address, phone, email, motto, logo FROM schools WHERE school_id = ?";
$stmt_school = $connection->prepare($sql_school);
$stmt_school->bind_param("i", $class_school_id);
$stmt_school->execute();
$result_school = $stmt_school->get_result();
$school = $result_school->fetch_assoc();

if (!$school) {
    echo "<!DOCTYPE html><html><head><title>Error</title></head><body>";
    echo "<h2>School not found</h2>";
    echo "<a href='admin_reports_printouts.php'>← Back to Reports</a>";
    echo "</body></html>";
    exit();
}

// Get exam details
$sql_exam = "SELECT exam_name FROM exams WHERE exam_id = ? AND school_id = ?";
$stmt_exam = $connection->prepare($sql_exam);
$stmt_exam->bind_param("ii", $exam_id, $class_school_id);
$stmt_exam->execute();
$result_exam = $stmt_exam->get_result();
$exam = $result_exam->fetch_assoc();

if (!$exam) {
    echo "<!DOCTYPE html><html><head><title>Error</title></head><body>";
    echo "<h2>Exam not found</h2>";
    echo "<a href='admin_reports_printouts.php'>← Back to Reports</a>";
    echo "</body></html>";
    exit();
}

// Configuration: Choose what to display in SUBJECTS column
// Options: 'name' (Subject Name) or 'code' (Subject Code)
define('SUBJECT_DISPLAY_MODE', 'name'); // Change to 'code' to show subject codes instead

// Helper function to get subject display text
function getSubjectDisplayText($subject_data) {
    if (SUBJECT_DISPLAY_MODE === 'code' && !empty($subject_data['subject_code'])) {
        return $subject_data['subject_code'];
    }
    return $subject_data['subject_name'];
}

// Function to determine class level
function getClassLevel($class_name) {
    $class_name_upper = strtoupper($class_name);
    
    // Check for S5-6 (A-Level)
    if (preg_match('/SENIOR\s*[56]|S\.?[56]\b|ALEVEL|A-LEVEL/i', $class_name_upper)) {
        return 'senior_level';
    }
    
    // Check for S3-4 (O-Level)
    if (preg_match('/SENIOR\s*[34]|S\.?[34]\b/i', $class_name_upper)) {
        return 'senior_olevel';
    }
    
    // Default to S1-2 (Lower levels)
    return 'lower_level';
}

// MODIFIED: Enhanced student query to include combination information

// Store chart data for all students
$all_chart_data = [];

if ($is_qr_access) {
    $sql_students = "
    SELECT 
        u.id as user_id, 
        u.username as student_name, 
        u.ADM, 
        u.parent_name, 
        u.parent_phone, 
        u.role, 
        u.class_id, 
        u.school_id, 
        u.photo,
        u.combination_id,
        c.class_name,
        sc.combination_code,
        sc.combination_name
    FROM users u
    LEFT JOIN subject_combinations sc ON u.combination_id = sc.combination_id
    LEFT JOIN classes c ON u.class_id = c.class_id
    WHERE u.id = ? AND u.class_id = ? AND u.school_id = ? AND u.role != 1";
    
    $stmt_students = $connection->prepare($sql_students);
    $stmt_students->bind_param("iii", $student_id, $class_id, $class_school_id);
} else {
    $sql_students = "
    SELECT 
        u.id as user_id, 
        u.username as student_name, 
        u.ADM, 
        u.parent_name, 
        u.parent_phone, 
        u.role, 
        u.class_id, 
        u.school_id, 
        u.photo,
        u.combination_id,
        c.class_name,
        c.class_level,
        sc.combination_code,
        sc.combination_name
    FROM users u
    LEFT JOIN subject_combinations sc ON u.combination_id = sc.combination_id
    LEFT JOIN classes c ON u.class_id = c.class_id
    WHERE u.class_id = ? AND u.school_id = ? AND u.role != 1
    ORDER by u.username";
    
    $stmt_students = $connection->prepare($sql_students);
    $stmt_students->bind_param("ii", $class_id, $class_school_id);
}
$stmt_students->execute();
$result_students = $stmt_students->get_result();

$students = [];
while ($row = $result_students->fetch_assoc()) {
    $students[] = $row;
}

// Validate QR code access
if ($is_qr_access && empty($students)) {
    echo "<!DOCTYPE html><html><head><title>Student Not Found</title></head><body>";
    echo "<h2>Student Not Found</h2>";
    echo "<p>The requested student could not be found or you don't have permission to view this report.</p>";
    echo "<p>Please contact the school administration for assistance.</p>";
    echo "</body></html>";
    exit();
}

// Determine class level
$class_level = getClassLevel($class_name);

// =============================================================================
// S3-4 SPECIFIC FUNCTIONALITY
// Handle S3-4 students with compulsory and optional subjects display
// =============================================================================

// Check if this is a specific S3-4 request
$s34_student_adm = $_GET['student_adm'] ?? '';
$s34_class_id = $_GET['s34_class_id'] ?? '';
$s34_stream_id = $_GET['s34_stream_id'] ?? '';
$s34_school_id = $_GET['s34_school_id'] ?? $class_school_id;
$s34_academic_year = $_GET['s34_academic_year'] ?? $academic_year;
$s34_term = $_GET['s34_term'] ?? $term;

// S3-4 Report Card Generation Function
function generateS34ReportCard($connection, $student_adm, $class_id, $stream_id, $school_id, $academic_year, $term) {
    try {
        // Get student information using student_adm (admission number)
        $sql_student = "SELECT u.*, c.class_name, s.stream_name 
                       FROM users u 
                       LEFT JOIN classes c ON u.class_id = c.class_id 
                       LEFT JOIN streams s ON u.stream_id = s.stream_id 
                       WHERE u.ADM = ? AND u.class_id = ? AND u.stream_id = ? AND u.school_id = ? AND u.role != 1";
        $stmt_student = $connection->prepare($sql_student);
        $stmt_student->bind_param("siii", $student_adm, $class_id, $stream_id, $school_id);
        $stmt_student->execute();
        $student_result = $stmt_student->get_result();
        $student = $student_result->fetch_assoc();
        $stmt_student->close();
        
        if (!$student) {
            return ['success' => false, 'error' => 'Student not found'];
        }
        
        // Fetch compulsory subjects for S3-4 (subjects with applicable_levels containing S3 or S4)
        $sql_compulsory = "SELECT * FROM subjects 
                          WHERE school_id = ? 
                          AND subject_category = 'Compulsory' 
                          AND (applicable_levels LIKE '%S3%' OR applicable_levels LIKE '%S4%')
                          ORDER BY subject_name";
        $stmt_compulsory = $connection->prepare($sql_compulsory);
        $stmt_compulsory->bind_param("i", $school_id);
        $stmt_compulsory->execute();
        $compulsory_result = $stmt_compulsory->get_result();
        $compulsory_subjects = [];
        while ($row = $compulsory_result->fetch_assoc()) {
            $compulsory_subjects[] = $row;
        }
        $stmt_compulsory->close();
        
        // Fetch student's optional subjects from student_subject_choices table
        $sql_optional = "SELECT s.* FROM student_subject_choices ssc
                        JOIN subjects s ON ssc.subject_id = s.subject_id
                        WHERE ssc.student_ADM = ? 
                        AND ssc.class_id = ?
                        AND ssc.stream_id = ?
                        AND ssc.school_id = ?
                        AND ssc.academic_year = ?
                        AND ssc.term = ?
                        ORDER BY s.subject_name
                        LIMIT 2"; // Limit to 2 subjects as specified
        $stmt_optional = $connection->prepare($sql_optional);
        $stmt_optional->bind_param("sisiss", $student_adm, $class_id, $stream_id, $school_id, $academic_year, $term);
        $stmt_optional->execute();
        $optional_result = $stmt_optional->get_result();
        $optional_subjects = [];
        while ($row = $optional_result->fetch_assoc()) {
            $optional_subjects[] = $row;
        }
        $stmt_optional->close();
        
        // Merge compulsory and optional subjects, avoiding duplicates
        $all_subjects = [];
        $subject_ids_seen = [];
        
        // Add compulsory subjects first
        foreach ($compulsory_subjects as $subject) {
            $all_subjects[] = [
                'subject_id' => $subject['subject_id'],
                'subject_name' => $subject['subject_name'],
                'subject_code' => $subject['subject_code'],
                'subject_category' => 'Compulsory',
                'is_compulsory' => true
            ];
            $subject_ids_seen[] = $subject['subject_id'];
        }
        
        // Add optional subjects (only if not already included as compulsory)
        foreach ($optional_subjects as $subject) {
            if (!in_array($subject['subject_id'], $subject_ids_seen)) {
                $all_subjects[] = [
                    'subject_id' => $subject['subject_id'],
                    'subject_name' => $subject['subject_name'],
                    'subject_code' => $subject['subject_code'],
                    'subject_category' => 'Optional',
                    'is_compulsory' => false
                ];
            } else {
                // If optional subject is also compulsory, mark it as both
                foreach ($all_subjects as &$existing_subject) {
                    if ($existing_subject['subject_id'] == $subject['subject_id']) {
                        $existing_subject['subject_category'] = 'Compulsory & Optional';
                        break;
                    }
                }
                unset($existing_subject);
            }
        }
        
        // Fetch marks for all subjects
        $subject_marks = [];
        if (!empty($all_subjects)) {
            $subject_ids = array_column($all_subjects, 'subject_id');
            $placeholders = str_repeat('?,', count($subject_ids) - 1) . '?';
            $sql_marks = "SELECT m.*, sp.paper_name 
                         FROM marks m 
                         LEFT JOIN subject_papers sp ON m.paper_id = sp.paper_id
                         WHERE m.student_id = ? AND m.subject_id IN ($placeholders)
                         ORDER BY m.subject_id";
            $stmt_marks = $connection->prepare($sql_marks);
            $params = array_merge([$student['id']], $subject_ids);
            $stmt_marks->bind_param(str_repeat('i', count($params)), ...$params);
            $stmt_marks->execute();
            $marks_result = $stmt_marks->get_result();
            while ($row = $marks_result->fetch_assoc()) {
                $subject_marks[$row['subject_id']] = $row;
            }
            $stmt_marks->close();
        }
        
        // Add marks data and teacher assignments to subjects
        foreach ($all_subjects as &$subject) {
            $subject['mark'] = $subject_marks[$subject['subject_id']]['mark'] ?? null;
            $subject['paper_name'] = $subject_marks[$subject['subject_id']]['paper_name'] ?? 'Main';
            
            // Get assigned teacher from class_subject_teachers table
            $teacher_name = 'Not Assigned';
            try {
                // Debug teacher query parameters for S3-4
                error_log("TEACHER QUERY DEBUG (S3-4): Class={$class_id} (type:" . gettype($class_id) . "), Subject={$subject['subject_id']} (type:" . gettype($subject['subject_id']) . "), Year={$academic_year} (type:" . gettype($academic_year) . "), Term={$term} (type:" . gettype($term) . ")");
                
                $sql_teacher_s34 = "SELECT u.username as teacher_name
                                   FROM class_subject_teachers cst
                                   JOIN users u ON cst.teacher_user_id = u.id
                                   WHERE cst.class_id = ? AND cst.subject_id = ? 
                                   AND cst.academic_year = ? AND cst.term = ?
                                   LIMIT 1";
                $stmt_teacher_s34 = $connection->prepare($sql_teacher_s34);
                
                // Use proper parameter types - ensure class_id and subject_id are integers
                $class_id_int = (int)$class_id;
                $subject_id_int = (int)$subject['subject_id'];
                $academic_year_int = (int)$academic_year;
                
                $stmt_teacher_s34->bind_param("iiis", $class_id_int, $subject_id_int, $academic_year_int, $term);
                
                if (!$stmt_teacher_s34->execute()) {
                    error_log("TEACHER QUERY ERROR (S3-4): " . $stmt_teacher_s34->error);
                    $stmt_teacher_s34->close();
                } else {
                    $result_teacher_s34 = $stmt_teacher_s34->get_result();
                    $teacher_data_s34 = $result_teacher_s34->fetch_assoc();
                    $stmt_teacher_s34->close();

                    if ($teacher_data_s34) {
                        $teacher_name = $teacher_data_s34['teacher_name'];
                        error_log("TEACHER FOUND (S3-4): Subject {$subject['subject_id']} - {$teacher_name}");
                    } else {
                        error_log("NO TEACHER (S3-4): Subject {$subject['subject_id']} - Class {$class_id}, Year {$academic_year}, Term {$term}");
                    }
                }
            } catch (Exception $e) {
                error_log("Teacher lookup failed (S3-4): " . $e->getMessage());
            }
            
            $subject['teacher_name'] = $teacher_name;
            
            // Calculate grade based on mark (O-Level grading system)
            if ($subject['mark'] !== null) {
                if ($subject['mark'] >= 90) $subject['grade'] = 'A+';
                elseif ($subject['mark'] >= 80) $subject['grade'] = 'A';
                elseif ($subject['mark'] >= 70) $subject['grade'] = 'B';
                elseif ($subject['mark'] >= 60) $subject['grade'] = 'C';
                elseif ($subject['mark'] >= 50) $subject['grade'] = 'D';
                elseif ($subject['mark'] >= 40) $subject['grade'] = 'E';
                else $subject['grade'] = 'F';
            } else {
                $subject['grade'] = 'N/A';
            }
        }
        unset($subject);
        
        // Calculate summary statistics
        $marks = array_filter(array_column($all_subjects, 'mark'), function($mark) { return $mark !== null; });
        $total_marks = array_sum($marks);
        $subject_count = count($marks);
        $average_mark = $subject_count > 0 ? round($total_marks / $subject_count, 1) : 0;
        
        return [
            'success' => true,
            'student' => $student,
            'subjects' => $all_subjects,
            'summary' => [
                'total_subjects' => count($all_subjects),
                'total_marks' => round($total_marks, 1),
                'average_mark' => $average_mark,
                'compulsory_count' => count(array_filter($all_subjects, function($s) { return $s['is_compulsory']; })),
                'optional_count' => count(array_filter($all_subjects, function($s) { return !$s['is_compulsory']; }))
            ]
        ];
        
    } catch (Exception $e) {
        error_log("S3-4 Report Card Error: " . $e->getMessage());
        return ['success' => false, 'error' => 'Failed to generate S3-4 report card'];
    }
}

// Generate S3-4 report card if requested
if (!empty($s34_student_adm) && !empty($s34_class_id) && !empty($s34_stream_id)) {
    $s34_report_data = generateS34ReportCard(
        $connection,
        $s34_student_adm,
        $s34_class_id,
        $s34_stream_id,
        $s34_school_id,
        $s34_academic_year,
        $s34_term
    );
    
    // S3-4 PDF generation request handling commented out - buttons removed
    /*
    if (isset($_GET['generate_s34_pdf']) && $_GET['generate_s34_pdf'] == '1') {
        if ($s34_report_data['success'] && class_exists('Dompdf\Dompdf')) {
            // Generate S3-4 specific PDF
            $html = generateS34PDFHTML($s34_report_data, $s34_academic_year, $s34_term, $class_school_id);
            $dompdf = new Dompdf\Dompdf([
                'isRemoteEnabled' => true,
                'isHtml5ParserEnabled' => true,
                'defaultFont' => 'DejaVu Sans'
            ]);
            $dompdf->loadHtml($html);
            $dompdf->setPaper('A4', 'portrait');
            $dompdf->render();
            
            $filename = "S34_Report_" . $s34_report_data['student']['username'] . "_{$s34_term}_{$s34_academic_year}.pdf";
            header('Content-Type: application/pdf');
            header('Content-Disposition: attachment; filename="' . $filename . '"');
            header('Content-Length: ' . strlen($dompdf->output()));
            echo $dompdf->output();
            exit;
        } else {
            echo "Error generating S3-4 PDF: " . ($s34_report_data['error'] ?? 'Unknown error');
            exit;
        }
    }
    */
}

// Include all the existing helper functions from the original file
function getSubjectPapers($subject_id, $school_id, $connection) {
    try {
        $sql = "SELECT paper_id, paper_name FROM subject_papers WHERE subject_id = ? AND school_id = ? ORDER BY paper_name";
        $stmt = $connection->prepare($sql);
        $stmt->bind_param("ii", $subject_id, $school_id);
        $stmt->execute();
        $result = $stmt->get_result();
        $papers = [];
        while ($row = $result->fetch_assoc()) {
            $papers[] = $row;
        }
        $stmt->close();
        return $papers;
    } catch (Exception $e) {
        error_log("Error fetching subject papers: " . $e->getMessage());
        return [];
    }
}

function getGradeFromScale($mark, $subject_id, $class_id, $academic_year, $term, $school_id, $connection, $grading_scale_name = '', $class_level = '') {
    try {
        // Build the SQL query with optional grading scale name filter
        if (!empty($grading_scale_name)) {
            // Use specific grading scale
            $sql = "SELECT grade_letter, grade, remarks FROM grading_scales 
                    WHERE school_id = ? AND grade_name = ?
                    AND (subject_id = ? OR subject_id = 0)
                    AND min_score <= ? AND max_score >= ?
                    ORDER BY min_score DESC LIMIT 1";
            $stmt = $connection->prepare($sql);
            $stmt->bind_param("isiii", $school_id, $grading_scale_name, $subject_id, $mark, $mark);
        } else {
            // Original logic - use academic year and term
            $sql = "SELECT grade_letter, grade, remarks FROM grading_scales 
                    WHERE school_id = ? AND academic_year = ? AND term_name = ?
                    AND (subject_id = ? OR subject_id IS NULL)
                    AND min_score <= ? AND max_score >= ?
                    ORDER BY min_score DESC LIMIT 1";
            $stmt = $connection->prepare($sql);
            $stmt->bind_param("issiii", $school_id, $academic_year, $term, $subject_id, $mark, $mark);
        }
        
        $stmt->execute();
        $result = $stmt->get_result();
        $grade_info = $result->fetch_assoc();
        $stmt->close();
        
        if ($grade_info) {
            // For senior 5 and 6 students, prefer the specific grade over grade_letter
            if ($class_level === 'senior_level' && !empty($grade_info['grade'])) {
                $grade_info['display_grade'] = $grade_info['grade'];
            } else {
                $grade_info['display_grade'] = $grade_info['grade_letter'];
            }
            return $grade_info;
        } else {
            // Fallback grading
            if ($mark >= 90) return ['grade_letter' => 'A+', 'grade' => '', 'display_grade' => 'A+', 'remarks' => 'Outstanding performance!'];
            if ($mark >= 80) return ['grade_letter' => 'A', 'grade' => '', 'display_grade' => 'A', 'remarks' => 'Excellent performance!'];
            if ($mark >= 70) return ['grade_letter' => 'B', 'grade' => '', 'display_grade' => 'B', 'remarks' => 'Very good performance!'];
            if ($mark >= 60) return ['grade_letter' => 'C', 'grade' => '', 'display_grade' => 'C', 'remarks' => 'Good performance!'];
            if ($mark >= 50) return ['grade_letter' => 'D', 'grade' => '', 'display_grade' => 'D', 'remarks' => 'Average performance!'];
            return ['grade_letter' => 'F', 'grade' => '', 'display_grade' => 'F', 'remarks' => 'Needs improvement!'];
        }
    } catch (Exception $e) {
        return ['grade_letter' => 'N/A', 'grade' => '', 'display_grade' => 'N/A', 'remarks' => 'Grade not available'];
    }
}

// Calculate UACE subject grade from paper grades
function calculateUACESubjectGrade($paper_grades, $paper_count) {
    if ($paper_count == 2) {
        return calculateUACE2PaperSubject($paper_grades);
    } elseif ($paper_count == 3) {
        return calculateUACE3PaperSubject($paper_grades);
    } elseif ($paper_count == 4) {
        return calculateUACE4PaperSubject($paper_grades);
    } else {
        return calculateUACESinglePaper($paper_grades[0] ?? '');
    }
}

// UACE 2-paper subject grading
function calculateUACE2PaperSubject($paper_grades) {
    // Convert grades to numeric values for calculation
    $grade_values = [];
    foreach ($paper_grades as $grade) {
        $numeric_grade = gradeToNumber($grade);
        $grade_values[] = $numeric_grade;
    }
    
    sort($grade_values); // Sort in ascending order to find worst grade
    $worst = $grade_values[0];
    $best = $grade_values[1];
    $aggregate = array_sum($grade_values);
    
    // DEBUG: Log the calculation details
    error_log("UACE 2-PAPER DEBUG: Input grades: " . json_encode($paper_grades) . " -> Numeric: " . json_encode($grade_values) . " -> Worst: $worst, Best: $best, Aggregate: $aggregate");
    
    // Principal Pass A: Both papers distinctions (1,2)
    if (in_array(1, $grade_values) && in_array(2, $grade_values)) {
        error_log("UACE 2-PAPER RESULT: Returning A (distinctions)");
        return ['grade' => 'A', 'grade_letter' => 'A', 'classification' => 'Principal Pass'];
    }
    
    // Principal Pass B: C3 in one with better in other, or C3 both
    if (in_array(3, $grade_values) && ($best <= 2)) {
        return ['grade' => 'B', 'grade_letter' => 'B', 'classification' => 'Principal Pass'];
    }
    
    // Principal Pass C: C4 in one with better, or C4 both
    if (in_array(4, $grade_values) && ($best <= 3)) {
        return ['grade' => 'C', 'grade_letter' => 'C', 'classification' => 'Principal Pass'];
    }
    
    // Principal Pass D: C5 in one with better, or C5 both
    if (in_array(5, $grade_values) && ($best <= 4)) {
        return ['grade' => 'D', 'grade_letter' => 'D', 'classification' => 'Principal Pass'];
    }
    
    // Principal Pass E: C6 combinations, or P7/P8 with aggregate ≤12
    if (in_array(6, $grade_values) && ($best <= 5)) {
        return ['grade' => 'E', 'grade_letter' => 'E', 'classification' => 'Principal Pass'];
    }
    
    // Subsidiary Pass O: P7/P8 with aggregate ≤16, or credit+F9
    if ($aggregate <= 16 || (in_array(8, $grade_values) && in_array(7, $grade_values))) {
        return ['grade' => 'O', 'grade_letter' => 'O', 'classification' => 'Subsidiary Pass'];
    }
    
    // Fail F: F9+P8, or F9 both
    return ['grade' => 'F', 'grade_letter' => 'F', 'classification' => 'Fail'];
}

// UACE 3-paper subject grading
function calculateUACE3PaperSubject($paper_grades) {
    $grade_values = [];
    foreach ($paper_grades as $grade) {
        $numeric_grade = gradeToNumber($grade);
        $grade_values[] = $numeric_grade;
    }
    
    sort($grade_values);
    $worst = $grade_values[0];
    $aggregate = array_sum($grade_values);
    
    // DEBUG: Log the calculation details
    error_log("UACE 3-PAPER DEBUG: Input grades: " . json_encode($paper_grades) . " -> Numeric: " . json_encode($grade_values) . " -> Worst: $worst, Aggregate: $aggregate");
    
    // Count F9 grades (these are fails and should disqualify from A grades)
    $f9_count = array_count_values($grade_values)[9] ?? 0;
    error_log("UACE 3-PAPER DEBUG: F9 count: $f9_count");
    
    // Count distinctions (D1, D2 = 1,2) - must be done BEFORE A grade check
    $distinction_count = 0;
    foreach ($grade_values as $val) {
        if ($val <= 2) $distinction_count++;
    }
    error_log("UACE 3-PAPER DEBUG: Distinction count: $distinction_count");
    
    // Principal Pass A: At worst C3 in one paper AND distinctions in the other two papers, NO F9s
    if ($worst <= 3 && $distinction_count >= 2 && $f9_count == 0) {
        error_log("UACE 3-PAPER RESULT: Returning A (worst=$worst <= 3, $distinction_count distinctions, no F9s)");
        return ['grade' => 'A', 'grade_letter' => 'A', 'classification' => 'Principal Pass'];
    }
    
    // Principal Pass B: At worst C4 in one, better in other two, NO F9s
    if ($worst <= 4 && $f9_count == 0) {
        return ['grade' => 'B', 'grade_letter' => 'B', 'classification' => 'Principal Pass'];
    }
    
    // Principal Pass C: At worst C5 in one, better in other two, NO F9s
    if ($worst <= 5 && $f9_count == 0) {
        return ['grade' => 'C', 'grade_letter' => 'C', 'classification' => 'Principal Pass'];
    }
    
    // Principal Pass D: At worst C6 in one, better in other two, NO F9s
    if ($worst <= 6 && $f9_count == 0) {
        return ['grade' => 'D', 'grade_letter' => 'D', 'classification' => 'Principal Pass'];
    }
    
    // Principal Pass E: P7 in one with credit/better in other two, NO F9s
    if ($worst <= 7 && $f9_count == 0) {
        return ['grade' => 'E', 'grade_letter' => 'E', 'classification' => 'Principal Pass'];
    }
    
    // Subsidiary Pass O: All P7/P8, or distinctions + F9s, or F9 in 1-2 with P7+ in remaining
    $p7p8_count = (array_count_values($grade_values)[7] ?? 0) + (array_count_values($grade_values)[8] ?? 0);
    
    // Case 1: All P7/P8 grades
    if ($worst >= 7 && $worst <= 8) {
        error_log("UACE 3-PAPER RESULT: Returning O (all P7/P8 grades)");
        return ['grade' => 'O', 'grade_letter' => 'O', 'classification' => 'Subsidiary Pass'];
    }
    
    // Case 2: Distinguished grades with F9s (D1,D2 + F9 = O)
    if ($distinction_count > 0 && $f9_count > 0 && $f9_count <= 2) {
        error_log("UACE 3-PAPER RESULT: Returning O (distinctions with F9s)");
        return ['grade' => 'O', 'grade_letter' => 'O', 'classification' => 'Subsidiary Pass'];
    }
    
    // Case 3: F9s with P7/P8 grades (no distinctions)
    if ($f9_count <= 2 && $p7p8_count >= 1 && $distinction_count == 0) {
        error_log("UACE 3-PAPER RESULT: Returning O (F9s with P7/P8, no distinctions)");
        return ['grade' => 'O', 'grade_letter' => 'O', 'classification' => 'Subsidiary Pass'];
    }
    
    // Fail F: F9s with no distinctions or P7/P8 grades to compensate
    if ($f9_count > 0 && $distinction_count == 0 && $p7p8_count == 0) {
        error_log("UACE 3-PAPER RESULT: Returning F (F9s with no distinctions or P7/P8)");
        return ['grade' => 'F', 'grade_letter' => 'F', 'classification' => 'Fail'];
    }
    
    // Default to fail if no other conditions met
    error_log("UACE 3-PAPER RESULT: Returning F (default)");
    return ['grade' => 'F', 'grade_letter' => 'F', 'classification' => 'Fail'];
}

// UACE 4-paper subject grading
function calculateUACE4PaperSubject($paper_grades) {
    $grade_values = [];
    foreach ($paper_grades as $grade) {
        $grade_values[] = gradeToNumber($grade);
    }
    
    sort($grade_values);
    $worst = $grade_values[0];
    $aggregate = array_sum($grade_values);
    
    // Count F9 grades
    $f9_count = array_count_values($grade_values)[9] ?? 0;
    error_log("UACE 4-PAPER DEBUG: F9 count: $f9_count");
    
    // Count distinctions (D1, D2 = 1,2)
    $distinction_count = 0;
    foreach ($grade_values as $val) {
        if ($val <= 2) $distinction_count++;
    }
    error_log("UACE 4-PAPER DEBUG: Distinction count: $distinction_count");
    
    // Principal Pass A: At worst C3 in one, distinctions in other three, NO F9s
    if ($worst <= 3 && $f9_count == 0) {
        return ['grade' => 'A', 'grade_letter' => 'A', 'classification' => 'Principal Pass'];
    }
    
    // Principal Pass B: At worst C4 in one, better in other three, NO F9s
    if ($worst <= 4 && $f9_count == 0) {
        return ['grade' => 'B', 'grade_letter' => 'B', 'classification' => 'Principal Pass'];
    }
    
    // Principal Pass C: At worst C5 in one, better in other three, NO F9s
    if ($worst <= 5 && $f9_count == 0) {
        return ['grade' => 'C', 'grade_letter' => 'C', 'classification' => 'Principal Pass'];
    }
    
    // Principal Pass D: At worst C6 in one, better in other three, NO F9s
    if ($worst <= 6 && $f9_count == 0) {
        return ['grade' => 'D', 'grade_letter' => 'D', 'classification' => 'Principal Pass'];
    }
    
    // Principal Pass E: P7 in one with credit/better in other three, NO F9s
    if ($worst <= 7 && $f9_count == 0) {
        return ['grade' => 'E', 'grade_letter' => 'E', 'classification' => 'Principal Pass'];
    }
    
    // Subsidiary Pass O: All P7/P8, or distinctions + F9s, or F9 in 1-2 with P7+ in remaining
    $p7p8_count = (array_count_values($grade_values)[7] ?? 0) + (array_count_values($grade_values)[8] ?? 0);
    
    // Case 1: All P7/P8 grades  
    if ($worst >= 7 && $worst <= 8) {
        error_log("UACE 4-PAPER RESULT: Returning O (all P7/P8 grades)");
        return ['grade' => 'O', 'grade_letter' => 'O', 'classification' => 'Subsidiary Pass'];
    }
    
    // Case 2: Distinguished grades with F9s (D1,D2 + F9 = O)
    if ($distinction_count > 0 && $f9_count > 0 && $f9_count <= 2) {
        error_log("UACE 4-PAPER RESULT: Returning O (distinctions with F9s)");
        return ['grade' => 'O', 'grade_letter' => 'O', 'classification' => 'Subsidiary Pass'];
    }
    
    // Case 3: F9s with P7/P8 grades (no distinctions)
    if ($f9_count <= 2 && $p7p8_count >= 2 && $distinction_count == 0) {
        error_log("UACE 4-PAPER RESULT: Returning O (F9s with P7/P8, no distinctions)");
        return ['grade' => 'O', 'grade_letter' => 'O', 'classification' => 'Subsidiary Pass'];
    }
    
    // Fail F: Too many F9s (3 or more) OR combinations that don't meet O-grade criteria
    if ($f9_count >= 3) {
        error_log("UACE 4-PAPER RESULT: Returning F (F9 count >= 3)");
        return ['grade' => 'F', 'grade_letter' => 'F', 'classification' => 'Fail'];
    }
    
    // Fail F: Too many F9s with no good grades to compensate
    if ($f9_count > 0 && $distinction_count == 0 && $p7p8_count == 0) {
        error_log("UACE 4-PAPER RESULT: Returning F (F9s with no distinctions or P7/P8)");
        return ['grade' => 'F', 'grade_letter' => 'F', 'classification' => 'Fail'];
    }
    
    // Default to fail
    error_log("UACE 4-PAPER RESULT: Returning F (default)");
    return ['grade' => 'F', 'grade_letter' => 'F', 'classification' => 'Fail'];
}

// UACE single paper (subsidiary) grading
function calculateUACESinglePaper($grade) {
    $grade_value = gradeToNumber($grade);
    
    // Subsidiary Pass O: Grades 1-6
    if ($grade_value >= 1 && $grade_value <= 6) {
        return ['grade' => 'O', 'grade_letter' => 'O', 'classification' => 'Subsidiary Pass'];
    }
    
    // Fail F: Grades 7-9
    return ['grade' => 'F', 'grade_letter' => 'F', 'classification' => 'Fail'];
}

// Helper function to convert grade letters to numeric values
function gradeToNumber($grade) {
    // UACE grade mapping: Distinctions (1-2), Credits (3-6), Passes (7-8), Fails (9)
    $grade_map = [
        // Distinctions (1-2)
        'A' => 1, 'A1' => 1, 'A2' => 2, 'D1' => 1, 'D2' => 2,
        // Credits (3-6)
        'B' => 2, 'B3' => 3, 'B4' => 4, 'C' => 3, 'C3' => 3, 'C4' => 4, 'C5' => 5, 'C6' => 6,
        // Passes (7-8)
        'D' => 4, 'E' => 5, 'P7' => 7, 'P8' => 8,
        // Fails (9)
        'F' => 6, 'F9' => 9,
        // Additional mappings for common variations
        'D3' => 3, 'D4' => 4, 'D5' => 5, 'D6' => 6,
        'E7' => 7, 'E8' => 8
    ];
    
    $numeric_grade = $grade_map[$grade] ?? null;
    
    // If grade not found in mapping, try to extract number from strings like "C3", "D1", etc.
    if ($numeric_grade === null) {
        preg_match('/(\d+)/', $grade, $matches);
        if (!empty($matches[1])) {
            $numeric_grade = (int)$matches[1];
        } else {
            // Fallback for common grades
            $fallback_map = ['A' => 1, 'B' => 2, 'C' => 3, 'D' => 4, 'E' => 5, 'F' => 6];
            $numeric_grade = $fallback_map[$grade] ?? 9;
        }
    }
    
    return $numeric_grade; // Default to 9 (F9) if still not found
}

// Get UACE points for a subject grade
function getUACEPoints($grade_letter, $grade, $paper_count) {
    $grade_points = [
        'A' => 6, 'B' => 5, 'C' => 4, 'D' => 3, 'E' => 2, 'O' => 1, 'F' => 0
    ];
    
    return $grade_points[$grade_letter] ?? 0;
}

// Calculate stream rank for a student
function calculateStreamRank($student_id, $class_id, $connection) {
    try {
        // Get student's stream_id first
        $sql_stream = "SELECT stream_id FROM users WHERE id = ?";
        $stmt_stream = $connection->prepare($sql_stream);
        $stmt_stream->bind_param("i", $student_id);
        $stmt_stream->execute();
        $result_stream = $stmt_stream->get_result();
        $stream_data = $result_stream->fetch_assoc();
        $stream_id = $stream_data['stream_id'] ?? null;
        $stmt_stream->close();
        
        if (!$stream_id) {
            error_log("STUDENT {$student_id} - No stream_id found for stream rank calculation");
            return '--';
        }
        
        // Get all students in the same stream with their performance data
        // Using existing marks table instead of exam_results
        $sql = "SELECT u.id as user_id,
                       COALESCE(SUM(CASE 
                           WHEN m.mark IS NOT NULL 
                           THEN CASE 
                               -- Convert marks to grades and calculate points
                               WHEN m.mark >= 80 THEN 6  -- A grade (80-100%)
                               WHEN m.mark >= 70 THEN 5  -- B grade (70-79%)
                               WHEN m.mark >= 60 THEN 4  -- C grade (60-69%)
                               WHEN m.mark >= 50 THEN 3  -- D grade (50-59%)
                               WHEN m.mark >= 40 THEN 2  -- E grade (40-49%)
                               WHEN m.mark >= 30 THEN 1  -- O grade (30-39%)
                               ELSE 0                   -- F grade (0-29%)
                           END
                           ELSE 0
                       END), 0) as total_points
                FROM users u
                LEFT JOIN marks m ON u.id = m.student_id
                WHERE u.stream_id = ?
                GROUP BY u.id
                ORDER BY total_points DESC";
        
        $stmt = $connection->prepare($sql);
        $stmt->bind_param("i", $stream_id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        $rank = 1;
        while ($row = $result->fetch_assoc()) {
            error_log("STREAM RANK - Student: {$row['user_id']}, Points: {$row['total_points']}, Rank: {$rank}");
            if ($row['user_id'] == $student_id) {
                $stmt->close();
                error_log("STUDENT {$student_id} - Stream rank calculated: {$rank}");
                return $rank;
            }
            $rank++;
        }
        
        $stmt->close();
        error_log("STUDENT {$student_id} - Stream rank not found, returning '--'");
        return '--';
    } catch (Exception $e) {
        error_log("Error calculating stream rank for student {$student_id}: " . $e->getMessage());
        return '--';
    }
}

// Calculate overall rank for a student (across all classes in the same level)
function calculateOverallRank($student_id, $class_level, $connection) {
    try {
        // DEBUG: Log the parameters received
        error_log("DEBUG calculateOverallRank - Student: {$student_id}, class_level received: {$class_level}");
        if ($class_level === 'senior_level') {
            error_log("DEBUG calculateOverallRank - Converting 'senior_level' to 'S5' for database query");
        }
        
        // FIXED: A-Level calculation with Principal/Subsidiary classification based on subject names
        $sql = "SELECT 
                    u.id as user_id,
                    COALESCE(SUM(
                        CASE 
                            -- Principal subjects: Grade-based points (A=6, B=5, C=4, D=3, E=2, O=1)
                            WHEN s.subject_name IN ('HISTORY', 'ECONOMICS', 'MATHEMATICS', 'PHYSICS', 'DIVINITY', 'SUB-MATH') THEN
                                CASE 
                                    WHEN AVG(m.mark) >= 80 THEN 6  -- A grade equivalent
                                    WHEN AVG(m.mark) >= 70 THEN 5  -- B grade equivalent
                                    WHEN AVG(m.mark) >= 60 THEN 4  -- C grade equivalent
                                    WHEN AVG(m.mark) >= 50 THEN 3  -- D grade equivalent
                                    WHEN AVG(m.mark) >= 40 THEN 2  -- E grade equivalent
                                    WHEN AVG(m.mark) >= 30 THEN 1  -- O grade equivalent
                                    ELSE 0
                                END
                            -- Subsidiary subjects: 1 point for passing
                            WHEN s.subject_name IN ('GENERAL PAPER', 'ICT', 'ART', 'ENTREPRENEURSHIP', 'AGRICULTURE') THEN
                                CASE WHEN AVG(m.mark) >= 40 THEN 1 ELSE 0 END
                            ELSE 0
                        END), 0) as total_points
                FROM users u
                JOIN classes c ON u.class_id = c.class_id
                JOIN marks m ON u.id = m.student_id
                JOIN subjects s ON m.subject_id = s.subject_id
                WHERE c.class_level = ?
                GROUP BY u.id
                ORDER BY total_points DESC";
        
        // FIXED: Convert class_level parameter back to database format
        $db_class_level = ($class_level === 'senior_level') ? 'S5' : $class_level;
        error_log("OVERALL RANK DEBUG - Input class_level: {$class_level}, DB class_level: {$db_class_level}");
        
        $stmt = $connection->prepare($sql);
        $stmt->bind_param("s", $db_class_level);
        $stmt->execute();
        $result = $stmt->get_result();
        
        $rank = 1;
        while ($row = $result->fetch_assoc()) {
            error_log("OVERALL RANK (HED/SM) - Student: {$row['user_id']}, Points: {$row['total_points']}, Rank: {$rank}");
            if ($row['user_id'] == $student_id) {
                $stmt->close();
                error_log("STUDENT {$student_id} - HED/SM Overall rank calculated: {$rank}");
                return $rank;
            }
            $rank++;
        }
        
        $stmt->close();
        error_log("STUDENT {$student_id} - HED/SM Overall rank not found, returning '--'");
        return '--';
    } catch (Exception $e) {
        error_log("Error calculating HED/SM overall rank for student {$student_id}: " . $e->getMessage());
        return '--';
    }
}

// Fallback function to calculate stream rank based on stored performance data
function getStreamRankFallback($student_id, $class_id, $connection) {
    try {
        // Get student's stream_id
        $sql_stream = "SELECT stream_id FROM users WHERE id = ?";
        $stmt_stream = $connection->prepare($sql_stream);
        $stmt_stream->bind_param("i", $student_id);
        $stmt_stream->execute();
        $result_stream = $stmt_stream->get_result();
        $stream_data = $result_stream->fetch_assoc();
        $stream_id = $stream_data['stream_id'] ?? null;
        $stmt_stream->close();
        
        if (!$stream_id) {
            return '--';
        }
        
        // CORRECTED: A-Level HED/SM calculation - same logic as overall rank
        $sql = "SELECT u.id as user_id,
                       COALESCE(
                           SUM(CASE 
                               WHEN subject_data.subject_name IN ('PHYSICS', 'ICT') THEN
                                   CASE 
                                       WHEN subject_data.mark_avg >= 80 THEN 6  -- A grade
                                       WHEN subject_data.mark_avg >= 70 THEN 5  -- B grade
                                       WHEN subject_data.mark_avg >= 60 THEN 4  -- C grade
                                       WHEN subject_data.mark_avg >= 50 THEN 3  -- D grade
                                       WHEN subject_data.mark_avg >= 40 THEN 2  -- E grade
                                       WHEN subject_data.mark_avg >= 30 THEN 1  -- O grade
                                       ELSE 0                                   -- F grade
                                   END
                               WHEN subject_data.subject_name IN ('ECONOMICS', 'TECHNOLOGY & DESIGN') AND 
                                    subject_data.is_top_principal = 1 THEN
                                   CASE 
                                       WHEN subject_data.mark_avg >= 80 THEN 6  -- A grade
                                       WHEN subject_data.mark_avg >= 70 THEN 5  -- B grade
                                       WHEN subject_data.mark_avg >= 60 THEN 4  -- C grade
                                       WHEN subject_data.mark_avg >= 50 THEN 3  -- D grade
                                       WHEN subject_data.mark_avg >= 40 THEN 2  -- E grade
                                       WHEN subject_data.mark_avg >= 30 THEN 1  -- O grade
                                       ELSE 0                                   -- F grade
                                   END
                               -- Subsidiary subjects: 1 point for passing
                               WHEN subject_data.subject_name = 'GENERAL PAPER' THEN
                                   CASE WHEN subject_data.mark_avg >= 40 THEN 1 ELSE 0 END
                               WHEN subject_data.subject_name IN ('ECONOMICS', 'TECHNOLOGY & DESIGN') AND 
                                    subject_data.is_top_principal = 0 THEN
                                   CASE WHEN subject_data.mark_avg >= 40 THEN 1 ELSE 0 END
                               ELSE 0
                           END), 0
                       ) as total_points
                FROM users u
                LEFT JOIN (
                    -- Calculate subject averages and identify Principal vs Subsidiary for HED/SM
                    SELECT 
                        m.student_id,
                        s.subject_name,
                        AVG(m.mark) as mark_avg,
                        -- For HED/SM: Identify which Economics/Technology subject is Principal (the better one)
                        CASE 
                            WHEN s.subject_name IN ('ECONOMICS', 'TECHNOLOGY & DESIGN') THEN
                                CASE 
                                    -- Mark as Principal if it's the better of the two
                                    WHEN AVG(m.mark) = (
                                        SELECT MAX(avg_mark) 
                                        FROM (
                                            SELECT AVG(m2.mark) as avg_mark
                                            FROM marks m2
                                            JOIN subjects s2 ON m2.subject_id = s2.subject_id
                                            WHERE m2.student_id = m.student_id 
                                            AND s2.subject_name IN ('ECONOMICS', 'TECHNOLOGY & DESIGN')
                                            GROUP BY s2.subject_name
                                        ) inner_sub
                                    ) THEN 1
                                    ELSE 0
                                END
                            ELSE NULL
                        END as is_top_principal
                    FROM marks m
                    JOIN subjects s ON m.subject_id = s.subject_id
                    GROUP BY m.student_id, s.subject_name
                ) subject_data ON u.id = subject_data.student_id
                WHERE u.stream_id = ?
                GROUP BY u.id
                ORDER BY total_points DESC";
        
        $stmt = $connection->prepare($sql);
        $stmt->bind_param("i", $stream_id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        $rank = 1;
        while ($row = $result->fetch_assoc()) {
            if ($row['user_id'] == $student_id) {
                $stmt->close();
                return $rank;
            }
            $rank++;
        }
        
        $stmt->close();
        return '--';
    } catch (Exception $e) {
        error_log("Fallback stream rank calculation failed for student {$student_id}: " . $e->getMessage());
        return '--';
    }
}

// Fallback function to calculate overall rank based on stored performance data
function getOverallRankFallback($student_id, $class_level, $connection) {
    try {
        // DEBUG: Log the parameters received
        error_log("DEBUG getOverallRankFallback - Student: {$student_id}, class_level received: {$class_level}");
        if ($class_level === 'senior_level') {
            error_log("DEBUG getOverallRankFallback - Converting 'senior_level' to 'S5' for database query");
        }
        
        // FIXED: A-Level calculation with Principal/Subsidiary classification based on subject names
        $sql = "SELECT 
                    u.id as user_id,
                    COALESCE(SUM(
                        CASE 
                            -- Principal subjects: Grade-based points (A=6, B=5, C=4, D=3, E=2, O=1)
                            WHEN s.subject_name IN ('HISTORY', 'ECONOMICS', 'MATHEMATICS', 'PHYSICS', 'DIVINITY', 'SUB-MATH') THEN
                                CASE 
                                    WHEN AVG(m.mark) >= 80 THEN 6  -- A grade equivalent
                                    WHEN AVG(m.mark) >= 70 THEN 5  -- B grade equivalent
                                    WHEN AVG(m.mark) >= 60 THEN 4  -- C grade equivalent
                                    WHEN AVG(m.mark) >= 50 THEN 3  -- D grade equivalent
                                    WHEN AVG(m.mark) >= 40 THEN 2  -- E grade equivalent
                                    WHEN AVG(m.mark) >= 30 THEN 1  -- O grade equivalent
                                    ELSE 0
                                END
                            -- Subsidiary subjects: 1 point for passing
                            WHEN s.subject_name IN ('GENERAL PAPER', 'ICT', 'ART', 'ENTREPRENEURSHIP', 'AGRICULTURE') THEN
                                CASE WHEN AVG(m.mark) >= 40 THEN 1 ELSE 0 END
                            ELSE 0
                        END), 0) as total_points
                FROM users u
                JOIN classes c ON u.class_id = c.class_id
                JOIN marks m ON u.id = m.student_id
                JOIN subjects s ON m.subject_id = s.subject_id
                WHERE c.class_level = ?
                GROUP BY u.id
                ORDER BY total_points DESC";
        
        // FIXED: Convert class_level parameter back to database format
        $db_class_level = ($class_level === 'senior_level') ? 'S5' : $class_level;
        error_log("OVERALL RANK DEBUG - Input class_level: {$class_level}, DB class_level: {$db_class_level}");
        
        $stmt = $connection->prepare($sql);
        $stmt->bind_param("s", $db_class_level);
        $stmt->execute();
        $result = $stmt->get_result();
        
        $rank = 1;
        while ($row = $result->fetch_assoc()) {
            if ($row['user_id'] == $student_id) {
                $stmt->close();
                return $rank;
            }
            $rank++;
        }
        
        $stmt->close();
        return '--';
    } catch (Exception $e) {
        error_log("Fallback HED/SM overall rank calculation failed for student {$student_id}: " . $e->getMessage());
        return '--';
    }
}

// Determine if a subject is Principal or Subsidiary based on combination
function isPrincipalSubject($subject_id, $combination_id, $subject_name, $connection) {
    // Get subject combination details
    $sql = "SELECT combination_code, combination_subjects FROM subject_combinations WHERE combination_id = ?";
    $stmt = $connection->prepare($sql);
    $stmt->bind_param("i", $combination_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $combo_data = $result->fetch_assoc();
    $stmt->close();
    
    if (!$combo_data) {
        return true; // Default to principal if no combination info
    }
    
    // Special handling for common UACE patterns
    $combination_code = strtoupper($combo_data['combination_code'] ?? '');
    
    // PEM/ICT combinations: PEM is principal, ICT is subsidiary
    if (stripos($combination_code, 'PEM') !== false && stripos($combination_code, 'ICT') !== false) {
        return (stripos($subject_name, 'MATHEMATICS') !== false || 
                stripos($subject_name, 'PHYSICS') !== false || 
                stripos($subject_name, 'ECONOMICS') !== false ||
                stripos($subject_name, 'PEM') !== false); // PEM components are principal
    }
    
    // ICT in combination is typically subsidiary
    if (stripos($subject_name, 'ICT') !== false || stripos($subject_name, 'COMPUTER') !== false) {
        return false; // ICT is subsidiary
    }
    
    // SUB MATH is typically subsidiary
    if (stripos($subject_name, 'SUB MATH') !== false || stripos($subject_name, 'SUBMATH') !== false) {
        return false; // Subsidiary Math is subsidiary
    }
    
    // General papers are subsidiary
    if (stripos($subject_name, 'GENERAL') !== false || stripos($subject_name, 'GENERAL PAPER') !== false) {
        return false; // General papers are subsidiary
    }
    
    // Parse combination subjects if available
    if (!empty($combo_data['combination_subjects'])) {
        $combo_subjects = explode(',', $combo_data['combination_subjects']);
        $combo_subjects = array_map('trim', $combo_subjects);
        
        // Find subject position in combination (first 2 are typically principal in 3-subject combos)
        $subject_position = array_search($subject_id, $combo_subjects);
        if ($subject_position !== false) {
            return $subject_position < 2; // First 2 subjects are principal
        }
    }
    
    return true; // Default to principal for other subjects
}

// Simplified version that determines Principal/Subsidiary based only on subject name
function isPrincipalSubjectByName($subject_name) {
    $subject_name = strtoupper(trim($subject_name ?? ''));
    
    // Always subsidiary subjects
    $subsidiary_subjects = [
        'GENERAL PAPER',
        'SUB MATH',
        'SUBMATH', 
        'SUBSIDIARY MATHEMATICS',
        'ICT',
        'COMPUTER',
        'COMPUTER STUDIES',
        'INFORMATION COMMUNICATION TECHNOLOGY'
    ];
    
    foreach ($subsidiary_subjects as $subsidiary) {
        if (strpos($subject_name, $subsidiary) !== false) {
            return false; // Subsidiary subject
        }
    }
    
    // Common Principal Subjects (for PEM/ICT combinations, PEM components are principal)
    $principal_patterns = [
        'MATHEMATICS', 'PHYSICS', 'CHEMISTRY', 'BIOLOGY', 
        'ECONOMICS', 'BUSINESS STUDIES', 'HISTORY', 'GEOGRAPHY',
        'LITERATURE', 'FINE ART', 'GENERAL PAPER'
    ];
    
    foreach ($principal_patterns as $pattern) {
        if (strpos($subject_name, $pattern) !== false) {
            return true; // Principal subject
        }
    }
    
    // Default to principal for other subjects
    return true;
}

function getGradePoints($grade) {
    // UACE Point System for A-Levels (Principal Subjects: A=6, B=5, C=4, D=3, E=2, O=1, F=0)
    // O-Level Point System (A+=5, A=5, B=4, C=3, D=2, E=1, F=0)
    $uace_points = [
        'A' => 6, 'B' => 5, 'C' => 4, 'D' => 3, 'E' => 2, 'O' => 1, 'F' => 0
    ];
    $olevel_points = [
        'A+' => 5, 'A' => 5, 'B' => 4, 'C' => 3, 'D' => 2, 'E' => 1, 'F' => 0
    ];
    
    // Check if this is a UACE grade (uppercase letters)
    if (isset($uace_points[$grade])) {
        error_log("UACE POINTS: Grade '{$grade}' = {$uace_points[$grade]} points");
        return $uace_points[$grade];
    }
    
    // Fallback to O-Level system
    $fallback_points = $olevel_points[$grade] ?? 0;
    error_log("FALLBACK POINTS: Grade '{$grade}' = {$fallback_points} points (O-Level system)");
    return $fallback_points;
}

// NEW: Function to populate examinations table based on student combinations
function populateExaminationsFromCombinations($connection, $student_id, $academic_year, $term, $exam_id, $class_school_id) {
    try {
        // Get student's combination information
        $sql_get_combination = "SELECT u.combination_id, sc.combination_code, sc.combination_name 
                               FROM users u 
                               LEFT JOIN subject_combinations sc ON u.combination_id = sc.combination_id 
                               WHERE u.id = ?";
        $stmt_combination = $connection->prepare($sql_get_combination);
        $stmt_combination->bind_param("i", $student_id);
        $stmt_combination->execute();
        $result_combination = $stmt_combination->get_result();
        $combination_data = $result_combination->fetch_assoc();
        $stmt_combination->close();

        if (!$combination_data || empty($combination_data['combination_id'])) {
            return false; // No combination assigned
        }

        // Get subjects for this combination
        $sql_subjects = "SELECT s.subject_id, s.subject_name, s.subject_code 
                        FROM subjects s 
                        JOIN combination_subjects cs ON s.subject_id = cs.subject_id 
                        WHERE cs.combination_id = ? AND s.school_id = ? 
                        ORDER BY s.subject_name";
        $stmt_subjects = $connection->prepare($sql_subjects);
        $stmt_subjects->bind_param("ii", $combination_data['combination_id'], $class_school_id);
        $stmt_subjects->execute();
        $result_subjects = $stmt_subjects->get_result();

        $exam_count = 0;
        while ($subject = $result_subjects->fetch_assoc()) {
            // Check if exam already exists for this subject
            $sql_check_exam = "SELECT exam_id FROM exam_subjects WHERE exam_id = ? AND subject_id = ?";
            $stmt_check = $connection->prepare($sql_check_exam);
            $stmt_check->bind_param("ii", $exam_id, $subject['subject_id']);
            $stmt_check->execute();
            $result_check = $stmt_check->get_result();
            
            if ($result_check->num_rows == 0) {
                // Insert new exam subject record
                $sql_insert_exam_subject = "INSERT INTO exam_subjects (exam_id, subject_id, created_at) 
                                          VALUES (?, ?, NOW())";
                $stmt_insert = $connection->prepare($sql_insert_exam_subject);
                $stmt_insert->bind_param("ii", $exam_id, $subject['subject_id']);
                $stmt_insert->execute();
                $stmt_insert->close();
                $exam_count++;
            }
            $stmt_check->close();
        }
        $stmt_subjects->close();

        return $exam_count > 0;
    } catch (Exception $e) {
        error_log("Error populating examinations from combinations: " . $e->getMessage());
        return false;
    }
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Enhanced Report Cards - <?php echo htmlspecialchars($class_name ?? ''); ?></title>
    <link rel="stylesheet" href="style.css">
    <link rel="icon" href="<?php echo htmlspecialchars($school['logo'] ?? 'images/logo.png'); ?>" type="image/png">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/qrcode-generator@1.4.4/qrcode.js"></script>
    <style>
        /* Enhanced Dashboard Container Structure */
        .dashboard-container {
            display: flex;
            min-height: 100vh;
            position: relative;
        }

        .main-content {
            flex: 1;
            margin-left: 250px;
            display: flex;
            flex-direction: column;
            min-height: 100vh;
            overflow: auto;
            transition: margin-left 0.3s ease;
            scroll-behavior: smooth;
        }

        .sidebar-collapsed .main-content {
            margin-left: 0;
        }

        /* Fixed Header */
        .header {
            position: sticky;
            top: 0;
            z-index: 999;
            background: white;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }

        .header-content {
            padding: 12px 20px;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .menu-toggle {
            background: none;
            border: none;
            font-size: 1.5em;
            cursor: pointer;
            color: #333;
            padding: 8px;
            border-radius: 4px;
            transition: background-color 0.2s ease;
        }

        .menu-toggle:hover {
            background-color: #f0f0f0;
        }

        .school-info {
            display: flex;
            align-items: center;
            gap: 12px;
            flex: 1;
        }

        .school-info img {
            width: 40px;
            height: 40px;
            border-radius: 8px;
            object-fit: contain;
        }

        .school-info h1 {
            margin: 0;
            font-size: 1.3em;
            font-weight: 600;
            color: #333;
        }

        .header-right {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        /* Language Selection Styles */
        .language-select {
            position: relative;
        }

        .language-select select {
            background: #fff;
            border: 1px solid #ddd;
            border-radius: 6px;
            padding: 6px 10px;
            font-size: 0.85em;
            color: #333;
            cursor: pointer;
            min-width: 120px;
            appearance: none;
            background-image: url('data:image/svg+xml;charset=US-ASCII,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 4 5"><path fill="%23666" d="M2 0L0 2h4zm0 5L0 3h4z"/></svg>');
            background-repeat: no-repeat;
            background-position: right 6px center;
            background-size: 10px;
            transition: all 0.2s ease;
        }

        .language-select select:hover {
            border-color: #007bff;
            box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.1);
        }

        .language-select select:focus {
            outline: none;
            border-color: #007bff;
            box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.1);
        }

        /* Search Bar Styles */
        .search-bar {
            position: relative;
            display: flex;
            align-items: center;
        }

        .search-bar i {
            position: absolute;
            left: 10px;
            color: #666;
            font-size: 0.9em;
        }

        .search-bar input {
            background: #fff;
            border: 1px solid #ddd;
            border-radius: 20px;
            padding: 8px 12px 8px 35px;
            font-size: 0.85em;
            color: #333;
            width: 200px;
            transition: all 0.2s ease;
        }

        .search-bar input:focus {
            outline: none;
            border-color: #007bff;
            box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.1);
            width: 250px;
        }

        /* Notifications Styles */
        .notifications {
            position: relative;
            cursor: pointer;
            padding: 8px;
            border-radius: 50%;
            transition: background-color 0.2s ease;
        }

        .notifications:hover {
            background-color: #f0f0f0;
        }

        .notifications i {
            font-size: 1.2em;
            color: #666;
        }

        .notifications .badge {
            position: absolute;
            top: 2px;
            right: 2px;
            background: #ff4757;
            color: white;
            border-radius: 50%;
            width: 18px;
            height: 18px;
            font-size: 0.7em;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
        }

        /* User Profile Styles */
        .user-profile {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 5px 10px;
            border-radius: 8px;
            transition: background-color 0.2s ease;
        }

        .user-profile:hover {
            background-color: #f0f0f0;
        }

        .user-profile img {
            width: 35px;
            height: 35px;
            border-radius: 50%;
            object-fit: cover;
        }

        .user-profile .user-name {
            font-size: 0.9em;
            font-weight: 600;
            color: #333;
        }

        .user-profile .user-email {
            font-size: 0.75em;
            color: #666;
        }

        /* Scrollable Content Area */
        .reports-content {
            flex: 1;
            overflow-y: auto;
            overflow-x: hidden;
            padding: 20px;
            background: #f5f5f5;
        }

        /* Scrollbar Styling */
        .reports-content::-webkit-scrollbar {
            width: 8px;
        }

        .reports-content::-webkit-scrollbar-track {
            background: #f1f1f1;
        }

        .reports-content::-webkit-scrollbar-thumb {
            background: #888;
            border-radius: 4px;
        }

        .reports-content::-webkit-scrollbar-thumb:hover {
            background: #555;
        }

        /* Fixed Sidebar */
        .sidebar {
            position: fixed;
            left: 0;
            top: 0;
            height: 100vh;
            width: 250px;
            overflow-y: auto;
            z-index: 1000;
            transition: transform 0.3s ease;
        }

        .sidebar.collapsed {
            transform: translateX(-250px);
        }

        /* Report Card Styles */
        .report-card { 
            background: white; 
            margin: 20px auto;
            page-break-after: always;
            position: relative;
            width: 210mm;
            height: 297mm;
            box-sizing: border-box;
            padding: 0;
            font-family: 'Arial', sans-serif;
            font-size: 11px;
            line-height: 1.3;
            border: 1px solid #e0e0e0;
            border-left: 20px solid;
            border-image: linear-gradient(to bottom, #28a745 0%, #28a745 5%, #4fc3f7 10%, #4fc3f7 100%) 1;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }

        /* Report Card Header */
        .report-card-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            padding: 15mm 15mm 8mm 15mm;
            border-bottom: 2px solid #4fc3f7;
        }

        .school-logo {
            width: 60px;
            height: 60px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #2c5aa0;
            font-weight: bold;
            font-size: 20px;
        }

        .school-logo img {
            width: 60px;
            height: 60px;
            object-fit: contain;
        }

        .school-details {
            text-align: right;
            color: black;
            font-weight: bold;
        }

        .school-name {
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 3px;
            color: black;
        }

        .school-address {
            font-size: 10px;
            line-height: 1.2;
            margin-bottom: 2px;
            font-weight: bold;
            color: black;
        }

        .school-contact {
            font-size: 9px;
            color: black;
            font-weight: bold;
        }

        /* Academic Report Button */
        .academic-report-button {
            text-align: center;
            padding: 15px 20px;
            margin: 10px 15mm;
            background: linear-gradient(135deg, #4fc3f7 0%, #007bff 0%);
            color: white;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(44, 90, 160, 0.3);
            font-size: 14px;
            font-weight: bold;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            transition: all 0.3s ease;
        }

        .academic-report-button:hover {
            background: linear-gradient(135deg, #1e3a72 0%, #0056b3 100%);
            box-shadow: 0 6px 18px rgba(44, 90, 160, 0.4);
            transform: translateY(-2px);
        }

        /* NEW: Enhanced Combination Information Styles */
        .enhanced-student-info {
            background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
            border: 1px solid #2196F3;
            border-radius: 8px;
            padding: 10px;
            margin: 10px 15mm;
            border-left: 4px solid #1976D2;
        }

        .enhanced-student-title {
            font-size: 11px;
            font-weight: bold;
            color: #1976D2;
            margin-bottom: 5px;
            text-transform: uppercase;
        }

        .enhanced-student-content {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 8px;
            font-size: 10px;
        }

        .student-info-field {
            display: flex;
            flex-direction: column;
        }

        .student-info-label {
            font-weight: bold;
            color: #2c5aa0;
            margin-bottom: 2px;
        }

        .student-info-value {
            color: #333;
        }

        .combination-info {
            background: #f8f9fb;
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 8px;
            margin: 5px 15mm;
            border-left: 4px solid #6f42c1;
        }

        .combination-title {
            font-size: 10px;
            font-weight: bold;
            color: #6f42c1;
            margin-bottom: 3px;
        }

        .combination-content {
            font-size: 9px;
            color: #333;
        }

        /* Performance Statistics */
        .senior-level-stats {
            display: flex;
            justify-content: space-around;
            margin: 10px 15mm;
            gap: 10px;
        }

        .stat-btn {
            background: linear-gradient(135deg, #6f42c1 0%, #5a32a3 100%);
            color: white;
            padding: 8px 12px;
            border-radius: 8px;
            text-align: center;
            flex: 1;
            border: none;
            font-size: 9px;
        }

        .stat-value {
            display: block;
            font-size: 14px;
            font-weight: bold;
            margin-bottom: 2px;
        }
        
        .stat-label {
            display: block;
            font-size: 9px;
            opacity: 0.9;
            line-height: 1.2;
        }
        
        .stat-btn small {
            display: block;
            margin-top: 2px;
            font-size: 8px;
            opacity: 0.7;
        }

        .stat-label {
            font-size: 8px;
            opacity: 0.9;
        }

        /* Student Section */
        .student-section {
            display: flex;
            padding: 8mm 15mm;
            gap: 20px;
            align-items: flex-start;
            border-left: 1px solid;
            border-image: linear-gradient(45deg, #007bff 0%, #28a745 50%, #007bff 100%) 1;
            background: linear-gradient(135deg, #e4ebf8ff 0%, #ffffff 100%);
        }

        .student-photo-column {
            flex: 0 0 80px;
        }

        .student-details {
            flex: 1;
            padding-top: 10px;
            font-weight: bold;
        }

        .student-photo {
            width: 80px;
            height: 100px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 10px;
            color: #666;
            background: #f8f9fb;
            border-radius: 8px;
            overflow: hidden;
        }

        .student-photo img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            border-radius: 6px;
        }

        .student-photo-placeholder {
            text-align: center;
            line-height: 1.2;
        }

        .student-info-vertical {
            display: flex;
            flex-direction: column;
            gap: 8px;
        }

        .student-info-item {
            font-size: 11px;
            color: #333;
        }

        .student-info-item strong {
            color: #2c5aa0;
            font-weight: bold;
        }

        .performance-graph {
            flex: 0 0 200px;
            background: #f8f9fb;
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 8px;
            height: 80px;
        }

        .chart-container {
            position: relative;
            height: 120px;
            margin: 5px 0;
        }

        /* Results Section */
        .results-section {
            margin: 0 15mm 10mm 15mm;
            border-left: 2px solid;
            border-image: #28a745 100%;
            background: none;
            padding: 10px;
            border-radius: 8px;
            font-weight: bold;
        }

        .results-title {
            background: #2c5aa0;
            color: white;
            padding: 8px 12px;
            margin: 0;
            font-size: 12px;
            font-weight: bold;
        }

        .results-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 9px;
            margin-bottom: 1mm;
            font-weight: bold;
        }

        .results-table th {
            background: none;
            color: #2c5aa0;
            padding: 8px;
            text-align: left;
            border: 1px solid #000;
            font-weight: bold;
        }

        .results-table td {
            padding: 6px 8px;
            border: 1px solid #000;
        }

        .results-table tr:nth-child(even) {
            background: none;
        }

        .results-table td[rowspan] {
            background-color: #f8f9fa;
            font-weight: bold;
            border-right: 2px solid #2c5aa0;
        }
        
        .subject-final-grade {
            background-color: #f8f9fa !important;
            border-top: 2px solid #007bff !important;
        }
        
        .subject-final-grade td {
            font-weight: bold;
            color: #495057;
        }
        
        .subject-paper {
            transition: background-color 0.2s ease;
        }

        .results-table td:nth-child(2) {
            font-style: italic;
            color: #495057;
        }

        .grade-badge {
            background: #28a745;
            color: white;
            padding: 2px 6px;
            border-radius: 10px;
            font-size: 8px;
            font-weight: bold;
        }

        /* Performance and Remarks */
        .performance-remarks-container {
            display: flex;
            gap: 10px;
            margin: 0 15mm 8mm 15mm;
            align-items: flex-start;
        }

        .performance-trends {
            flex: 0 0 300px;
            background: #f8f9fb;
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 10px;
            border-left: 4px solid;
            border-image: linear-gradient(45deg, #007bff 0%, #28a745 50%, #007bff 100%) 1;
        }

        .trends-title {
            font-size: 11px;
            font-weight: bold;
            color: #2c5aa0;
            margin-bottom: 8px;
        }

        .trends-chart {
            height: 60px;
            background: white;
            border: 1px solid #eee;
            border-radius: 4px;
            position: relative;
        }

        .remarks-section {
            flex: 1;
            display: grid;
            grid-template-columns: 1fr;
            gap: 0px;
        }

        .remark-box {
            background: none;
            border: none;
            border-radius: 0;
            padding: 5px;
        }

        .remark-title {
            font-size: 10px;
            font-weight: bold;
            color: #2c5aa0;
            margin-bottom: 0px;
        }

        .remark-content {
            font-size: 9px;
            min-height: 25px;
            line-height: 1.3;
        }

        /* Comments and Grade Descriptors for S1-S4 - Compact Version */
        .comments-grade-descriptors {
            width: 100%;
            display: flex;
            flex-direction: column;
            gap: 8px;
        }

        .comments-section {
            background: none;
            border-radius: 4px;
            overflow: hidden;
            box-shadow: 0 1px 2px rgba(0,0,0,0.1);
        }

        .comments-header {
            background: linear-gradient(135deg, #4fc3f7 0%, #29b6f6 100%);
            color: white;
            padding: 6px 12px;
            font-size: 9px;
            font-weight: bold;
            text-align: center;
        }

        .comments-content {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 8px;
            padding: 10px;
            background: white;
        }

        .comment-panel {
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 4px;
            padding: 8px;
        }

        .comment-title {
            font-size: 8px;
            font-weight: bold;
            color: #2c5aa0;
            margin-bottom: 4px;
        }

        .comment-text {
            font-size: 7px;
            line-height: 1.2;
            color: #495057;
            min-height: 20px;
            margin-bottom: 6px;
        }

        .signature-line {
            font-size: 6px;
            color: #6c757d;
            border-top: 1px solid #dee2e6;
            padding-top: 4px;
        }

        .grade-descriptors-section {
            background: white;
            border-radius: 4px;
            overflow: hidden;
            box-shadow: 0 1px 2px rgba(0,0,0,0.1);
        }

        .grade-descriptors-header {
            background: linear-gradient(135deg, #4fc3f7 0%, #29b6f6 100%);
            color: white;
            padding: 6px 12px;
            font-size: 9px;
            font-weight: bold;
            text-align: center;
        }

        .grade-descriptors-table {
            padding: 8px;
            background: white;
        }

        .grade-descriptors-table-inner th {
            font-size: 7px;
            font-weight: bold;
            padding: 4px 6px;
        }

        .grade-descriptors-table-inner td {
            font-size: 6px;
            line-height: 1.2;
            padding: 3px 6px;
        }

        /* Footer */
        .report-footer {
            position: absolute;
            bottom: 10mm;
            left: 15mm;
            right: 15mm;
            display: flex;
            justify-content: space-between;
            align-items: flex-end;
        }

        .school-motto-footer {
            background: linear-gradient(135deg, #007bff 0%, #28a745 100%);
            color: white;
            padding: 8px 15px;
            border-radius: 20px;
            font-size: 10px;
            font-weight: bold;
            text-align: center;
            border: none;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            max-width: 60%;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .school-motto-footer:hover {
            background: linear-gradient(135deg, #0056b3 0%, #1e7e34 100%);
            box-shadow: 0 4px 8px rgba(0,0,0,0.15);
            transform: translateY(-1px);
        }

        .qr-code {
            width: 50px;
            height: 50px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            font-size: 8px;
            color: #e47272ff;
            text-align: center;
        }
        
        .qr-code img {
            max-width: 45px;
            max-height: 45px;
            border-radius: 4px;
        }

        /* Subject and Paper Row Styling */
        .subject-main {
            background-color: #f8f9fb;
            font-weight: bold;
        }

        .subject-paper {
            background-color: #ffffff;
        }

        /* Watermark */
        .report-card-watermark {
            position: absolute;
            top: 0%;
            left: 0%;
            transform: translate(-50%, -50%);
            z-index: -1;
            opacity: 0.05;
            width: 300px;
            height: 300px;
            background-size: contain;
            background-repeat: no-repeat;
            background-position: center;
            pointer-events: none;
        }

        /* Print styles */
        @media print { 
            .back-link, .no-print, .school-header, .report-header, .report-info { 
                display: none !important; 
            }
            
            body { 
                background: white !important; 
                margin: 0 !important; 
                padding: 0 !important; 
                font-size: 12pt;
                line-height: 1.4;
            }
            
            .report-card {
                box-shadow: none !important; 
                page-break-after: always;
                page-break-inside: avoid;
                width: 210mm !important;
                height: 297mm !important;
                margin: 10mm !important;
                padding: 15mm !important;
                border: 2px solid #000 !important;
                background: white !important;
                font-family: Arial, sans-serif !important;
                position: relative;
            }
            
            .report-card:last-child {
                page-break-after: auto;
            }
            
            /* Print styles for report card content */
            .report-card * {
                color: #000 !important;
                background: white !important;
            }
            
            .report-card h1, .report-card h2, .report-card h3, .report-card h4 {
                color: #000 !important;
                margin: 0 0 10px 0 !important;
            }
            
            .report-card .student-info {
                border-bottom: 2px solid #000;
                padding-bottom: 10px;
                margin-bottom: 15px;
            }
            
            .report-card .grades-table {
                width: 100% !important;
                border-collapse: collapse !important;
                margin: 10px 0 !important;
                font-size: 10pt;
            }
            
            .report-card .grades-table th,
            .report-card .grades-table td {
                border: 1px solid #000 !important;
                padding: 5px !important;
                text-align: left !important;
            }
            
            .report-card .grades-table th {
                background-color: #f0f0f0 !important;
                font-weight: bold !important;
            }
            
            .report-card .performance-grid {
                display: grid !important;
                grid-template-columns: repeat(2, 1fr) !important;
                gap: 10px !important;
                margin: 15px 0 !important;
            }
            
            .report-card .performance-item {
                border: 1px solid #000 !important;
                padding: 8px !important;
                text-align: center !important;
                background: white !important;
            }
            
            .report-card .summary-section {
                margin-top: 20px !important;
                border: 1px solid #000 !important;
                padding: 10px !important;
            }
            
            .report-card .grade-legend {
                margin-top: 15px !important;
                font-size: 9pt !important;
            }
            
            .report-card .remarks-section {
                margin-top: 20px !important;
                border-top: 1px solid #000 !important;
                padding-top: 10px !important;
            }
            
            @page {
                size: A4;
                margin: 0;
            }
        }

        /* Mobile Responsive */
        @media (max-width: 768px) {
            .main-content {
                margin-left: 0;
            }
            .sidebar {
                transform: translateX(-250px);
            }
            .sidebar.collapsed {
                transform: translateX(0);
            }
            .reports-content {
                padding-bottom: 90px;
            }
        }

        body { 
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; 
            margin: 0;
            padding: 0;
            min-height: 100vh;
            background: #f5f5f5;
        }

        /* FORM-BASED REPORT CARD LAYOUT */
        .report-card-form {
            border: 2px solid #000;
            padding: 20px;
            margin: 20px 0;
            background: #fff;
            font-family: Arial, sans-serif;
        }

        .form-header {
            text-align: center;
            border-bottom: 2px solid #000;
            padding-bottom: 15px;
            margin-bottom: 20px;
        }

        .form-title {
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 10px;
        }

        .form-subtitle {
            font-size: 14px;
            margin-bottom: 5px;
        }

        .form-row {
            display: flex;
            margin-bottom: 10px;
            border-bottom: 1px solid #ddd;
            padding-bottom: 8px;
        }

        .form-label {
            font-weight: bold;
            width: 150px;
            border-right: 2px solid #000;
            padding-right: 15px;
        }

        .form-value {
            padding-left: 15px;
            flex: 1;
        }

        /* Form styles for report card information */
        .form-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 15px;
            margin: 20px 0;
        }

        .form-group {
            display: flex;
            flex-direction: column;
        }

        .form-group label {
            font-weight: bold;
            margin-bottom: 5px;
            color: #333;
        }

        .form-control {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
            font-family: Arial, sans-serif;
            background-color: #f9f9f9;
            transition: border-color 0.3s ease;
        }

        .form-control:focus {
            outline: none;
            border-color: #007bff;
            background-color: #fff;
            box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
        }

        .form-control[readonly] {
            background-color: #e9ecef;
            cursor: not-allowed;
        }

        .form-actions {
            margin-top: 20px;
            text-align: center;
            padding-top: 15px;
            border-top: 2px solid #ddd;
        }

        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 6px;
            font-size: 14px;
            font-weight: bold;
            cursor: pointer;
            margin: 0 5px;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-block;
        }

        .btn-primary {
            background-color: #007bff;
            color: white;
            box-shadow: 0 2px 4px rgba(0,123,255,0.2);
        }

        .btn-primary:hover {
            background-color: #0056b3;
            transform: translateY(-1px);
            box-shadow: 0 4px 8px rgba(0,123,255,0.3);
        }

        .btn-secondary {
            background-color: #6c757d;
            color: white;
            box-shadow: 0 2px 4px rgba(108,117,125,0.2);
        }

        .btn-secondary:hover {
            background-color: #545b62;
            transform: translateY(-1px);
            box-shadow: 0 4px 8px rgba(108,117,125,0.3);
        }

        .form-section {
            margin: 20px 0;
            border: 1px solid #000;
            padding: 15px;
        }

        .form-section-title {
            font-weight: bold;
            font-size: 16px;
            margin-bottom: 15px;
            text-align: center;
            background: #f0f0f0;
            padding: 8px;
            border-bottom: 1px solid #000;
        }

        .performance-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-bottom: 20px;
        }

        .performance-item {
            border: 1px solid #000;
            padding: 10px;
            text-align: center;
        }

        .performance-label {
            font-size: 12px;
            margin-bottom: 5px;
        }

        .performance-value {
            font-size: 16px;
            font-weight: bold;
        }

        .grades-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 15px;
        }

        .grades-table th,
        .grades-table td {
            border: 1px solid #000;
            padding: 8px;
            text-align: left;
        }

        .grades-table th {
            background: #f0f0f0;
            font-weight: bold;
            text-align: center;
        }

        .signature-section {
            margin-top: 30px;
            display: flex;
            justify-content: space-between;
        }

        .signature-box {
            border: 1px solid #000;
            width: 45%;
            padding: 20px;
            text-align: center;
        }
    </style>
</head>
<body>
    <div class="dashboard-container" id="dashboardContainer">
        <!-- Sidebar -->
        <aside class="sidebar" id="sidebar">
            <div class="logo">
                <img src="images/logo.png" alt="divine Logo">
               <br><H8> DIVINE REPORTS</H8></br>
            </div>
            <nav>
                <ul>
                    <li><a href="admin_dashboard.php" id="dashboardLink"><i class="fas fa-th-large"></i> Dashboard</a></li>
                    <li><a href="admin_calendar.php" id="calendarLink"><i class="far fa-calendar-alt"></i> Calendar</a></li>
                    <li><a href="admin_user_management.php" id="usersLink"><i class="fas fa-users-cog"></i> Users</a></li>
                    <li><a href="admin_students.php" id="studentsLink"><i class="fas fa-user-graduate"></i> Students</a></li>
                    <li><a href="admin_teachers.php" id="teachersLink"><i class="fas fa-chalkboard-teacher"></i> Teachers</a></li>
                    <li class="hide-on-mobile"><a href="admin_classes.php" id="classesLink"><i class="fas fa-chalkboard"></i> Classes</a></li>
                    <li class="hide-on-mobile"><a href="admin_subjects.php" id="subjectsLink"><i class="fas fa-book"></i> Subjects</a></li>
                    <li class="hide-on-mobile"><a href="admin_exams.php" id="examsLink"><i class="fas fa-file-alt"></i> Exams</a></li>
                    <li class="hide-on-mobile"><a href="admin_messages.php" id="messagesLink"><i class="fas fa-envelope"></i> Messages</a></li>
                    <li><a href="admin_reports_printouts.php" id="printoutsLink"><i class="fas fa-print"></i> Printouts</a></li>
                    <li class="hide-on-mobile"><a href="admin_system_settings.php" id="systemSettingsLink"><i class="fas fa-cog"></i> Settings</a></li>
                    <li class="hide-on-mobile"><a href="logout.php" class="logout-btn" id="logoutLink"><i class="fas fa-sign-out-alt"></i> Logout</a></li>
                </ul>
            </nav>
        </aside>

        <!-- Main Content Area -->
        <div class="main-content">
            <!-- Fixed Header -->
            <header class="header">
                <button class="menu-toggle" id="menuToggle">
                    <i class="fas fa-bars"></i>
                </button>
                <div class="school-info">
                    <img src="<?php echo htmlspecialchars($school['logo'] ?? 'images/logo.png'); ?>" alt="<?php echo htmlspecialchars($school['school_name'] ?? 'Divine Reports'); ?> Logo">
                    <h1><?php echo htmlspecialchars($school['school_name'] ?? 'Divine Reports'); ?></h1>
                </div>
                <div class="header-right">
                    <div class="language-select">
                        <select id="languageSelect" onchange="changeLanguage()">
                           <option value="en" <?php echo (($_SESSION['language'] ?? 'en') == 'en') ? 'selected' : ''; ?>>🇬🇧 English</option>
                           <option value="lg" <?php echo (($_SESSION['language'] ?? 'en') == 'lg') ? 'selected' : ''; ?>>🇺🇬 Luganda</option>
                           <option value="sw" <?php echo (($_SESSION['language'] ?? 'en') == 'sw') ? 'selected' : ''; ?>>🇹🇿 Kiswahili</option>
                        </select>
                    </div>
                    <div class="search-bar">
                        <i class="fas fa-search"></i>
                        <input type="text" placeholder="Search students/data" id="searchPlaceholder">
                    </div>
                    <div class="notifications">
                        <i class="fas fa-bell"></i>
                        <span class="badge">3</span>
                    </div>
                    <div class="user-profile">
                        <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==" alt="User Photo" class="rounded-circle" style="width: 40px; height: 40px;">
                        <div>
                            <div class="user-name"><?php echo htmlspecialchars($_SESSION['username'] ?? 'Admin'); ?></div>
                            <div class="user-email">Logged in as: <?php echo htmlspecialchars($_SESSION['role_name'] ?? 'Administrator'); ?></div>
                        </div>
                    </div>
                </div>
            </header>

            <!-- Scrollable Content -->
            <div class="reports-content">
                
                <div class="no-print">
                    <?php if (!$is_qr_access): ?>
                        
                    <?php endif; ?>
                </div>
        
                <div class="report-info">
                    <form id="reportCardInfoForm" class="readonly-form">
                        <h3> REPORT CARD INFORMATION</h3>
                        <div class="form-grid">
                            <div class="form-group">
                                <label for="academic_year"><strong>ACADEMIC YEAR:</strong></label>
                                <input type="text" id="academic_year" name="academic_year" value="<?php echo htmlspecialchars($academic_year ?? ''); ?>" class="form-control readonly" readonly>
                            </div>
                            <div class="form-group">
                                <label for="term"><strong>TERM:</strong></label>
                                <input type="text" id="term" name="term" value="<?php echo htmlspecialchars($term ?? ''); ?>" class="form-control readonly" readonly>
                            </div>
                            <div class="form-group">
                                <label for="class_name"><strong>CLASS:</strong></label>
                                <input type="text" id="class_name" name="class_name" value="<?php echo htmlspecialchars($class_name ?? ''); ?>" class="form-control readonly" readonly>
                            </div>
                            <div class="form-group">
                                <label for="level"><strong>LEVEL:</strong></label>
                                <input type="text" id="level" name="level" value="<?php echo ucfirst(str_replace('_', ' ', $class_level)); ?>" class="form-control readonly" readonly>
                            </div>
                            <div class="form-group">
                                <label for="total_students"><strong>TOTAL STUDENTS:</strong></label>
                                <input type="number" id="total_students" name="total_students" value="<?php echo count($students); ?>" class="form-control readonly" readonly>
                            </div>
                            <div class="form-group">
                                <label for="school_name"><strong>SCHOOL:</strong></label>
                                <input type="text" id="school_name" name="school_name" value="<?php echo htmlspecialchars($school['school_name'] ?? ''); ?>" class="form-control readonly" readonly>
                            </div>
                            <div class="form-group">
                                <label for="generated"><strong>GENERATED:</strong></label>
                                <input type="text" id="generated" name="generated" value="<?php echo date('Y-m-d H:i:s'); ?>" class="form-control readonly" readonly>
                            </div>
                            <div class="form-group">
                                <label for="exam_name"><strong>EXAM:</strong></label>
                                <input type="text" id="exam_name" name="exam_name" value="<?php echo htmlspecialchars($exam['exam_name'] ?? ''); ?>" class="form-control readonly" readonly>
                            </div>
                        </div>
                        <div class="form-actions">
                            <button type="button" onclick="printCurrentView()" class="btn btn-success">🖨️ Print Current View</button>
                        </div>
                    </form>
                </div>

                <?php if (!empty($students)): ?>
                    <?php foreach ($students as $student): ?>
                        <?php
                        // Populate examinations based on student combinations (only for A-Level students)
                        if ($class_level === 'senior_level' && !empty($student['combination_id'])) {
                            populateExaminationsFromCombinations($connection, $student['user_id'], $academic_year, $term, $exam_id, $class_school_id);
                        }

                        // Get student stream information
                        $student_stream_id = null;
                        $stream_name = '';
                        $sql_get_stream = "SELECT stream_id FROM users WHERE id = ?";
                        $stmt_stream = $connection->prepare($sql_get_stream);
                        $stmt_stream->bind_param("i", $student['user_id']);
                        $stmt_stream->execute();
                        $result_stream = $stmt_stream->get_result();
                        $stream_data = $result_stream->fetch_assoc();
                        $student_stream_id = $stream_data['stream_id'] ?? null;
                        $stmt_stream->close();

                        // Get stream name
                        if ($student_stream_id) {
                            $sql_stream_name = "SELECT stream_name FROM streams WHERE stream_id = ?";
                            $stmt_stream_name = $connection->prepare($sql_stream_name);
                            $stmt_stream_name->bind_param("i", $student_stream_id);
                            $stmt_stream_name->execute();
                            $result_stream_name = $stmt_stream_name->get_result();
                            $stream_name_data = $result_stream_name->fetch_assoc();
                            $stream_name = $stream_name_data['stream_name'] ?? '';
                            $stmt_stream_name->close();
                        }

                        // Initialize variables
                        $grades_data = [];
                        $total_subjects = 0;
                        $total_marks = 0;
                        $subjects_with_marks = 0;
                        $highest_mark = 0;
                        $lowest_mark = 100;
                        $total_points = 0;
                        $points_calculated = 0;
                        $grades_by_subject = [];
                        
                        // Reset tracking variables for debugging
                        $point_calculation_log = [];

                        try {
                            // Get subjects for this student based on their level and combination
                            if ($class_level === 'senior_level' && !empty($student['combination_id'])) {
                                // For A-Level students with combinations, use combination_subjects table
                                $sql_subjects = "SELECT DISTINCT s.subject_id, s.subject_name, s.subject_code
                                               FROM subjects s
                                               JOIN combination_subjects cs ON s.subject_id = cs.subject_id
                                               WHERE s.school_id = ? AND cs.combination_id = ?
                                               ORDER BY s.subject_name";
                                $stmt_subjects = $connection->prepare($sql_subjects);
                                $stmt_subjects->bind_param("ii", $class_school_id, $student['combination_id']);
                            } else {
                                // For S1-S2 (lower_level) and S3-S4 (senior_olevel) students, get subjects directly from subjects table
                                // with appropriate level filtering
                                if ($class_level === 'lower_level') {
                                    // S1-S2 students: get subjects applicable to S1 or S2 levels
                                    $sql_subjects = "SELECT DISTINCT s.subject_id, s.subject_name, s.subject_code
                                                   FROM subjects s
                                                   WHERE s.school_id = ?
                                                   AND (s.applicable_levels LIKE '%S1%' OR s.applicable_levels LIKE '%S2%' OR s.applicable_levels LIKE '%Lower%')
                                                   ORDER BY s.subject_name";
                                } elseif ($class_level === 'senior_olevel') {
                                    // S3-S4 students: get subjects applicable to S3 or S4 levels  
                                    $sql_subjects = "SELECT DISTINCT s.subject_id, s.subject_name, s.subject_code
                                                   FROM subjects s
                                                   WHERE s.school_id = ?
                                                   AND (s.applicable_levels LIKE '%S3%' OR s.applicable_levels LIKE '%S4%' OR s.applicable_levels LIKE '%Senior%')
                                                   ORDER BY s.subject_name";
                                } else {
                                    // Fallback: get all subjects for unknown class levels
                                    $sql_subjects = "SELECT DISTINCT s.subject_id, s.subject_name, s.subject_code
                                                   FROM subjects s
                                                   WHERE s.school_id = ?
                                                   ORDER BY s.subject_name";
                                }
                                
                                $stmt_subjects = $connection->prepare($sql_subjects);
                                $stmt_subjects->bind_param("i", $class_school_id);
                            }
                            $stmt_subjects->execute();
                            $result_subjects = $stmt_subjects->get_result();

                            // Use a more robust approach: collect all subjects first, then deduplicate
                            $all_subjects = [];
                            while ($subject = $result_subjects->fetch_assoc()) {
                                $all_subjects[] = $subject;
                            }
                            $stmt_subjects->close();
                            
                            // Deduplicate by subject_id before processing
                            $seen_ids = [];
                            $unique_subjects = [];
                            foreach ($all_subjects as $subject) {
                                if (!in_array($subject['subject_id'], $seen_ids)) {
                                    $seen_ids[] = $subject['subject_id'];
                                    $unique_subjects[] = $subject;
                                } else {
                                    error_log("DUPLICATE REMOVED: {$subject['subject_name']} (ID: {$subject['subject_id']})");
                                }
                            }
                            
                            // Now process unique subjects
                            foreach ($unique_subjects as $subject) {
                                error_log("PROCESSING SUBJECT: {$subject['subject_name']} (ID: {$subject['subject_id']}) for student {$student['user_id']}");
                                
                                // Test if debugging is working
                                error_log("*** DEBUG TEST: This is a test message - debugging is working ***");
                                error_log("*** DEBUG: Class ID = {$class_id}, Academic Year = {$academic_year}, Term = {$term} ***");
                                
                                $mark = null;
                                $paper_marks = [];
                                
                                // Check if this subject has papers
                                $has_papers_query = "SELECT COUNT(*) as paper_count FROM subject_papers WHERE subject_id = ? AND school_id = ?";
                                $stmt_paper_check = $connection->prepare($has_papers_query);
                                $stmt_paper_check->bind_param("ii", $subject['subject_id'], $class_school_id);
                                $stmt_paper_check->execute();
                                $paper_count_result = $stmt_paper_check->get_result();
                                $paper_count_data = $paper_count_result->fetch_assoc();
                                $has_papers = ($paper_count_data['paper_count'] > 0);
                                $stmt_paper_check->close();
                                
                                if ($has_papers) {
                                    // Get individual paper marks for this subject
                                    $sql_paper_marks = "SELECT m.paper_id, sp.paper_name, m.mark
                                                       FROM marks m
                                                       JOIN subject_papers sp ON m.paper_id = sp.paper_id
                                                       WHERE m.student_id = ? AND m.subject_id = ? AND m.exam_id = ?
                                                       ORDER BY sp.paper_name";
                                    $stmt_paper_marks = $connection->prepare($sql_paper_marks);
                                    $stmt_paper_marks->bind_param("iii", $student['user_id'], $subject['subject_id'], $exam_id);
                                    $stmt_paper_marks->execute();
                                    $result_paper_marks = $stmt_paper_marks->get_result();
                                    
                                    while ($paper_mark_data = $result_paper_marks->fetch_assoc()) {
                                        $paper_marks[$paper_mark_data['paper_id']] = [
                                            'paper_name' => $paper_mark_data['paper_name'],
                                            'mark' => $paper_mark_data['mark']
                                        ];
                                    }
                                    $stmt_paper_marks->close();
                                    
                                    // Calculate total mark from paper marks (average if multiple papers)
                                    if (!empty($paper_marks)) {
                                        $total = 0;
                                        $count = 0;
                                        foreach ($paper_marks as $paper_data) {
                                            if ($paper_data['mark'] !== null) {
                                                $total += $paper_data['mark'];
                                                $count++;
                                            }
                                        }
                                        $mark = ($count > 0) ? round($total / $count, 2) : null;
                                    }
                                } else {
                                    // Get regular subject mark (no papers)
                                    $sql_marks = "SELECT m.mark
                                                 FROM marks m
                                                 WHERE m.student_id = ? AND m.subject_id = ? AND m.exam_id = ?
                                                 LIMIT 1";
                                    $stmt_marks = $connection->prepare($sql_marks);
                                    $stmt_marks->bind_param("iii", $student['user_id'], $subject['subject_id'], $exam_id);
                                    $stmt_marks->execute();
                                    $result_marks = $stmt_marks->get_result();
                                    $mark_data = $result_marks->fetch_assoc();
                                    $stmt_marks->close();
                                    $mark = $mark_data['mark'] ?? null;
                                }

                                // Get assigned teacher from class_subject_teachers table
                                $teacher_name = 'Not Assigned';
                                $teacher_user_id = 0;
                                
                                // Debug teacher query parameters
                                error_log("*** TEACHER QUERY ATTEMPT: Class={$class_id}, Subject={$subject['subject_id']}, Year={$academic_year}, Term={$term} ***");
                                error_log("*** TEACHER QUERY DEBUG: About to execute teacher lookup query ***");
                                
                                $sql_teacher = "SELECT u.username as teacher_name, cst.teacher_user_id
                                               FROM class_subject_teachers cst
                                               JOIN users u ON cst.teacher_user_id = u.id
                                               WHERE cst.class_id = ? AND cst.subject_id = ? 
                                               AND cst.academic_year = ? AND cst.term = ?
                                               LIMIT 1";
                                $stmt_teacher = $connection->prepare($sql_teacher);
                                
                                // Use proper parameter types - ensure class_id and subject_id are integers
                                $class_id_int = (int)$class_id;
                                $subject_id_int = (int)$subject['subject_id'];
                                $academic_year_int = (int)$academic_year;
                                
                                $stmt_teacher->bind_param("iiis", $class_id_int, $subject_id_int, $academic_year_int, $term);
                                
                                if (!$stmt_teacher->execute()) {
                                    error_log("TEACHER QUERY ERROR: " . $stmt_teacher->error);
                                    $stmt_teacher->close();
                                } else {
                                    $result_teacher = $stmt_teacher->get_result();
                                    $teacher_data = $result_teacher->fetch_assoc();
                                    $stmt_teacher->close();

                                    if ($teacher_data) {
                                        $teacher_name = $teacher_data['teacher_name'];
                                        $teacher_user_id = $teacher_data['teacher_user_id'];
                                        error_log("TEACHER FOUND: Subject {$subject['subject_id']} - {$teacher_name} ({$teacher_user_id})");
                                    } else {
                                        error_log("NO TEACHER: Subject {$subject['subject_id']} - Class {$class_id}, Year {$academic_year}, Term {$term}");
                                    }
                                }

                                $teacher_info = ['teacher_user_id' => $teacher_user_id];

                                // Get subject data with papers
                                $subject_data = [
                                    'subject_id' => $subject['subject_id'],
                                    'subject_name' => $subject['subject_name'],
                                    'subject_code' => $subject['subject_code'],
                                    'papers' => [],
                                    'paper_marks' => []
                                ];

                                if ($class_level === 'senior_level') {
                                    $subject_data['papers'] = getSubjectPapers($subject['subject_id'], $class_school_id, $connection);
                                    // Add paper marks to subject data for display
                                    $subject_data['paper_marks'] = $paper_marks;
                                }

                                $subject_data['mark'] = $mark;
                                $subject_data['teacher_name'] = $teacher_name;
                                $subject_data['teacher_user_id'] = $teacher_info['teacher_user_id'];

                                // Calculate UACE subject grade for senior level multi-paper subjects
                                if ($class_level === 'senior_level' && $has_papers && !empty($paper_marks) && $mark !== null) {
                                    $paper_grades = [];
                                    foreach ($paper_marks as $paper_data) {
                                        if ($paper_data['mark'] !== null) {
                                            $paper_grade_info = getGradeFromScale($paper_data['mark'], $subject['subject_id'], $class_id, $academic_year, $term, $class_school_id, $connection, $grading_scale_name, $class_level);
                                            $paper_grades[] = $paper_grade_info['display_grade'];
                                        }
                                    }
                                    
                                    // TEST: Verify gradeToNumber function
                                    error_log("GRADE TO NUMBER TEST:");
                                    foreach ($paper_grades as $test_grade) {
                                        $numeric = gradeToNumber($test_grade);
                                        error_log("  '$test_grade' -> $numeric");
                                    }
                                    
                                    if (!empty($paper_grades)) {
                                        // DEBUG: Log the grades being passed to UACE calculation
                                        error_log("UACE DEBUG: Subject {$subject['subject_name']} papers: " . json_encode($paper_grades));
                                        
                                        // Calculate subject grade from papers
                                        $subject_grade = calculateUACESubjectGrade($paper_grades, count($paper_grades));
                                        error_log("UACE RESULT: Subject {$subject['subject_name']} final grade: " . json_encode($subject_grade));
                                        
                                        $subject_data['subject_grade'] = $subject_grade;
                                    }
                                } elseif (($class_level === 'senior_level' || $class_level === 'senior_olevel') && !$has_papers && $mark !== null) {
                                    // Single paper subject - use individual grade
                                    $grade_info = getGradeFromScale($mark, $subject['subject_id'], $class_id, $academic_year, $term, $class_school_id, $connection, $grading_scale_name, $class_level);
                                    $subject_data['subject_grade'] = [
                                        'grade' => $grade_info['display_grade'],
                                        'grade_letter' => $grade_info['grade_letter'],
                                        'points' => getGradePoints($grade_info['grade_letter']),
                                        'classification' => ($grade_info['grade_letter'] == 'O') ? 'Subsidiary Pass (O)' : 'Fail (F)'
                                    ];
                                }

                                $grades_data[] = $subject_data;
                                $total_subjects++;

                                if ($mark !== null) {
                                    // Subject has marks - will be included in calculations
                                    $total_marks += $mark;
                                    $subjects_with_marks++;
                                    $highest_mark = max($highest_mark, $mark);
                                    if ($lowest_mark == 100) {
                                        $lowest_mark = $mark;
                                    } else {
                                        $lowest_mark = min($lowest_mark, $mark);
                                    }
                                    // Store grade data
                                    $grade_data_entry = [
                                        'subject' => $subject_data['subject_name'],
                                        'mark' => $mark
                                    ];

                                    if ($class_level === 'senior_level' || $class_level === 'senior_olevel') {
                                        if ($has_papers && !empty($paper_marks)) {
                                            // Multi-paper subject - calculate UACE subject grade
                                            $paper_grades = [];
                                            foreach ($paper_marks as $paper_data) {
                                                if ($paper_data['mark'] !== null) {
                                                    $paper_grade_info = getGradeFromScale($paper_data['mark'], $subject['subject_id'], $class_id, $academic_year, $term, $class_school_id, $connection, $grading_scale_name, $class_level);
                                                    $paper_grades[] = $paper_grade_info['display_grade'];
                                                }
                                            }
                                            
                                            if (!empty($paper_grades)) {
                                                // Calculate subject grade from papers
                                                $subject_grade = calculateUACESubjectGrade($paper_grades, count($paper_grades));
                                                $grade_data_entry['subject_grade'] = $subject_grade;
                                                $grade_data_entry['subject_papers'] = $paper_marks;
                                                
                                                // SAFETY CHECK: Verify subject grade is valid before adding points
                                                if (!empty($subject_grade['grade_letter']) && $subject_grade['grade_letter'] !== 'F') {
                                                    $grade_points = getUACEPoints($subject_grade['grade_letter'], $subject_grade['grade'], count($paper_grades));
                                                    
                                                    // ADDITIONAL VALIDATION: Ensure points calculation succeeded
                                                    if ($grade_points !== null && $grade_points >= 0) {
                                                        $total_points += $grade_points;
                                                        $points_calculated++;
                                                        
                                                        // Track point calculation
                                                        $calculation_entry = [
                                                            'type' => 'principal',
                                                            'subject' => $subject['subject_name'],
                                                            'grade' => $subject_grade['grade_letter'],
                                                            'points' => $grade_points,
                                                            'total_after' => $total_points,
                                                            'papers' => count($paper_grades)
                                                        ];
                                                        $point_calculation_log[] = $calculation_entry;
                                                        
                                                        // Debug logging for principal subjects
                                                        error_log("STUDENT {$student['user_id']} - PRINCIPAL: {$subject['subject_name']} - Grade: {$subject_grade['grade_letter']} - Points: {$grade_points} - Running Total: {$total_points}");
                                                    } else {
                                                        error_log("STUDENT {$student['user_id']} - PRINCIPAL: {$subject['subject_name']} - INVALID POINTS: {$grade_points} (skipping)");
                                                    }
                                                } else {
                                                    error_log("STUDENT {$student['user_id']} - PRINCIPAL: {$subject['subject_name']} - F GRADE OR INVALID: {$subject_grade['grade_letter']} (not counting points)");
                                                }
                                            }
                                        } else {
                                            // Single paper subject
                                            $grade_info = getGradeFromScale($mark, $subject['subject_id'], $class_id, $academic_year, $term, $class_school_id, $connection, $grading_scale_name, $class_level);
                                            $grade_data_entry['subject_grade'] = [
                                                'grade' => $grade_info['display_grade'],
                                                'grade_letter' => $grade_info['grade_letter'],
                                                'points' => getGradePoints($grade_info['grade_letter']),
                                                'classification' => ($grade_info['grade_letter'] == 'O') ? 'Subsidiary Pass (O)' : 'Fail (F)'
                                            ];
                                            
                                            // SAFETY CHECK: Verify grade_info is valid before adding points
                                            if (!empty($grade_info['grade_letter']) && $grade_info['grade_letter'] !== 'F') {
                                                $grade_points = getGradePoints($grade_info['grade_letter']);
                                                
                                                // ADDITIONAL VALIDATION: Ensure points calculation succeeded
                                                if ($grade_points !== null && $grade_points >= 0) {
                                                    $total_points += $grade_points;
                                                    $points_calculated++;
                                                    
                                                    // Track point calculation
                                                    $calculation_entry = [
                                                        'type' => 'single',
                                                        'subject' => $subject['subject_name'],
                                                        'grade' => $grade_info['grade_letter'],
                                                        'points' => $grade_points,
                                                        'total_after' => $total_points,
                                                        'mark' => $mark
                                                    ];
                                                    $point_calculation_log[] = $calculation_entry;
                                                    
                                                    // Debug logging for single paper subjects
                                                    error_log("STUDENT {$student['user_id']} - SINGLE PAPER: {$subject['subject_name']} - Grade: {$grade_info['grade_letter']} - Points: {$grade_points} - Running Total: {$total_points}");
                                                } else {
                                                    error_log("STUDENT {$student['user_id']} - SINGLE PAPER: {$subject['subject_name']} - INVALID POINTS: {$grade_points} (skipping)");
                                                }
                                            } else {
                                                error_log("STUDENT {$student['user_id']} - SINGLE PAPER: {$subject['subject_name']} - F GRADE OR INVALID: {$grade_info['grade_letter']} (not counting points)");
                                            }
                                            
                                            // Debug logging for single paper subjects
                                            error_log("STUDENT {$student['user_id']} - SINGLE PAPER: {$subject['subject_name']} - Grade: {$grade_info['grade_letter']} - Points: {$grade_points} - Running Total: {$total_points}");
                                        }
                                    }

                                    $grades_by_subject[] = $grade_data_entry;
                                }
                            }
                            
                            error_log("Student {$student['user_id']}: Retrieved " . count($all_subjects) . " total, " . count($unique_subjects) . " unique subjects");
                            
                        } catch (Exception $e) {
                            error_log("Error fetching subject data: " . $e->getMessage());
                            
                            // FALLBACK: Try to get subjects directly without complex joins (only if no subjects loaded)
                            if (empty($grades_data)) {
                                try {
                                    if ($class_level === 'senior_level' && !empty($student['combination_id'])) {
                                        // Get combination subjects directly with deduplication
                                        $sql_fallback = "SELECT DISTINCT s.subject_id, s.subject_name, s.subject_code 
                                                       FROM combination_subjects cs
                                                       JOIN subjects s ON cs.subject_id = s.subject_id
                                                       WHERE cs.combination_id = ?
                                                       ORDER BY s.subject_name";
                                        $stmt_fallback = $connection->prepare($sql_fallback);
                                        $stmt_fallback->bind_param("i", $student['combination_id']);
                                    } else {
                                        // For S1-S2 (lower_level) and S3-S4 (senior_olevel) students, get subjects with level filtering
                                        if ($class_level === 'lower_level') {
                                            // S1-S2 students: get subjects applicable to S1 or S2 levels
                                            $sql_fallback = "SELECT DISTINCT subject_id, subject_name, subject_code 
                                                           FROM subjects 
                                                           WHERE school_id = ?
                                                           AND (applicable_levels LIKE '%S1%' OR applicable_levels LIKE '%S2%' OR applicable_levels LIKE '%Lower%')
                                                           ORDER BY subject_name";
                                        } elseif ($class_level === 'senior_olevel') {
                                            // S3-S4 students: get subjects applicable to S3 or S4 levels  
                                            $sql_fallback = "SELECT DISTINCT subject_id, subject_name, subject_code 
                                                           FROM subjects 
                                                           WHERE school_id = ?
                                                           AND (applicable_levels LIKE '%S3%' OR applicable_levels LIKE '%S4%' OR applicable_levels LIKE '%Senior%')
                                                           ORDER BY subject_name";
                                        } else {
                                            // Fallback for unknown class levels
                                            $sql_fallback = "SELECT DISTINCT subject_id, subject_name, subject_code FROM subjects WHERE school_id = ? ORDER BY subject_name";
                                        }
                                        $stmt_fallback = $connection->prepare($sql_fallback);
                                        $stmt_fallback->bind_param("i", $class_school_id);
                                    }
                                    
                                    $stmt_fallback->execute();
                                    $result_fallback = $stmt_fallback->get_result();
                                    
                                    // Deduplicate fallback results too
                                    $fallback_subjects = [];
                                    while ($subject = $result_fallback->fetch_assoc()) {
                                        $fallback_subjects[] = $subject;
                                    }
                                    $stmt_fallback->close();
                                    
                                    // Deduplicate fallback
                                    $fallback_seen_ids = [];
                                    $fallback_unique = [];
                                    foreach ($fallback_subjects as $subject) {
                                        if (!in_array($subject['subject_id'], $fallback_seen_ids)) {
                                            $fallback_seen_ids[] = $subject['subject_id'];
                                            $fallback_unique[] = $subject;
                                        } else {
                                            error_log("FALLBACK DUPLICATE REMOVED: {$subject['subject_name']} (ID: {$subject['subject_id']})");
                                        }
                                    }
                                    
                                    foreach ($fallback_unique as $subject) {
                                        // Add subject with no marks
                                        // Get assigned teacher from class_subject_teachers table (fallback)
                                        $teacher_name = 'Not Assigned';
                                        $teacher_user_id = 0;
                                        
                                        try {
                                            // Debug teacher query parameters for fallback
                                            error_log("TEACHER QUERY DEBUG (FALLBACK): Class={$class_id} (type:" . gettype($class_id) . "), Subject={$subject['subject_id']} (type:" . gettype($subject['subject_id']) . "), Year={$academic_year} (type:" . gettype($academic_year) . "), Term={$term} (type:" . gettype($term) . ")");
                                            
                                            $sql_teacher_fallback = "SELECT u.username as teacher_name, cst.teacher_user_id
                                                                   FROM class_subject_teachers cst
                                                                   JOIN users u ON cst.teacher_user_id = u.id
                                                                   WHERE cst.class_id = ? AND cst.subject_id = ? 
                                                                   AND cst.academic_year = ? AND cst.term = ?
                                                                   LIMIT 1";
                                            $stmt_teacher_fallback = $connection->prepare($sql_teacher_fallback);
                                            
                                            // Use proper parameter types - ensure class_id and subject_id are integers
                                            $class_id_int = (int)$class_id;
                                            $subject_id_int = (int)$subject['subject_id'];
                                            $academic_year_int = (int)$academic_year;
                                            
                                            $stmt_teacher_fallback->bind_param("iiis", $class_id_int, $subject_id_int, $academic_year_int, $term);
                                            
                                            if (!$stmt_teacher_fallback->execute()) {
                                                error_log("TEACHER QUERY ERROR (FALLBACK): " . $stmt_teacher_fallback->error);
                                                $stmt_teacher_fallback->close();
                                            } else {
                                                $result_teacher_fallback = $stmt_teacher_fallback->get_result();
                                                $teacher_data_fallback = $result_teacher_fallback->fetch_assoc();
                                                $stmt_teacher_fallback->close();

                                                if ($teacher_data_fallback) {
                                                    $teacher_name = $teacher_data_fallback['teacher_name'];
                                                    $teacher_user_id = $teacher_data_fallback['teacher_user_id'];
                                                    error_log("TEACHER FOUND (FALLBACK): Subject {$subject['subject_id']} - {$teacher_name} ({$teacher_user_id})");
                                                } else {
                                                    error_log("NO TEACHER (FALLBACK): Subject {$subject['subject_id']} - Class {$class_id}, Year {$academic_year}, Term {$term}");
                                                }
                                            }
                                        } catch (Exception $e) {
                                            error_log("Teacher lookup failed (fallback): " . $e->getMessage());
                                        }

                                        $subject_data = [
                                            'subject_id' => $subject['subject_id'],
                                            'subject_name' => $subject['subject_name'],
                                            'subject_code' => $subject['subject_code'],
                                            'papers' => [],
                                            'mark' => null,
                                            'teacher_name' => $teacher_name,
                                            'teacher_user_id' => $teacher_user_id
                                        ];
                                        
                                        // Try to get papers for senior level students in fallback as well
                                        if ($class_level === 'senior_level') {
                                            $subject_data['papers'] = getSubjectPapers($subject['subject_id'], $class_school_id, $connection);
                                            // Add empty paper_marks for fallback subjects
                                            $subject_data['paper_marks'] = [];
                                        }
                                        
                                        $grades_data[] = $subject_data;
                                        $total_subjects++;
                                    }
                                    error_log("Student {$student['user_id']}: Fallback loaded " . count($fallback_unique) . " unique subjects");
                                    
                                } catch (Exception $e2) {
                                    error_log("Fallback also failed: " . $e2->getMessage());
                                }
                            }
                        }

                        // Final safety check - remove any remaining duplicates
                        $final_grades = [];
                        $final_seen = [];
                        foreach ($grades_data as $subject) {
                            if (!in_array($subject['subject_id'], $final_seen)) {
                                $final_seen[] = $subject['subject_id'];
                                $final_grades[] = $subject;
                            } else {
                                error_log("FINAL CLEANUP: Removed duplicate {$subject['subject_name']} (ID: {$subject['subject_id']})");
                            }
                        }
                        $grades_data = $final_grades;

                        $average_mark = $subjects_with_marks > 0 ? round($total_marks / $subjects_with_marks, 1) : 0;
                        $average_points = $points_calculated > 0 && ($class_level === 'senior_level' || $class_level === 'senior_olevel') ? round($total_points / $points_calculated, 2) : 0;

                        // Calculate rankings (only for senior level students)
                        $stream_rank = '--';
                        $overall_rank = '--';
                        
                        if ($class_level === 'senior_level') {
                            // Try main stream rank calculation
                            try {
                                $stream_rank = calculateStreamRank($student['user_id'], $class_id, $connection);
                                
                                // If main calculation returned dash, try fallback
                                if ($stream_rank === '--' && function_exists('getStreamRankFallback')) {
                                    error_log("STUDENT {$student['user_id']} - Main stream rank failed, trying fallback");
                                    $stream_rank = getStreamRankFallback($student['user_id'], $class_id, $connection);
                                    if ($stream_rank !== '--') {
                                        error_log("STUDENT {$student['user_id']} - Stream rank fallback successful: {$stream_rank}");
                                    }
                                }
                            } catch (Exception $e) {
                                error_log("STUDENT {$student['user_id']} - Stream rank calculation failed: " . $e->getMessage());
                                // Try fallback on error
                                if (function_exists('getStreamRankFallback')) {
                                    try {
                                        $stream_rank = getStreamRankFallback($student['user_id'], $class_id, $connection);
                                        if ($stream_rank !== '--') {
                                            error_log("STUDENT {$student['user_id']} - Stream rank fallback successful: {$stream_rank}");
                                        }
                                    } catch (Exception $e2) {
                                        error_log("STUDENT {$student['user_id']} - Stream rank fallback also failed: " . $e2->getMessage());
                                        $stream_rank = '--';
                                    }
                                } else {
                                    $stream_rank = '--';
                                }
                            }
                            
                            // Try main overall rank calculation
                            try {
                                $student_class_level = $student['class_level'] ?? '';
                                $overall_rank = calculateOverallRank($student['user_id'], $student_class_level, $connection);
                                
                                // If main calculation returned dash, try fallback
                                if ($overall_rank === '--' && function_exists('getOverallRankFallback')) {
                                    error_log("STUDENT {$student['user_id']} - Main overall rank failed, trying fallback");
                                    $overall_rank = getOverallRankFallback($student['user_id'], $student_class_level, $connection);
                                    if ($overall_rank !== '--') {
                                        error_log("STUDENT {$student['user_id']} - Overall rank fallback successful: {$overall_rank}");
                                    }
                                }
                            } catch (Exception $e) {
                                error_log("STUDENT {$student['user_id']} - Overall rank calculation failed: " . $e->getMessage());
                                // Try fallback on error
                                if (function_exists('getOverallRankFallback')) {
                                    try {
                                        $overall_rank = getOverallRankFallback($student['user_id'], $student['class_level'], $connection);
                                        if ($overall_rank !== '--') {
                                            error_log("STUDENT {$student['user_id']} - Overall rank fallback successful: {$overall_rank}");
                                        }
                                    } catch (Exception $e2) {
                                        error_log("STUDENT {$student['user_id']} - Overall rank fallback also failed: " . $e2->getMessage());
                                        $overall_rank = '--';
                                    }
                                } else {
                                    $overall_rank = '--';
                                }
                            }
                            
                            // Final rank logging
                            error_log("STUDENT {$student['user_id']} - FINAL RANKS: Stream: {$stream_rank}, Overall: {$overall_rank}");
                        }

                        // Final debug logging for total points calculation
                        error_log("STUDENT {$student['user_id']} - FINAL TOTAL POINTS: {$total_points} calculated from {$points_calculated} subjects. Average Points: {$average_points}");
                        error_log("STUDENT {$student['user_id']} - MARK VALIDATION: {$subjects_with_marks} subjects with marks out of {$total_subjects} total subjects");
                        
                        // Log detailed point calculation breakdown
                        if (!empty($point_calculation_log)) {
                            error_log("=== DETAILED POINT CALCULATION LOG ===");
                            foreach ($point_calculation_log as $index => $entry) {
                                error_log("Step " . ($index + 1) . ": {$entry['type']} - {$entry['subject']} - Grade {$entry['grade']} = {$entry['points']} points - Total: {$entry['total_after']}");
                            }
                            error_log("=== END CALCULATION LOG ===");
                        } else {
                            error_log("STUDENT {$student['user_id']} - NO VALID SUBJECTS FOUND FOR POINT CALCULATION");
                        }

                        // Prepare chart data for this student
                        $chart_data = [
                            'subjects' => [],
                            'marks' => [],
                            'historical_data' => []
                        ];

                        // Get subject names and marks for overview chart
                        foreach ($grades_data as $subject) {
                            if ($subject['mark'] !== null) {
                                $chart_data['subjects'][] = $subject['subject_name'];
                                $chart_data['marks'][] = (float)$subject['mark'];
                                error_log("Student {$student['user_id']}: CHART - Subject: {$subject['subject_name']}, Mark: {$subject['mark']}");
                            }
                        }

                        error_log("Student {$student['user_id']}: Chart overview data - " . count($chart_data['subjects']) . " subjects, " . count($chart_data['marks']) . " marks");

                        // Get historical performance data for trends chart
                        $historical_data = getStudentHistoricalPerformance($student['user_id'], $connection, $class_school_id, $class_id);
                        $chart_data['historical_data'] = $historical_data;

                        error_log("Student {$student['user_id']}: Historical data - " . count($historical_data['labels']) . " labels, " . count($historical_data['values']) . " values");

                        // Store chart data for this student
                        $all_chart_data[$student['user_id']] = $chart_data;
                        
                        // Enhanced debug logging for chart data
                        error_log("Student {$student['user_id']}: CHART DATA STORED - Subjects: " . count($chart_data['subjects']) . ", Marks: " . count($chart_data['marks']) . ", Historical: " . count($chart_data['historical_data']));
                        error_log("Student {$student['user_id']}: Chart data keys available: " . implode(', ', array_keys($chart_data)));

                        // Calculate overall grade
                        $overall_grade = '';
                        $overall_remarks = '';
                        if ($subjects_with_marks > 0) {
                            $overall_grade_info = getGradeFromScale($average_mark, 0, $class_id, $academic_year, $term, $class_school_id, $connection, $grading_scale_name, $class_level);
                            $overall_grade = $overall_grade_info['display_grade'];
                            $overall_remarks = $overall_grade_info['remarks'];
                        }
                        ?>
                        
                        <div class="report-card">
                            <!-- School Logo Watermark for this Report Card -->
                            <?php if (!empty($school['logo'])): ?>
                                <div class="report-card-watermark" style="background-image: url('<?php echo htmlspecialchars($school['logo']); ?>');"></div>
                            <?php endif; ?>

                            <!-- Header Section with School Details -->
                            <div class="report-card-header">
                                <div class="school-logo">
                                    <?php if (!empty($school['logo']) && file_exists($school['logo'])): ?>
                                        <img src="<?php echo htmlspecialchars($school['logo']); ?>" alt="School Logo">
                                    <?php else: ?>
                                        <?php echo strtoupper(substr($school['school_name'], 0, 1)); ?>
                                    <?php endif; ?>
                                </div>
                                <div class="school-details">
                                    <div class="school-name"><?php echo htmlspecialchars($school['school_name']); ?></div>
                                    <div class="school-address"><?php echo htmlspecialchars($school['address'] ?? 'Address not available'); ?></div>
                                    <div class="school-contact">
                                        <?php if (!empty($school['phone'])): ?>Tel: <?php echo htmlspecialchars($school['phone']); ?><?php endif; ?>
                                        <?php if (!empty($school['phone']) && !empty($school['email'])): ?> | <?php endif; ?>
                                        <?php if (!empty($school['email'])): ?>Email: <?php echo htmlspecialchars($school['email']); ?><?php endif; ?>
                                    </div>
                                </div>
                            </div>

                            <!-- Enhanced Academic Report Form Button -->
                            <div class="academic-report-button">
                                <?php if ($class_level === 'senior_level'): ?>
                                    ACADEMIC REPORT FORM - SENIOR LEVEL (<?php echo strtoupper(htmlspecialchars($class_name ?? '')); ?>) - <?php echo strtoupper(htmlspecialchars($exam['exam_name'] ?? '')); ?> - (<?php echo htmlspecialchars(($academic_year ?? '') . ' ' . ($term ?? '')); ?>)
                                <?php elseif ($class_level === 'senior_olevel'): ?>
                                    ACADEMIC REPORT FORM - O-LEVEL (<?php echo strtoupper(htmlspecialchars($class_name ?? '')); ?>) - <?php echo strtoupper(htmlspecialchars($exam['exam_name'] ?? '')); ?> - (<?php echo htmlspecialchars(($academic_year ?? '') . ' ' . ($term ?? '')); ?>)
                                <?php else: ?>
                                    ACADEMIC REPORT FORM - <?php echo strtoupper(htmlspecialchars($class_name ?? '')); ?> - <?php echo strtoupper(htmlspecialchars($exam['exam_name'] ?? '')); ?> - (<?php echo htmlspecialchars(($academic_year ?? '') . ' ' . ($term ?? '')); ?>)
                                <?php endif; ?>
                            </div>

                            <!-- Simplified Performance Statistics -->
                            <?php if ($class_level === 'senior_level'): ?>
                                <div class="senior-level-stats">
                                    <div class="stat-btn">
                                        <span class="stat-value"><?php 
                                            $principal_passes = 0;
                                            $subsidiary_passes = 0;
                                            
                                            foreach ($grades_by_subject as $grade_data) {
                                                $subject_name = $grade_data['subject'] ?? 'Unknown Subject';
                                                
                                                // Determine if subject is principal or subsidiary based on subject name patterns
                                                $is_principal = isPrincipalSubjectByName($subject_name);
                                                
                                                if (isset($grade_data['subject_papers']) && count($grade_data['subject_papers']) > 0) {
                                                    // Multi-paper subject - use the subject grade
                                                    $subject_grade = $grade_data['subject_grade'] ?? [];
                                                    $grade_letter = $subject_grade['grade_letter'] ?? 'F';
                                                    
                                                    if (in_array($grade_letter, ['A', 'B', 'C', 'D', 'E'])) {
                                                        if ($is_principal) {
                                                            $principal_passes++;
                                                        } else {
                                                            // Subsidiary subjects don't get Principal Pass, they get Subsidiary Pass classification
                                                            // But for counting purposes, still add to subsidiary pass count
                                                            $subsidiary_passes++;
                                                        }
                                                    } elseif ($grade_letter == 'O') {
                                                        $subsidiary_passes++;
                                                    }
                                                } else {
                                                    // Single paper subject - use individual grade
                                                    $grade_letter = getGradeFromScale($grade_data['mark'], 0, $class_id, $academic_year, $term, $class_school_id, $connection, $grading_scale_name, $class_level)['grade_letter'];
                                                    
                                                    if (in_array($grade_letter, ['A', 'B', 'C', 'D', 'E'])) {
                                                        if ($is_principal) {
                                                            $principal_passes++;
                                                        } else {
                                                            // Subsidiary subjects don't get Principal Pass, they get Subsidiary Pass classification  
                                                            $subsidiary_passes++;
                                                        }
                                                    } elseif ($grade_letter == 'O') {
                                                        $subsidiary_passes++;
                                                    }
                                                }
                                            }
                                            echo $principal_passes;
                                        ?></span>
                                        <span class="stat-label">Principal Pass</span>
                                    </div>
                                    <div class="stat-btn">
                                        <span class="stat-value"><?php echo $subsidiary_passes; ?></span>
                                        <span class="stat-label">Subsidiary Pass</span>
                                    </div>
                                    <div class="stat-btn" title="Total A-Level points from <?php echo $points_calculated; ?> valid subjects (HED/SM system - max 20 points)">
                                        <span class="stat-value"><?php echo $total_points . '/20'; ?></span>
                                        <span class="stat-label">A-Level Points</span>
                                        <small style="font-size: 10px; color: #666;"><?php echo $points_calculated; ?> subjects</small>
                                    </div>
                                    <div class="stat-btn">
                                        <span class="stat-value"><?php echo $average_points; ?></span>
                                        <span class="stat-label">Average Points</span>
                                    </div>
                                    <div class="stat-btn">
                                        <span class="stat-value"><?php echo isset($stream_rank) ? $stream_rank : '--'; ?></span>
                                        <span class="stat-label">Stream Rank</span>
                                    </div>
                                    <div class="stat-btn">
                                        <span class="stat-value"><?php echo isset($overall_rank) ? $overall_rank : '--'; ?></span>
                                        <span class="stat-label">Overall Rank</span>
                                    </div>
                                </div>
                            <?php endif; ?>



                            <!-- Student Photo and Details Section -->
                            <div class="student-section">
                                <div class="student-photo-column">
                                    <div class="student-photo">
                                        <?php 
                                        $photo_exists = false;
                                        $photo_path = '';
                                        
                                        if (!empty($student['photo'])) {
                                            if (file_exists($student['photo'])) {
                                                $photo_exists = true;
                                                $photo_path = $student['photo'];
                                            }
                                        }
                                        
                                        if ($photo_exists): ?>
                                            <img src="<?php echo htmlspecialchars($photo_path); ?>" alt="Student Photo">
                                        <?php else: ?>
                                            <div class="student-photo-placeholder">
                                                👤<br>
                                                <small style="font-size: 8px;">Student<br>Photo</small>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                </div>

                                <div class="student-details">
                                    <div class="student-info-vertical">
                                        <div class="student-info-item">
                                            <strong>NAME:</strong> <?php echo strtoupper(htmlspecialchars($student['student_name'])); ?>
                                        </div>
                                        <div class="student-info-item">
                                            <strong>ADMNO:</strong> <?php echo htmlspecialchars($student['ADM'] ?? 'N/A'); ?>
                                        </div>
                                        <div class="student-info-item">
                                            <strong>CLASS:</strong> <?php echo htmlspecialchars($class_name . ($stream_name ? ' ' . $stream_name : '')); ?>
                                        </div>
                                        <?php 
                                        $combination_display = '';
                                        if (!empty($student['combination_name'])) {
                                            $combination_display = $student['combination_name'];
                                        } elseif (!empty($student['combination_code'])) {
                                            $combination_display = $student['combination_code'];
                                        }
                                        
                                        if (!empty($combination_display)): ?>
                                        <div class="student-info-item">
                                            <strong>COMBINATION:</strong> <?php echo htmlspecialchars($combination_display); ?>
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                </div>

                                <?php if ($class_level === 'senior_level'): ?>
                                <div class="performance-graph">
                                    <div style="text-align: center; font-weight: bold; margin-bottom: 5px; color: #2c5aa0;">Performance Overview</div>
                                    <div class="chart-container">
                                        <canvas id="overviewChart_<?php echo $student['user_id']; ?>"></canvas>
                                    </div>
                                </div>
                                <?php endif; ?>
                            </div>

                            <!-- Examination Results Table -->
                            <div class="results-section">
                                <h3 class="results-title">EXAMINATION RESULTS</h3>
                                <!-- MODIFIED: Added final subject grade rows after papers for UACE subjects -->
                                <!-- Each multi-paper subject now shows individual paper results followed by overall subject grade -->
                                <!-- Statistics now properly distinguish Principal vs Subsidiary subjects based on combination -->
                                <!-- Examples: PEM/ICT -> PEM=Principal, ICT=Subsidiary; General paper=Subsidiary -->
                                <table class="results-table">
                                    <thead>
                                        <tr>
                                            <th>SUBJECTS</th>
                                            <th>MARKS</th>
                                            <th>GRADE</th>
                                            <th>COMMENTS</th>
                                            <th>TEACHER</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php
                                        // Enhanced duplicate prevention table rendering
                                        $unique_subjects = [];
                                        $seen_subject_ids = [];

                                        foreach ($grades_data as $subject_data) {
                                            if (!in_array($subject_data['subject_id'], $seen_subject_ids)) {
                                                $seen_subject_ids[] = $subject_data['subject_id'];
                                                $unique_subjects[] = $subject_data;
                                            } else {
                                                error_log("TABLE RENDERING: Skipped duplicate {$subject_data['subject_name']} (ID: {$subject_data['subject_id']})");
                                            }
                                        }

                                        if (!empty($unique_subjects)) {
                                            foreach ($unique_subjects as $subject_data) {
                                                $mark = $subject_data['mark'];
                                                $grade = '';
                                                $comments = '';
                                                $teacher_name = $subject_data['teacher_name'] ?? 'Not Assigned';
                                                
                                                if ($mark !== null) {
                                                    $grade_info = getGradeFromScale($mark, $subject_data['subject_id'], $class_id, $academic_year, $term, $class_school_id, $connection, $grading_scale_name, $class_level);
                                                    $grade = $grade_info['display_grade'];
                                                    $comments = $grade_info['remarks'];
                                                    
                                                    // Check if this subject has papers (for senior level students)
                                                    if ($class_level === 'senior_level' && !empty($subject_data['papers']) && count($subject_data['papers']) > 0) {
                                                        $total_papers = count($subject_data['papers']);
                                                        $paper_count = 0;
                                                        
                                                        // Display each paper as individual rows with merged subject column
                                                        foreach ($subject_data['papers'] as $paper_index => $paper) {
                                                            $paper_mark = $subject_data['paper_marks'][$paper['paper_id']]['mark'] ?? null;
                                                            $paper_grade = '';
                                                            $paper_comments = '';
                                                            $paper_mark_display = '';
                                                            $is_last_paper = ($paper_index === count($subject_data['papers']) - 1);
                                                            
                                                            if ($paper_mark !== null) {
                                                                $paper_grade_info = getGradeFromScale($paper_mark, $subject_data['subject_id'], $class_id, $academic_year, $term, $class_school_id, $connection, $grading_scale_name, $class_level);
                                                                $paper_grade = $paper_grade_info['display_grade'];
                                                                $paper_comments = $paper_grade_info['remarks'];
                                                                $paper_mark_display = $paper_mark . "%";
                                                            }
                                                            
                                                            // For the last paper, show the final subject grade in a separate summary row
                                                            
                                                            echo "<tr class='subject-paper'>";
                                                            
                                                            // Only show subject name on first paper row with rowspan (including summary row)
                                                            if ($paper_count === 0) {
                                                                echo "<td rowspan='" . ($total_papers + 1) . "'><strong>" . htmlspecialchars(getSubjectDisplayText($subject_data)) . "</strong></td>";
                                                            }
                                                            
                                                            if ($paper_mark !== null) {
                                                                echo "<td>" . htmlspecialchars($paper_mark_display) . "</td>";
                                                                echo "<td><span class='grade-badge'>" . htmlspecialchars($paper_grade) . "</span></td>";
                                                                echo "<td>" . htmlspecialchars($paper_comments) . "</td>";
                                                            } else {
                                                                echo "<td style='color: #999;'>No mark</td>";
                                                                echo "<td><span class='grade-badge' style='background: #6c757d;'>N/A</span></td>";
                                                                echo "<td style='color: #999;'>-</td>";
                                                            }
                                                            
                                                            // Show teacher name on first row only (with increased rowspan for summary)
                                                            if ($paper_count === 0) {
                                                                echo "<td rowspan='" . ($total_papers + 1) . "'>" . htmlspecialchars($teacher_name) . "</td>";
                                                            }
                                                            echo "</tr>";
                                                            
                                                            $paper_count++;
                                                        }
                                                        
                                                        // Add final subject grade summary row after all papers
                                                        if ($paper_count > 0 && !empty($subject_data['subject_grade'])) {
                                                            $final_grade_letter = $subject_data['subject_grade']['grade_letter'] ?? '';
                                                            $final_grade_classification = $subject_data['subject_grade']['classification'] ?? '';
                                                            
                                                            if (!empty($final_grade_letter)) {
                                                                echo "<tr class='subject-final-grade' style='background-color: #f8f9fa; font-weight: bold;'>";
                                                                echo "<td></td>"; // Marks column (empty for summary)
                                                                echo "<td><span class='grade-badge' style='background: linear-gradient(45deg, #007bff, #0056b3); color: white; font-weight: bold;'>" . 
                                                                     htmlspecialchars($final_grade_letter) . "</span></td>"; // Grade column - final grade here
                                                                echo "<td>" . htmlspecialchars($final_grade_classification) . "</td>"; // Comments column - classification here
                                                                echo "</tr>";
                                                            }
                                                        }
                                                    } else {
                                                        // Regular subject without papers
                                                        // Note: Showing only subject name (not both name and code) for cleaner presentation
                                                        echo "<tr>";
                                                        echo "<td><strong>" . htmlspecialchars(getSubjectDisplayText($subject_data)) . "</strong></td>";
                                                        echo "<td>" . htmlspecialchars($mark) . "%</td>";
                                                        echo "<td><span class='grade-badge'>" . htmlspecialchars($grade) . "</span></td>";
                                                        echo "<td>" . htmlspecialchars($comments) . "</td>";
                                                        echo "<td>" . htmlspecialchars($teacher_name) . "</td>";
                                                        echo "</tr>";
                                                    }
                                                } else {
                                                    // No marks recorded case
                                                    if ($class_level === 'senior_level' && !empty($subject_data['papers']) && count($subject_data['papers']) > 0) {
                                                        $total_papers = count($subject_data['papers']);
                                                        $paper_count = 0;
                                                        
                                                        // Display each paper as individual rows with merged subject column
                                                        foreach ($subject_data['papers'] as $paper_index => $paper) {
                                                            $paper_mark = $subject_data['paper_marks'][$paper['paper_id']]['mark'] ?? null;
                                                            $paper_grade = '';
                                                            $paper_comments = '';
                                                            $paper_mark_display = '';
                                                            $is_last_paper = ($paper_index === count($subject_data['papers']) - 1);
                                                            
                                                            if ($paper_mark !== null) {
                                                                $paper_grade_info = getGradeFromScale($paper_mark, $subject_data['subject_id'], $class_id, $academic_year, $term, $class_school_id, $connection, $grading_scale_name, $class_level);
                                                                $paper_grade = $paper_grade_info['display_grade'];
                                                                $paper_comments = $paper_grade_info['remarks'];
                                                                $paper_mark_display = $paper_mark . "%";
                                                            } else {
                                                                $paper_grade = 'N/A';
                                                                $paper_comments = 'No marks recorded';
                                                            }
                                                            
                                                            echo "<tr class='subject-paper'>";
                                                            
                                                            // Only show subject name on first paper row with rowspan (including summary row)
                                                            if ($paper_count === 0) {
                                                                echo "<td rowspan='" . ($total_papers + 1) . "'><strong>" . htmlspecialchars(getSubjectDisplayText($subject_data)) . "</strong></td>";
                                                            }
                                                            
                                                            echo "<td>" . htmlspecialchars($paper_mark_display ?: 'No mark') . "</td>";
                                                            echo "<td><span class='grade-badge' style='background: #6c757d;'>" . htmlspecialchars($paper_grade) . "</span></td>";
                                                            echo "<td style='color: #999;'>" . htmlspecialchars($paper_comments) . "</td>";
                                                            
                                                            // Show teacher name on first row only (with increased rowspan for summary)
                                                            if ($paper_count === 0) {
                                                                echo "<td rowspan='" . ($total_papers + 1) . "'>" . htmlspecialchars($teacher_name) . "</td>";
                                                            }
                                                            echo "</tr>";
                                                            
                                                            $paper_count++;
                                                        }
                                                        
                                                        // Add final subject grade summary row for no marks case
                                                        if ($paper_count > 0) {
                                                            echo "<tr class='subject-final-grade' style='background-color: #f8f9fa; font-weight: bold;'>";
                                                            echo "<td></td>"; // Marks column (empty for summary)
                                                            echo "<td><span class='grade-badge' style='background: #6c757d;'>N/A</span></td>"; // Grade column - N/A
                                                            echo "<td style='color: #999;'>No marks recorded</td>"; // Comments column - message here
                                                            echo "</tr>";
                                                        }
                                                    } else {
                                                        // Regular subject without papers and no marks
                                                        echo "<tr>";
                                                        echo "<td><strong>" . htmlspecialchars($subject_data['subject_name']) . "</strong></td>";
                                                        echo "<td style='color: #999;'>-</td>";
                                                        echo "<td><span class='grade-badge' style='background: #6c757d;'>N/A</span></td>";
                                                        echo "<td style='color: #999;'>No marks recorded</td>";
                                                        echo "<td>" . htmlspecialchars($teacher_name) . "</td>";
                                                        echo "</tr>";
                                                    }
                                                }
                                            }
                                        } else {
                                            echo "<tr><td colspan='6' style='text-align: center; color: #999;'>No subjects found for this student</td></tr>";
                                        }

                                        error_log("Student " . $student['user_id'] . ": Displayed " . count($unique_subjects) . " unique subjects (originally had " . count($grades_data) . ")");
                                        
                                        // Calculate average score and grade (only for S1-2 and S3-4, not S5-6)
                                        if ($class_level !== 'senior_level') {
                                            $valid_marks = [];
                                            $total_subjects = count($unique_subjects); // Total number of subjects student is taking
                                            
                                            foreach ($unique_subjects as $subject_data) {
                                                if ($subject_data['mark'] !== null && is_numeric($subject_data['mark'])) {
                                                    $valid_marks[] = (float)$subject_data['mark'];
                                                }
                                            }
                                            
                                            if (!empty($valid_marks)) {
                                                $total_marks = array_sum($valid_marks);
                                                $average_score = round($total_marks / $total_subjects, 1); // Divide by total subjects, not subjects with marks
                                                
                                                // Get grade for the average score (using first subject as reference for grading scale)
                                                $first_subject = $unique_subjects[0];
                                                $average_grade_info = getGradeFromScale($average_score, $first_subject['subject_id'], $class_id, $academic_year, $term, $class_school_id, $connection, $grading_scale_name, $class_level);
                                                $average_grade = $average_grade_info['display_grade'];
                                                $average_comments = $average_grade_info['remarks'];
                                                
                                                // Add average score row
                                                echo "<tr style='background-color: #e3f2fd; font-weight: bold; border-top: 2px solid #1976d2;'>";
                                                echo "<td><strong>AVERAGE SCORE</strong></td>";
                                                echo "<td><strong>" . $average_score . "</strong></td>";
                                                echo "<td><span class='grade-badge' style='background: linear-gradient(45deg, #1976d2, #0d47a1); color: white; font-weight: bold;'>" . htmlspecialchars($average_grade) . "</span></td>";
                                                echo "<td>" . htmlspecialchars($average_comments) . "</td>";
                                                echo "<td style='font-style: italic;'>System Generated</td>";
                                                echo "</tr>";
                                            }
                                        }
                                        ?>
                                    </tbody>
                                </table>
                            </div>

                            <!-- Performance and Remarks / Comments and Grade Descriptors -->
                            <div class="performance-remarks-container">
                                <?php if ($class_level === 'senior_level'): ?>
                                <!-- Senior Level: Performance Trends and Remarks -->
                                <div class="performance-trends">
                                    <div class="trends-title">STUDENT'S PERFORMANCE OVER TIME</div>
                                    <div class="trends-chart">
                                        <canvas id="trendsChart_<?php echo $student['user_id']; ?>"></canvas>
                                    </div>
                                </div>

                                <div class="remarks-section">
                                    <div class="remark-box">
                                        <div class="remark-title">CLASS TEACHER'S REMARKS</div>
                                        <div class="remark-content">
                                            <?php echo htmlspecialchars($overall_remarks ?? ''); ?>
                                        </div>
                                        <div style="margin-top: 5px; font-size: 8px;">
                                            Signature: ________________<br>
                                            Date: <?php echo date('Y-m-d'); ?>
                                        </div>
                                    </div>

                                    <div class="remark-box">
                                        <div class="remark-title">PRINCIPAL'S REMARKS</div>
                                        <div class="remark-content">
                                            Keep up the excellent work and strive for excellence in all your endeavors.
                                        </div>
                                        <div style="margin-top: 5px; font-size: 8px;">
                                            Signature: ________________<br>
                                            Date: <?php echo date('Y-m-d'); ?>
                                        </div>
                                    </div>
                                </div>
                                <?php else: ?>
                                <!-- Junior Level (S1-S4): Comments and Grade Descriptors - Compact Version -->
                                <div class="comments-grade-descriptors">
                                    <!-- COMMENTS Section -->
                                    <div class="comments-section">
                                        <div class="comments-header">COMMENTS</div>
                                        <div class="comments-content">
                                            <div class="comment-panel">
                                                <div class="comment-title">Class Teacher Remarks:</div>
                                                <div class="comment-text">Aim higher next time</div>
                                                <div class="signature-line">
                                                    Signature: ________________<br>
                                                    Date: <?php echo date('Y-m-d'); ?>
                                                </div>
                                            </div>
                                            <div class="comment-panel">
                                                <div class="comment-title">Head Teacher Remarks:</div>
                                                <div class="comment-text">Basic pass! keep working to improve</div>
                                                <div class="signature-line">
                                                    Signature: ________________<br>
                                                    Date: <?php echo date('Y-m-d'); ?>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- GRADE DESCRIPTORS Section -->
                                    <div class="grade-descriptors-section">
                                        <div class="grade-descriptors-header">GRADE DESCRIPTORS</div>
                                        <div class="grade-descriptors-table">
                                            <table class="grade-descriptors-table-inner" style="width: 100%; border-collapse: collapse;">
                                                <thead>
                                                    <tr>
                                                        <th style="background-color: #2c5aa0; color: white; padding: 4px; text-align: center; border: 1px solid #ddd; font-size: 7px;">GRADE</th>
                                                        <th style="background-color: #2c5aa0; color: white; padding: 4px; text-align: center; border: 1px solid #ddd; font-size: 7px;">SCORE RANGE</th>
                                                        <th style="background-color: #2c5aa0; color: white; padding: 4px; text-align: center; border: 1px solid #ddd; font-size: 7px;">GRADE DESCRIPTOR</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <tr>
                                                        <td style="padding: 3px; text-align: center; border: 1px solid #ddd; font-weight: bold; font-size: 7px;">A</td>
                                                        <td style="padding: 3px; text-align: center; border: 1px solid #ddd; font-size: 7px;">80 - 100</td>
                                                        <td style="padding: 3px; border: 1px solid #ddd; font-size: 6px; line-height: 1.2;">Exceptional - Extraordinary competency</td>
                                                    </tr>
                                                    <tr>
                                                        <td style="padding: 3px; text-align: center; border: 1px solid #ddd; font-weight: bold; font-size: 7px;">B</td>
                                                        <td style="padding: 3px; text-align: center; border: 1px solid #ddd; font-size: 7px;">70 - 79</td>
                                                        <td style="padding: 3px; border: 1px solid #ddd; font-size: 6px; line-height: 1.2;">Outstanding - High level competency</td>
                                                    </tr>
                                                    <tr>
                                                        <td style="padding: 3px; text-align: center; border: 1px solid #ddd; font-weight: bold; font-size: 7px;">C</td>
                                                        <td style="padding: 3px; text-align: center; border: 1px solid #ddd; font-size: 7px;">60 - 69</td>
                                                        <td style="padding: 3px; border: 1px solid #ddd; font-size: 6px; line-height: 1.2;">Satisfactory - Adequate competency</td>
                                                    </tr>
                                                    <tr>
                                                        <td style="padding: 3px; text-align: center; border: 1px solid #ddd; font-weight: bold; font-size: 7px;">D</td>
                                                        <td style="padding: 3px; text-align: center; border: 1px solid #ddd; font-size: 7px;">50 - 59</td>
                                                        <td style="padding: 3px; border: 1px solid #ddd; font-size: 6px; line-height: 1.2;">Basic - Minimum competency</td>
                                                    </tr>
                                                    <tr>
                                                        <td style="padding: 3px; text-align: center; border: 1px solid #ddd; font-weight: bold; font-size: 7px;">E</td>
                                                        <td style="padding: 3px; text-align: center; border: 1px solid #ddd; font-size: 7px;">&lt;49</td>
                                                        <td style="padding: 3px; border: 1px solid #ddd; font-size: 6px; line-height: 1.2;">Elementary - Below basic competency</td>
                                                    </tr>
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                                <?php endif; ?>
                            </div>

                            <!-- Footer -->
                            <div class="report-footer">
                                <div class="school-motto-footer">
                                    <?php if (!empty($school['motto'])): ?>
                                        <strong>School Motto:</strong> "<?php echo htmlspecialchars($school['motto']); ?>"
                                    <?php else: ?>
                                        <strong>School Motto:</strong> "Excellence in Education"
                                    <?php endif; ?>
                                </div>
                                <div class="qr-code" id="qr-code-<?php echo $student['user_id']; ?>">
                                    <div style="font-size: 7px; margin-bottom: 2px;">Scan for Details</div>
                                </div>
                            </div>

                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <div class="no-students-message">
                        <h3>No Students Found</h3>
                        <p>No students found for the selected class and parameters.</p>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <script>
        // JavaScript functionality
        const menuToggle = document.getElementById('menuToggle');
        const dashboardContainer = document.getElementById('dashboardContainer');
        
        menuToggle.addEventListener('click', function() {
            dashboardContainer.classList.toggle('sidebar-collapsed');
        });

        function changeLanguage() {
            const language = document.getElementById('languageSelect').value;
            // Store language preference in session
            fetch('set_language.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'language=' + language
            }).then(() => {
                location.reload();
            });
        }

        // Initialize charts and QR codes for each student
        document.addEventListener('DOMContentLoaded', function() {
            // Debug: Log chart data availability
            console.log('Available students:', <?php echo json_encode(array_column($students, 'user_id')); ?>);
            console.log('Available chart data:', <?php echo json_encode(array_keys($all_chart_data)); ?>);
            console.log('Chart data count:', <?php echo count($all_chart_data); ?>);
            
            <?php if (!empty($students)): ?>
                <?php foreach ($students as $student): ?>
                    // Check if chart data exists for this student
                    console.log('Student <?php echo $student['user_id']; ?> chart data exists:', <?php echo isset($all_chart_data[$student['user_id']]) ? 'true' : 'false'; ?>);
                    <?php if ($class_level === 'senior_level'): ?>
                    // Initialize overview chart for S5-S6 students only
                    const overviewCanvas_<?php echo $student['user_id']; ?> = document.getElementById('overviewChart_<?php echo $student['user_id']; ?>');
                    if (overviewCanvas_<?php echo $student['user_id']; ?> && typeof Chart !== 'undefined') {
                        const ctxOverview_<?php echo $student['user_id']; ?> = overviewCanvas_<?php echo $student['user_id']; ?>.getContext('2d');
                        // Check if student has chart data in $all_chart_data
                        const studentChartData_<?php echo $student['user_id']; ?> = <?php echo isset($all_chart_data[$student['user_id']]) ? json_encode($all_chart_data[$student['user_id']]) : 'null'; ?>;
                        const hasChartData_<?php echo $student['user_id']; ?> = studentChartData_<?php echo $student['user_id']; ?> && studentChartData_<?php echo $student['user_id']; ?>.subjects && studentChartData_<?php echo $student['user_id']; ?>.marks;
                        
                        // Use actual chart data if available, empty arrays if not
                        const finalSubjects_<?php echo $student['user_id']; ?> = hasChartData_<?php echo $student['user_id']; ?> ? studentChartData_<?php echo $student['user_id']; ?>.subjects : [];
                        const finalMarks_<?php echo $student['user_id']; ?> = hasChartData_<?php echo $student['user_id']; ?> ? studentChartData_<?php echo $student['user_id']; ?>.marks : [];
                        
                        // Debug: Log the data being used
                        console.log('Student <?php echo $student['user_id']; ?> Overview Data:', {
                            hasChartData: hasChartData_<?php echo $student['user_id']; ?>,
                            subjects: finalSubjects_<?php echo $student['user_id']; ?>,
                            marks: finalMarks_<?php echo $student['user_id']; ?>,
                            dataLength: finalSubjects_<?php echo $student['user_id']; ?>.length
                        });

                        // Only create chart if student has actual data
                        if (hasChartData_<?php echo $student['user_id']; ?> && finalSubjects_<?php echo $student['user_id']; ?>.length > 0) {
                            new Chart(ctxOverview_<?php echo $student['user_id']; ?>, {
                                type: 'bar',
                                data: {
                                    labels: finalSubjects_<?php echo $student['user_id']; ?>,
                                    datasets: [{
                                        label: 'Marks',
                                        data: finalMarks_<?php echo $student['user_id']; ?>,
                                        backgroundColor: '#2c5aa0',
                                        borderColor: '#1e3d6f',
                                        borderWidth: 2,
                                        barThickness: 20,  // Set fixed bar width in pixels
                                        maxBarThickness: 25  // Maximum bar width for smaller bars
                                    }]
                                },
                                options: {
                                    responsive: true,
                                    maintainAspectRatio: false,
                                    plugins: { 
                                        legend: { display: false },
                                        tooltip: {
                                            callbacks: {
                                                label: function(context) {
                                                    return 'Mark: ' + context.parsed.y + '%';
                                                }
                                            }
                                        }
                                    },
                                    scales: {
                                        x: { 
                                            display: true,
                                            ticks: {
                                                font: { size: 10 },
                                                maxRotation: 45
                                            }
                                        },
                                        y: { 
                                            beginAtZero: true, 
                                            max: 100, 
                                            display: true,
                                            ticks: {
                                                stepSize: 20,
                                                font: { size: 10 }
                                            }
                                        }
                                    }
                                }
                            });
                        } else {
                            console.log('No data available for Student <?php echo $student['user_id']; ?> overview chart');
                            // Show a message in the chart container
                            ctxOverview_<?php echo $student['user_id']; ?>.font = "12px Arial";
                            ctxOverview_<?php echo $student['user_id']; ?>.fillStyle = "#999";
                            ctxOverview_<?php echo $student['user_id']; ?>.textAlign = "center";
                            ctxOverview_<?php echo $student['user_id']; ?>.fillText("No chart data available", 100, 60);
                        }
                    }
                    <?php endif; ?>

                    <?php if ($class_level === 'senior_level'): ?>
                    // Initialize trends chart for S5-S6 students only
                    const trendsCanvas_<?php echo $student['user_id']; ?> = document.getElementById('trendsChart_<?php echo $student['user_id']; ?>');
                    if (trendsCanvas_<?php echo $student['user_id']; ?> && typeof Chart !== 'undefined') {
                        const ctxTrends_<?php echo $student['user_id']; ?> = trendsCanvas_<?php echo $student['user_id']; ?>.getContext('2d');
                        // Check if student has chart data and extract historical data
                        const studentChartData_<?php echo $student['user_id']; ?> = <?php echo isset($all_chart_data[$student['user_id']]) ? json_encode($all_chart_data[$student['user_id']]) : 'null'; ?>;
                        const hasChartData_<?php echo $student['user_id']; ?> = studentChartData_<?php echo $student['user_id']; ?> && studentChartData_<?php echo $student['user_id']; ?>.historical_data;
                        
                        // Get historical data if available, empty arrays if not
                        const finalTrendsLabels_<?php echo $student['user_id']; ?> = hasChartData_<?php echo $student['user_id']; ?> ? (studentChartData_<?php echo $student['user_id']; ?>.historical_data.labels || []) : [];
                        const finalTrendsValues_<?php echo $student['user_id']; ?> = hasChartData_<?php echo $student['user_id']; ?> ? (studentChartData_<?php echo $student['user_id']; ?>.historical_data.values || []) : [];

                        // Debug: Log the trends data being used
                        console.log('Student <?php echo $student['user_id']; ?> Trends Data:', {
                            hasChartData: hasChartData_<?php echo $student['user_id']; ?>,
                            labels: finalTrendsLabels_<?php echo $student['user_id']; ?>,
                            values: finalTrendsValues_<?php echo $student['user_id']; ?>,
                            dataLength: finalTrendsLabels_<?php echo $student['user_id']; ?>.length
                        });

                        // Only create chart if student has historical data
                        if (hasChartData_<?php echo $student['user_id']; ?> && finalTrendsLabels_<?php echo $student['user_id']; ?>.length > 0) {
                            new Chart(ctxTrends_<?php echo $student['user_id']; ?>, {
                                type: 'line',
                                data: {
                                    labels: finalTrendsLabels_<?php echo $student['user_id']; ?>,
                                    datasets: [{
                                        label: 'Average Score',
                                        data: finalTrendsValues_<?php echo $student['user_id']; ?>,
                                        borderColor: '#28a745',
                                        backgroundColor: 'rgba(40, 167, 69, 0.1)',
                                        borderWidth: 2,
                                        fill: true,
                                        tension: 0.3,
                                        pointBackgroundColor: '#28a745',
                                        pointBorderColor: '#1e5420',
                                        pointRadius: 4
                                    }]
                                },
                                options: {
                                    responsive: true,
                                    maintainAspectRatio: false,
                                    plugins: { 
                                        legend: { display: false },
                                        tooltip: {
                                            callbacks: {
                                                label: function(context) {
                                                    return 'Average: ' + context.parsed.y + '%';
                                                }
                                            }
                                        }
                                    },
                                    scales: {
                                        x: { 
                                            display: true,
                                            grid: { display: false }, 
                                            ticks: { font: { size: 10 } }
                                        },
                                        y: { 
                                            beginAtZero: true, 
                                            max: 100, 
                                            display: true,
                                            grid: { display: false }, 
                                            ticks: { font: { size: 10 }, stepSize: 20 }
                                        }
                                    }
                                }
                            });
                        } else {
                            console.log('No historical data available for Student <?php echo $student['user_id']; ?> trends chart');
                            // Show a message in the chart container
                            ctxTrends_<?php echo $student['user_id']; ?>.font = "12px Arial";
                            ctxTrends_<?php echo $student['user_id']; ?>.fillStyle = "#999";
                            ctxTrends_<?php echo $student['user_id']; ?>.textAlign = "center";
                            ctxTrends_<?php echo $student['user_id']; ?>.fillText("No historical data", 100, 60);
                        }
                    }
                    <?php endif; ?>

                    // Initialize QR code
                    const qrElement_<?php echo $student['user_id']; ?> = document.getElementById('qr-code-<?php echo $student['user_id']; ?>');
                    if (qrElement_<?php echo $student['user_id']; ?>) {
                        const studentDetailsUrl = `${window.location.origin}${window.location.pathname}?student_id=<?php echo $student['user_id']; ?>&academic_year=<?php echo urlencode($academic_year); ?>&term=<?php echo urlencode($term); ?>&exam_id=<?php echo $exam_id; ?>&class_id=<?php echo $class_id; ?>&class_level=<?php echo $class_level; ?>&grading_scale=<?php echo urlencode($grading_scale_name); ?>`;
                        
                        if (typeof qrcode !== 'undefined') {
                            const qr_<?php echo $student['user_id']; ?> = qrcode(0, 'M');
                            qr_<?php echo $student['user_id']; ?>.addData(studentDetailsUrl);
                            qr_<?php echo $student['user_id']; ?>.make();
                            
                            const qrHTML = qr_<?php echo $student['user_id']; ?>.createImgTag(2, 2);
                            qrElement_<?php echo $student['user_id']; ?>.innerHTML = qrHTML + '<div style="font-size: 7px; margin-top: 2px;">Scan for Details</div>';
                            
                            const qrImg = qrElement_<?php echo $student['user_id']; ?>.querySelector('img');
                            if (qrImg) {
                                qrImg.style.width = '45px';
                                qrImg.style.height = '45px';
                                qrImg.style.border = '1px solid #2c5aa0';
                            }
                        } else {
                            const encodedUrl = encodeURIComponent(studentDetailsUrl);
                            const qrApiUrl = `https://chart.googleapis.com/chart?chs=45x45&cht=qr&chl=${encodedUrl}`;
                            qrElement_<?php echo $student['user_id']; ?>.innerHTML = `<img src="${qrApiUrl}" style="width: 45px; height: 45px; border: 1px solid #2c5aa0;" alt="QR Code"><div style="font-size: 7px; margin-top: 2px;">Scan for Details</div>`;
                        }
                    }
                <?php endforeach; ?>
            <?php endif; ?>
        });
    </script>
</body>
</html>

<?php

/**
 * Get student's historical performance data for trends chart
 * @param int $student_id
 * @param mysqli $connection
 * @param int $school_id
 * @param int $class_id
 * @return array Historical performance data with labels and values
 */
function getStudentHistoricalPerformance($student_id, $connection, $school_id, $class_id) {
    $historical_data = [
        'labels' => [],
        'values' => []
    ];
    
    try {
        // Get previous exams for this student (limit to last 5 exams for performance)
        $sql_historical = "
        SELECT DISTINCT e.exam_id, e.exam_name, e.year, e.term
        FROM exams e
        JOIN marks m ON e.exam_id = m.exam_id
        WHERE e.school_id = ? AND m.student_id = ?
        ORDER BY e.year DESC, e.term DESC, e.exam_id DESC
        LIMIT 5";
        
        $stmt_historical = $connection->prepare($sql_historical);
        $stmt_historical->bind_param("ii", $school_id, $student_id);
        $stmt_historical->execute();
        $result_historical = $stmt_historical->get_result();
        
        $exam_data = [];
        while ($exam = $result_historical->fetch_assoc()) {
            $exam_data[] = $exam;
        }
        $stmt_historical->close();
        
        // Reverse to get chronological order
        $exam_data = array_reverse($exam_data);
        
        // Get average marks for each exam
        foreach ($exam_data as $exam) {
            $sql_avg = "
            SELECT AVG(m.mark) as average_mark
            FROM marks m
            WHERE m.student_id = ? AND m.exam_id = ? AND m.mark IS NOT NULL";
            
            $stmt_avg = $connection->prepare($sql_avg);
            $stmt_avg->bind_param("ii", $student_id, $exam['exam_id']);
            $stmt_avg->execute();
            $result_avg = $stmt_avg->get_result();
            $avg_data = $result_avg->fetch_assoc();
            $stmt_avg->close();
            
            $avg_mark = $avg_data['average_mark'] ? round($avg_data['average_mark'], 1) : 0;
            
            // Create label (Term + Year)
            $label = "Term " . $exam['term'] . " " . $exam['year'];
            
            $historical_data['labels'][] = $label;
            $historical_data['values'][] = $avg_mark;
        }
        
        // If no historical data, provide current exam average
        if (empty($historical_data['labels'])) {
            // Try to get current exam data if available
            $current_exam_id = $_GET['exam_id'] ?? '';
            if (!empty($current_exam_id)) {
                $sql_current = "
                SELECT AVG(m.mark) as average_mark
                FROM marks m
                WHERE m.student_id = ? AND m.exam_id = ? AND m.mark IS NOT NULL";
                
                $stmt_current = $connection->prepare($sql_current);
                $stmt_current->bind_param("ii", $student_id, $current_exam_id);
                $stmt_current->execute();
                $result_current = $stmt_current->get_result();
                $current_data = $result_current->fetch_assoc();
                $stmt_current->close();
                
                $current_avg = $current_data['average_mark'] ? round($current_data['average_mark'], 1) : 0;
                
                $historical_data['labels'][] = "Current Term";
                $historical_data['values'][] = $current_avg;
            }
        }
        
    } catch (Exception $e) {
        error_log("Error getting historical performance: " . $e->getMessage());
        
        // Fallback: Try simpler approach without historical data
        try {
            // Get current exam data as fallback
            $current_exam_id = $_GET['exam_id'] ?? '';
            if (!empty($current_exam_id)) {
                $sql_current = "
                SELECT AVG(m.mark) as average_mark
                FROM marks m
                WHERE m.student_id = ? AND m.exam_id = ? AND m.mark IS NOT NULL";
                
                $stmt_current = $connection->prepare($sql_current);
                $stmt_current->bind_param("ii", $student_id, $current_exam_id);
                $stmt_current->execute();
                $result_current = $stmt_current->get_result();
                $current_data = $result_current->fetch_assoc();
                $stmt_current->close();
                
                $current_avg = $current_data['average_mark'] ? round($current_data['average_mark'], 1) : 0;
                
                $historical_data['labels'] = ["Current Exam"];
                $historical_data['values'] = [$current_avg];
                error_log("Historical performance fallback: Using current exam data only");
            } else {
                // Last resort: return empty data
                $historical_data['labels'] = ["No Historical Data"];
                $historical_data['values'] = [0];
                error_log("Historical performance: No current exam available, returning empty data");
            }
        } catch (Exception $e2) {
            error_log("Fallback also failed: " . $e2->getMessage());
            // Final fallback
            $historical_data['labels'] = ["No Data Available"];
            $historical_data['values'] = [0];
        }
    }
    
    return $historical_data;
}
?>

<script>
// PDF generation function commented out - buttons removed
/*
function printReportCards() {
    // Check if we're on the main report page
    const urlParams = new URLSearchParams(window.location.search);
    const classId = urlParams.get('class_id');
    const academicYear = urlParams.get('academic_year');
    const term = urlParams.get('term');
    const examId = urlParams.get('exam_id');
    
    if (!classId || !academicYear || !term || !examId) {
        alert('Missing required parameters for PDF generation.');
        return;
    }
    
    // Show loading indicator
    const loadingMsg = document.createElement('div');
    loadingMsg.style.cssText = `
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background: #007bff;
        color: white;
        padding: 20px 40px;
        border-radius: 10px;
        font-size: 16px;
        font-weight: bold;
        z-index: 10000;
        box-shadow: 0 4px 8px rgba(0,0,0,0.3);
    `;
    loadingMsg.textContent = 'Generating PDF Report...';
    document.body.appendChild(loadingMsg);
    
    // Generate PDF
    const pdfUrl = `?generate_pdf=1&class_id=${classId}&academic_year=${encodeURIComponent(academicYear)}&term=${encodeURIComponent(term)}&exam_id=${examId}`;
    
    // Create download link
    const downloadLink = document.createElement('a');
    downloadLink.href = pdfUrl;
    downloadLink.style.display = 'none';
    downloadLink.download = `Report_Cards_${term}_${academicYear}.pdf`;
    document.body.appendChild(downloadLink);
    downloadLink.click();
    
    // Remove loading indicator
    setTimeout(() => {
        document.body.removeChild(loadingMsg);
    }, 2000);
}
*/

// Individual student PDF generation function commented out - buttons removed
/*
function generateStudentPDF(studentId, studentName) {
    const urlParams = new URLSearchParams(window.location.search);
    const classId = urlParams.get('class_id');
    const academicYear = urlParams.get('academic_year');
    const term = urlParams.get('term');
    const examId = urlParams.get('exam_id');
    
    if (!classId || !academicYear || !term || !examId) {
        alert('Missing required parameters for PDF generation.');
        return;
    }
    
    // Show loading indicator
    const loadingMsg = document.createElement('div');
    loadingMsg.style.cssText = `
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background: #28a745;
        color: white;
        padding: 20px 40px;
        border-radius: 10px;
        font-size: 16px;
        font-weight: bold;
        z-index: 10000;
        box-shadow: 0 4px 8px rgba(0,0,0,0.3);
    `;
    loadingMsg.textContent = `Generating PDF for ${studentName}...`;
    document.body.appendChild(loadingMsg);
    
    // Generate PDF for single student
    const pdfUrl = `?generate_single_pdf=1&student_id=${studentId}&class_id=${classId}&academic_year=${encodeURIComponent(academicYear)}&term=${encodeURIComponent(term)}&exam_id=${examId}`;
    
    // Create download link
    const downloadLink = document.createElement('a');
    downloadLink.href = pdfUrl;
    downloadLink.style.display = 'none';
    downloadLink.download = `Report_Card_${encodeURIComponent(studentName)}_${term}_${academicYear}.pdf`;
    document.body.appendChild(downloadLink);
    downloadLink.click();
    
    // Remove loading indicator
    setTimeout(() => {
        document.body.removeChild(loadingMsg);
    }, 2000);
}
*/

// Function to print the current view
function printCurrentView() {
    // Hide non-essential elements that shouldn't be printed
    const elementsToHide = [
        '.form-actions',
        '.btn',
        'button',
        '.no-print',
        '.sidebar',
        '.navigation'
    ];
    
    const hiddenElements = [];
    
    // Hide specified elements
    elementsToHide.forEach(selector => {
        const elements = document.querySelectorAll(selector);
        elements.forEach(element => {
            if (element.style.display !== 'none') {
                element.setAttribute('data-original-display', element.style.display);
                element.style.display = 'none';
                hiddenElements.push(element);
            }
        });
    });
    
    // Add print-specific styles
    const printStyle = document.createElement('style');
    printStyle.id = 'print-style';
    printStyle.textContent = `
        @media print {
            body {
                font-size: 12pt;
                line-height: 1.4;
            }
            .header {
                position: relative !important;
            }
            .main-content {
                margin-left: 0 !important;
            }
            .report-card {
                page-break-inside: avoid;
                margin-bottom: 20px;
            }
        }
    `;
    document.head.appendChild(printStyle);
    
    // Print the page
    window.print();
    
    // Restore hidden elements after printing
    setTimeout(() => {
        hiddenElements.forEach(element => {
            const originalDisplay = element.getAttribute('data-original-display');
            if (originalDisplay) {
                element.style.display = originalDisplay;
                element.removeAttribute('data-original-display');
            } else {
                element.style.display = '';
            }
        });
        
        // Remove print styles
        const styleElement = document.getElementById('print-style');
        if (styleElement) {
            document.head.removeChild(styleElement);
        }
    }, 100);
}
</script>

<?php
// =============================================================================
// 1. MAIN PDF GENERATION FUNCTIONS
// =============================================================================

/**
 * Complete implementation of PDF generation for all report cards
 */
function generateReportCardsPDF($connection, $academic_year, $term, $exam_id, $class_id, $student_ids = []) {
    try {
        logDebugInfo("PDF generation started", [
            'academic_year' => $academic_year,
            'term' => $term,
            'exam_id' => $exam_id,
            'class_id' => $class_id,
            'student_count' => count($student_ids),
            'dompdf_available' => class_exists('Dompdf\Dompdf')
        ]);
        
        // Check if dompdf is available
        if (!class_exists('Dompdf\\Dompdf')) {
            logDebugInfo("Dompdf not available, using HTML fallback");
            // 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>';
        
        // Build HTML with CSS and JavaScript
        $html = generateCompletePDFCSS() . '<body>';
        $html .= '<div class="print-button-container no-print">';
        $html .= '<button class="print-button" onclick="printAllReports()">🖨️ Print All Reports (' . count($students) . ')</button>';
        $html .= '<button class="print-button secondary" onclick="window.print()">🖨️ Print Current Page</button>';
        $html .= '</div>';
        
        // 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
                );
            }
        }
        
        // Add JavaScript for print functionality
        $html .= generatePrintJavaScript();
        $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 generateSingleStudentPDF($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);
        
        logDebugInfo("Student data retrieved", [
            'student_found' => !empty($student_data['student']),
            'grades_count' => count($student_data['grades'] ?? []),
            'student_name' => $student_data['student']['username'] ?? 'NOT FOUND',
            'class_name' => $class_info['class_name'] ?? 'NOT FOUND',
            'exam_name' => $exam_info['exam_name'] ?? 'NOT FOUND'
        ]);
        
        // Build HTML with CSS and JavaScript
        $html = generateCompletePDFCSS() . '<body>';
        $html .= '<div class="print-button-container no-print">';
        $html .= '<button class="print-button" onclick="window.print()">🖨️ Print This Report</button>';
        $html .= '<button class="print-button secondary" onclick="window.close()">✖️ Close</button>';
        $html .= '</div>';
        $html .= generateCompleteStudentReportCardHTML(
            $student_data, 
            $academic_year, 
            $term, 
            $class_info, 
            $exam_info, 
            $school_info,
            $student_data['student']
        );
        // Add JavaScript for print functionality
        $html .= generatePrintJavaScript();
        $html .= '</body></html>';
        
        logDebugInfo("HTML generated", [
            'html_length' => strlen($html),
            'has_school_header' => strpos($html, 'school-header') !== false,
            'has_grades_table' => strpos($html, 'grades-table') !== false,
            'has_student_info' => strpos($html, 'student-info-box') !== false
        ]);
        
        // Generate PDF
        $dompdf->loadHtml($html);
        $dompdf->setPaper('A4', 'portrait');
        $dompdf->render();
        
        $student_name = $student_data['student']['username'] ?? 'Student';
        $filename = "Report_Card_{$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. DATA RETRIEVAL FUNCTIONS
// =============================================================================

/**
 * Enhanced class information retrieval
 */
function getCompleteClassInfo($connection, $class_id) {
    $stmt = $connection->prepare("SELECT c.*, s.school_name 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();
    return $result->fetch_assoc() ?: [];
}

/**
 * Enhanced exam information retrieval
 */
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();
    return $result->fetch_assoc() ?: [];
}

/**
 * Enhanced school information retrieval
 */
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();
    return $result->fetch_assoc() ?: [];
}

/**
 * Enhanced class students retrieval
 */
function getCompleteClassStudents($connection, $class_id) {
    $stmt = $connection->prepare("
        SELECT u.*, c.class_name, s.stream_name, sc.combination_name 
        FROM users u 
        LEFT JOIN classes c ON u.class_id = c.class_id 
        LEFT JOIN streams s ON u.stream_id = s.stream_id 
        LEFT JOIN subject_combinations sc ON u.combination_id = sc.combination_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();
    return $result->fetch_all(MYSQLI_ASSOC) ?: [];
}

/**
 * Enhanced specific students retrieval
 */
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, s.stream_name, sc.combination_name 
        FROM users u 
        LEFT JOIN classes c ON u.class_id = c.class_id 
        LEFT JOIN streams s ON u.stream_id = s.stream_id 
        LEFT JOIN subject_combinations sc ON u.combination_id = sc.combination_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();
    return $result->fetch_all(MYSQLI_ASSOC) ?: [];
}

/**
 * Complete student report data retrieval
 */
function getCompleteStudentReportData($connection, $student_id, $exam_id, $class_id, $academic_year, $term) {
    // Get basic student information
    $stmt_student = $connection->prepare("
        SELECT u.*, c.class_name, s.stream_name, sc.combination_name 
        FROM users u 
        LEFT JOIN classes c ON u.class_id = c.class_id 
        LEFT JOIN streams s ON u.stream_id = s.stream_id 
        LEFT JOIN subject_combinations sc ON u.combination_id = sc.combination_id 
        WHERE u.id = ?
    ");
    $stmt_student->bind_param("i", $student_id);
    $stmt_student->execute();
    $student_result = $stmt_student->get_result();
    $student = $student_result->fetch_assoc() ?: [];
    $stmt_student->close();

    if (empty($student)) {
        return ['student' => [], 'grades' => []];
    }

    // Get grades/marks data
    $stmt_grades = $connection->prepare("
        SELECT 
            m.mark,
            m.subject_id,
            s.subject_name,
            s.subject_code,
            sp.paper_name,
            sp.paper_id,
            t.username as teacher_name
        FROM marks m
        LEFT JOIN subjects s ON m.subject_id = s.subject_id
        LEFT JOIN subject_papers sp ON m.paper_id = sp.paper_id
        LEFT JOIN users t ON m.teacher_user_id = t.id
        WHERE m.student_id = ? AND m.exam_id = ?
        ORDER BY s.subject_name, sp.paper_name
    ");
    $stmt_grades->bind_param("ii", $student_id, $exam_id);
    $stmt_grades->execute();
    $grades_result = $stmt_grades->get_result();
    $grades = $grades_result->fetch_all(MYSQLI_ASSOC) ?: [];
    $stmt_grades->close();

    // Calculate summary statistics and add grade conversion
    $total_marks = array_sum(array_column($grades, 'mark'));
    $grade_count = count($grades);
    $average_mark = $grade_count > 0 ? $total_marks / $grade_count : 0;
    
    // Add grade conversion for each grade record
    foreach ($grades as &$grade) {
        $mark = $grade['mark'];
        $subject_id = $grade['subject_id'] ?? 0;
        $class_level = $student['class_level'] ?? '';
        
        // Get grade letter based on mark
        $grade_info = getGradeFromScale($mark, $subject_id, $class_id, $academic_year, $term, $student['school_id'], $connection, '', $class_level);
        $grade['grade'] = $grade_info['grade_letter'] ?? 'N/A';
    }
    unset($grade); // Break the reference
    
    // Get ranking information (simplified)
    $class_rank = calculateSimpleClassRank($student_id, $class_id, $connection);

    return [
        'student' => $student,
        'grades' => $grades,
        'total_subjects' => $grade_count,
        'total_marks' => round($total_marks, 1),
        'average_mark' => round($average_mark, 1),
        'class_rank' => $class_rank,
        'class_total' => 30, // You can make this dynamic
        'highest_mark' => !empty($grades) ? max(array_column($grades, 'mark')) : 0,
        'lowest_mark' => !empty($grades) ? min(array_column($grades, 'mark')) : 0
    ];
}

/**
 * Simple class rank calculation
 */
function calculateSimpleClassRank($student_id, $class_id, $connection) {
    try {
        $stmt = $connection->prepare("
            SELECT u.id, AVG(m.mark) as avg_mark
            FROM users u
            LEFT JOIN marks m ON u.id = m.student_id
            WHERE u.class_id = ?
            GROUP BY u.id
            ORDER BY avg_mark DESC
        ");
        $stmt->bind_param("i", $class_id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        $rank = 1;
        while ($row = $result->fetch_assoc()) {
            if ($row['id'] == $student_id) {
                return $rank;
            }
            $rank++;
        }
        
        return '--';
    } catch (Exception $e) {
        return '--';
    }
}

// =============================================================================
// 3. HTML GENERATION FUNCTIONS
// =============================================================================

/**
 * Generate complete professional student report card HTML
 */
function generateCompleteStudentReportCardHTML($student_data, $academic_year, $term, $class_info, $exam_info, $school_info, $student) {
    $report_id = 'report_card_' . $student['id'] . '_' . $exam_info['id'];
    $html = '<div class="report-card" id="' . $report_id . '" style="page-break-after: always; margin-bottom: 30px;">';
    
    // Print button for individual report card
    $html .= '<div class="no-print print-single-btn" style="text-align: right; margin-bottom: 15px;">';
    $html .= '<button class="print-button secondary" onclick="printSingleReport(\'' . $report_id . '\')">🖨️ Print This Report</button>';
    $html .= '</div>';
    
    // School Header
    $html .= '<div class="school-header" style="text-align: center; border-bottom: 3px solid #2c5aa0; padding-bottom: 15px; margin-bottom: 20px;">';
    if (!empty($school_info['logo'])) {
        $html .= '<img src="' . htmlspecialchars($school_info['logo']) . '" alt="School Logo" style="width: 80px; height: 80px; object-fit: contain; margin-bottom: 10px;">';
    }
    $html .= '<h1 style="margin: 5px 0; color: #2c5aa0; font-size: 24px; font-weight: bold;">' . htmlspecialchars($school_info['school_name'] ?? '') . '</h1>';
    $html .= '<h2 style="margin: 5px 0; color: #333; font-size: 18px; font-weight: bold;">ACADEMIC REPORT</h2>';
    $html .= '<div style="color: #666; font-size: 14px;">' . htmlspecialchars($class_info['class_name'] ?? '') . ' - ' . htmlspecialchars($exam_info['exam_name'] ?? '') . '</div>';
    $html .= '<div style="color: #666; font-size: 14px;">' . htmlspecialchars($academic_year . ' ' . $term) . '</div>';
    $html .= '</div>';
    
    // Student Information Box
    $html .= '<div class="student-info-box" style="border: 2px solid #2c5aa0; padding: 15px; margin-bottom: 20px; background-color: #f8f9fa;">';
    $html .= '<div style="display: table; width: 100%;">';
    $html .= '<div style="display: table-cell; width: 50%; vertical-align: top; padding-right: 20px;">';
    $html .= '<strong>Student Name:</strong> ' . htmlspecialchars($student_data['student']['username'] ?? '') . '<br>';
    $html .= '<strong>Admission No:</strong> ' . htmlspecialchars($student_data['student']['ADM'] ?? '') . '<br>';
    $html .= '<strong>Class:</strong> ' . htmlspecialchars($class_info['class_name'] ?? '') . '<br>';
    $html .= '<strong>Stream:</strong> ' . htmlspecialchars($student_data['student']['stream_name'] ?? 'N/A') . '<br>';
    $html .= '</div>';
    $html .= '<div style="display: table-cell; width: 50%; vertical-align: top;">';
    $html .= '<strong>Combination:</strong> ' . htmlspecialchars($student_data['student']['combination_name'] ?? 'N/A') . '<br>';
    $html .= '<strong>Academic Year:</strong> ' . htmlspecialchars($academic_year) . '<br>';
    $html .= '<strong>Term:</strong> ' . htmlspecialchars($term) . '<br>';
    $html .= '<strong>Exam:</strong> ' . htmlspecialchars($exam_info['exam_name'] ?? '') . '<br>';
    $html .= '</div>';
    $html .= '</div>';
    $html .= '</div>';
    
    // Grades Table
    if (!empty($student_data['grades'])) {
        $html .= '<table class="grades-table" style="width: 100%; border-collapse: collapse; margin-bottom: 20px; font-size: 12px;">';
        $html .= '<thead>';
        $html .= '<tr style="background-color: #2c5aa0; color: white;">';
        $html .= '<th style="border: 1px solid #ddd; padding: 12px 8px; text-align: left;">Subject</th>';
        $html .= '<th style="border: 1px solid #ddd; padding: 12px 8px; text-align: center;">Marks</th>';
        $html .= '<th style="border: 1px solid #ddd; padding: 12px 8px; text-align: center;">Grade</th>';
        $html .= '<th style="border: 1px solid #ddd; padding: 12px 8px; text-align: center;">Teacher</th>';
        $html .= '</tr>';
        $html .= '</thead>';
        $html .= '<tbody>';
        
        foreach ($student_data['grades'] as $grade) {
            $html .= '<tr>';
            $html .= '<td style="border: 1px solid #ddd; padding: 8px;"><strong>' . htmlspecialchars($grade['subject_name'] ?? '') . '</strong></td>';
            $html .= '<td style="border: 1px solid #ddd; padding: 8px; text-align: center;">' . number_format($grade['mark'] ?? 0, 1) . '%</td>';
            $html .= '<td style="border: 1px solid #ddd; padding: 8px; text-align: center;"><strong>' . htmlspecialchars($grade['grade'] ?? 'N/A') . '</strong></td>';
            $html .= '<td style="border: 1px solid #ddd; padding: 8px; text-align: center;">' . htmlspecialchars($grade['teacher_name'] ?? 'N/A') . '</td>';
            $html .= '</tr>';
        }
        
        // Calculate average score and grade for PDF
        $valid_marks_pdf = [];
        foreach ($student_data['grades'] as $grade) {
            if (isset($grade['mark']) && is_numeric($grade['mark'])) {
                $valid_marks_pdf[] = (float)$grade['mark'];
            }
        }
        
        // Calculate average score and grade for PDF (only for S1-2 and S3-4, not S5-6)
        if (!empty($valid_marks_pdf) && $class_level !== 'senior_level') {
            $total_marks_pdf = array_sum($valid_marks_pdf);
            $total_subjects_pdf = count($student_data['grades']); // Total number of subjects student is taking
            $average_score_pdf = round($total_marks_pdf / $total_subjects_pdf, 1); // Divide by total subjects, not subjects with marks
            $html .= '<tr style="background-color: #e3f2fd; font-weight: bold; border-top: 2px solid #1976d2;">';
            $html .= '<td style="border: 1px solid #ddd; padding: 8px;"><strong>AVERAGE SCORE</strong></td>';
            $html .= '<td style="border: 1px solid #ddd; padding: 8px; text-align: center;"><strong>' . $average_score_pdf . '</strong></td>';
            $html .= '<td style="border: 1px solid #ddd; padding: 8px; text-align: center;"><strong>System Generated</strong></td>';
            $html .= '<td style="border: 1px solid #ddd; padding: 8px; text-align: center;"><em>Auto-calculated</em></td>';
            $html .= '</tr>';
        }
        
        $html .= '</tbody></table>';
    }
    
    // Performance Summary
    $html .= '<div class="performance-summary" style="border: 2px solid #28a745; padding: 15px; margin-bottom: 20px; background-color: #f8fff9;">';
    $html .= '<h3 style="margin-top: 0; color: #28a745; font-size: 16px;">PERFORMANCE SUMMARY</h3>';
    $html .= '<div style="display: table; width: 100%;">';
    $html .= '<div style="display: table-cell; width: 25%; text-align: center; padding: 10px; border: 1px solid #ddd;">';
    $html .= '<div style="font-size: 24px; font-weight: bold; color: #2c5aa0;">' . $student_data['total_subjects'] . '</div>';
    $html .= '<div style="font-size: 12px; color: #666;">Total Subjects</div>';
    $html .= '</div>';
    $html .= '<div style="display: table-cell; width: 25%; text-align: center; padding: 10px; border: 1px solid #ddd;">';
    $html .= '<div style="font-size: 24px; font-weight: bold; color: #2c5aa0;">' . number_format($student_data['total_marks'], 1) . '</div>';
    $html .= '<div style="font-size: 12px; color: #666;">Total Marks</div>';
    $html .= '</div>';
    $html .= '<div style="display: table-cell; width: 25%; text-align: center; padding: 10px; border: 1px solid #ddd;">';
    $html .= '<div style="font-size: 24px; font-weight: bold; color: #2c5aa0;">' . number_format($student_data['average_mark'], 1) . '%</div>';
    $html .= '<div style="font-size: 12px; color: #666;">Average</div>';
    $html .= '</div>';
    $html .= '<div style="display: table-cell; width: 25%; text-align: center; padding: 10px; border: 1px solid #ddd;">';
    $html .= '<div style="font-size: 24px; font-weight: bold; color: #2c5aa0;">' . $student_data['class_rank'] . '</div>';
    $html .= '<div style="font-size: 12px; color: #666;">Class Rank</div>';
    $html .= '</div>';
    $html .= '</div>';
    $html .= '</div>';
    
    // Include remarks section for S5-S6 students, comments and grade descriptors for S1-S4
    $class_level = getClassLevel($class_info['class_name']);
    if ($class_level === 'senior_level') {
        // S5-S6: Original remarks section
        $html .= '<div class="remarks-section" style="margin-bottom: 20px;">';
        $html .= '<div style="display: table; width: 100%;">';
        $html .= '<div style="display: table-cell; width: 50%; padding-right: 10px;">';
        $html .= '<div style="border: 1px solid #ddd; padding: 10px; min-height: 80px;">';
        $html .= '<strong>Class Teacher\'s Remarks:</strong><br>';
        $html .= '<em>Student shows good progress and actively participates in class activities.</em>';
        $html .= '</div>';
        $html .= '</div>';
        $html .= '<div style="display: table-cell; width: 50%; padding-left: 10px;">';
        $html .= '<div style="border: 1px solid #ddd; padding: 10px; min-height: 80px;">';
        $html .= '<strong>Headmaster\'s Remarks:</strong><br>';
        $html .= '<em>Continue working hard and maintain excellent standards.</em>';
        $html .= '</div>';
        $html .= '</div>';
        $html .= '</div>';
        $html .= '</div>';
    } else {
        // S1-S4: COMMENTS and GRADE DESCRIPTORS sections - Compact Version
        // COMMENTS Section
        $html .= '<div style="margin-bottom: 10px;">';
        $html .= '<div style="background: linear-gradient(135deg, #4fc3f7 0%, #29b6f6 100%); color: white; padding: 6px 12px; font-size: 9px; font-weight: bold; text-align: center; border-radius: 4px 4px 0 0;">COMMENTS</div>';
        $html .= '<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 8px; padding: 8px; background: white; border: 1px solid #e9ecef; border-top: none;">';
        
        $html .= '<div style="background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 4px; padding: 8px;">';
        $html .= '<div style="font-size: 8px; font-weight: bold; color: #2c5aa0; margin-bottom: 4px;">Class Teacher Remarks:</div>';
        $html .= '<div style="font-size: 7px; line-height: 1.2; color: #495057; min-height: 20px; margin-bottom: 6px;">Aim higher next time</div>';
        $html .= '<div style="font-size: 6px; color: #6c757d; border-top: 1px solid #dee2e6; padding-top: 4px;">Signature: ________________<br>Date: ' . date('Y-m-d') . '</div>';
        $html .= '</div>';
        
        $html .= '<div style="background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 4px; padding: 8px;">';
        $html .= '<div style="font-size: 8px; font-weight: bold; color: #2c5aa0; margin-bottom: 4px;">Head Teacher Remarks:</div>';
        $html .= '<div style="font-size: 7px; line-height: 1.2; color: #495057; min-height: 20px; margin-bottom: 6px;">Basic pass! keep working to improve</div>';
        $html .= '<div style="font-size: 6px; color: #6c757d; border-top: 1px solid #dee2e6; padding-top: 4px;">Signature: ________________<br>Date: ' . date('Y-m-d') . '</div>';
        $html .= '</div>';
        
        $html .= '</div>';
        $html .= '</div>';

        // GRADE DESCRIPTORS Section
        $html .= '<div style="margin-bottom: 10px;">';
        $html .= '<div style="background: linear-gradient(135deg, #4fc3f7 0%, #29b6f6 100%); color: white; padding: 6px 12px; font-size: 9px; font-weight: bold; text-align: center; border-radius: 4px 4px 0 0;">GRADE DESCRIPTORS</div>';
        $html .= '<div style="padding: 8px; background: white; border: 1px solid #e9ecef; border-top: none;">';
        $html .= '<table style="width: 100%; border-collapse: collapse; font-size: 7px;">';
        $html .= '<thead>';
        $html .= '<tr>';
        $html .= '<th style="background-color: #2c5aa0; color: white; padding: 4px; text-align: center; border: 1px solid #ddd; font-size: 7px;">GRADE</th>';
        $html .= '<th style="background-color: #2c5aa0; color: white; padding: 4px; text-align: center; border: 1px solid #ddd; font-size: 7px;">SCORE RANGE</th>';
        $html .= '<th style="background-color: #2c5aa0; color: white; padding: 4px; text-align: center; border: 1px solid #ddd; font-size: 7px;">GRADE DESCRIPTOR</th>';
        $html .= '</tr>';
        $html .= '</thead>';
        $html .= '<tbody>';
        
        $grade_descriptors = [
            ['grade' => 'A', 'range' => '80 - 100', 'desc' => 'Exceptional - Extraordinary competency'],
            ['grade' => 'B', 'range' => '70 - 79', 'desc' => 'Outstanding - High level competency'],
            ['grade' => 'C', 'range' => '60 - 69', 'desc' => 'Satisfactory - Adequate competency'],
            ['grade' => 'D', 'range' => '50 - 59', 'desc' => 'Basic - Minimum competency'],
            ['grade' => 'E', 'range' => '<49', 'desc' => 'Elementary - Below basic competency']
        ];
        
        foreach ($grade_descriptors as $gd) {
            $html .= '<tr>';
            $html .= '<td style="padding: 3px; text-align: center; border: 1px solid #ddd; font-weight: bold; font-size: 7px;">' . $gd['grade'] . '</td>';
            $html .= '<td style="padding: 3px; text-align: center; border: 1px solid #ddd; font-size: 7px;">' . $gd['range'] . '</td>';
            $html .= '<td style="padding: 3px; border: 1px solid #ddd; line-height: 1.2; font-size: 6px;">' . $gd['desc'] . '</td>';
            $html .= '</tr>';
        }
        
        $html .= '</tbody></table>';
        $html .= '</div>';
        $html .= '</div>';
    }
    
    // Footer with QR Code and Date
    $html .= '<div class="report-footer" style="border-top: 2px solid #2c5aa0; padding-top: 15px; text-align: center; color: #666; font-size: 12px;">';
    $html .= '<div style="margin-bottom: 10px;">Generated on: ' . date('Y-m-d H:i:s') . '</div>';
    $html .= '<div style="font-size: 10px; color: #999;">This report was generated electronically and is valid without signature.</div>';
    $html .= '</div>';
    
    $html .= '</div>';
    
    return $html;
}

/**
 * Generate complete professional CSS for PDF
 */
function generateCompletePDFCSS() {
    return '
    <style>
        @page {
            margin: 15mm;
            size: A4;
        }
        
        body {
            font-family: "Arial", sans-serif;
            margin: 0;
            padding: 0;
            font-size: 11pt;
            line-height: 1.4;
            color: #000;
        }
        
        .report-card {
            border: 2px solid #2c5aa0;
            padding: 20px;
            margin-bottom: 20px;
            background: #fff;
            width: 100%;
            box-sizing: border-box;
            page-break-inside: avoid;
        }
        
        .school-header h1 {
            font-size: 24pt;
            margin: 5px 0;
        }
        
        .school-header h2 {
            font-size: 18pt;
            margin: 5px 0;
        }
        
        .student-info-box {
            border: 2px solid #2c5aa0;
            padding: 15px;
            margin-bottom: 20px;
            background-color: #f8f9fa;
        }
        
        .grades-table {
            width: 100%;
            border-collapse: collapse;
            margin: 15px 0;
            font-size: 10pt;
        }
        
        .grades-table th,
        .grades-table td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: center;
        }
        
        .grades-table th {
            background-color: #2c5aa0;
            color: white;
            font-weight: bold;
        }
        
        .grades-table td:first-child {
            text-align: left;
            font-weight: bold;
        }
        
        .performance-summary {
            border: 2px solid #28a745;
            padding: 15px;
            margin-bottom: 20px;
            background-color: #f8fff9;
        }
        
        .performance-summary h3 {
            margin-top: 0;
            color: #28a745;
            font-size: 16pt;
        }
        
        .remarks-section {
            margin-bottom: 20px;
        }
        
        .report-footer {
            border-top: 2px solid #2c5aa0;
            padding-top: 15px;
            text-align: center;
            color: #666;
            font-size: 10pt;
        }
        
        /* Print Styles */
        @media print {
            body {
                font-size: 10pt;
                line-height: 1.3;
            }
            
            .no-print {
                display: none !important;
            }
            
            .print-button-container {
                display: none !important;
            }
            
            .report-card {
                border: 1px solid #333;
                padding: 15px;
                margin-bottom: 15px;
                page-break-inside: avoid;
            }
            
            .school-header {
                border-bottom: 2px solid #333;
                margin-bottom: 15px;
            }
            
            .grades-table th {
                background-color: #f0f0f0 !important;
                color: #000 !important;
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
            }
            
            .performance-summary {
                border: 1px solid #333;
                background-color: #f9f9f9 !important;
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
            }
            
            .student-info-box {
                border: 1px solid #333;
                background-color: #f9f9f9 !important;
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
            }
            
            .remarks-section div {
                border: 1px solid #333;
            }
            
            @page {
                margin: 12mm;
                size: A4 portrait;
            }
        }
        
        /* Print Buttons */
        .print-button-container {
            text-align: center;
            margin: 20px 0;
            padding: 15px;
            background-color: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 5px;
        }
        
        .print-button {
            background-color: #28a745;
            color: white;
            border: none;
            padding: 12px 24px;
            font-size: 16px;
            cursor: pointer;
            border-radius: 5px;
            margin: 0 10px;
            transition: background-color 0.3s;
        }
        
        .print-button:hover {
            background-color: #218838;
        }
        
        .print-button.secondary {
            background-color: #6c757d;
        }
        
        .print-button.secondary:hover {
            background-color: #5a6268;
        }
    </style>';
}

/**
 * Generate JavaScript for print functionality
 */
function generatePrintJavaScript() {
    return '
    <script>
        // Print single report card
        function printSingleReport(reportId) {
            // Show only the specific report card
            document.querySelectorAll(".report-card").forEach(function(card) {
                card.style.display = "none";
            });
            
            var targetReport = document.getElementById(reportId);
            if (targetReport) {
                targetReport.style.display = "block";
                // Add print button that will be hidden in print
                var printBtn = targetReport.querySelector(".print-single-btn");
                if (printBtn) printBtn.style.display = "none";
            }
            
            // Wait for DOM update then print
            setTimeout(function() {
                window.print();
                // Restore all cards after printing
                setTimeout(function() {
                    document.querySelectorAll(".report-card").forEach(function(card) {
                        card.style.display = "block";
                    });
                    if (targetReport && printBtn) {
                        printBtn.style.display = "inline-block";
                    }
                }, 100);
            }, 100);
        }
        
        // Print all report cards
        function printAllReports() {
            // Hide all print buttons before printing
            document.querySelectorAll(".print-button, .print-single-btn").forEach(function(btn) {
                btn.style.display = "none";
            });
            
            // Print the page
            window.print();
            
            // Show all print buttons after printing
            setTimeout(function() {
                document.querySelectorAll(".print-button, .print-single-btn").forEach(function(btn) {
                    btn.style.display = "inline-block";
                });
            }, 100);
        }
        
        // Print current page
        function printCurrentPage() {
            // Hide navigation and controls
            document.querySelectorAll(".navigation, .controls, .print-button").forEach(function(element) {
                if (element) element.style.display = "none";
            });
            
            // Print the page
            window.print();
            
            // Show navigation and controls after printing
            setTimeout(function() {
                document.querySelectorAll(".navigation, .controls, .print-button").forEach(function(element) {
                    if (element) element.style.display = "block";
                });
            }, 100);
        }
        
        // Initialize print functionality when page loads
        document.addEventListener("DOMContentLoaded", function() {
            // Add print button to navigation
            var nav = document.querySelector(".navigation");
            if (nav) {
                var printBtn = document.createElement("button");
                printBtn.className = "print-button";
                printBtn.innerHTML = "🖨️ Print All";
                printBtn.onclick = printAllReports;
                nav.appendChild(printBtn);
            }
        });
    </script>';
}

// =============================================================================
// 4. FALLBACK AND UTILITY FUNCTIONS
// =============================================================================

/**
 * Generate printable HTML fallback when dompdf is not available
 */
function generatePrintableHTML($connection, $academic_year, $term, $exam_id, $class_id, $student_ids = []) {
    $html = generateCompletePDFCSS() . '<body>';
    
    // Add print button container
    $html .= '<div class="print-button-container no-print">';
    $html .= '<button class="print-button" onclick="window.print()">🖨️ Print Report</button>';
    $html .= '<button class="print-button secondary" onclick="window.close()">✖️ Close</button>';
    $html .= '</div>';
    
    $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 .= '<p>Alternatively, contact your system administrator to install the dompdf library.</p>';
    $html .= '</div>';
    
    // Add JavaScript for print functionality
    $html .= generatePrintJavaScript();
    $html .= '</body></html>';
    
    return [
        'success' => true,
        'html_content' => $html,
        'filename' => 'report_preview.html'
    ];
}

// =============================================================================
// 5. S3-4 SPECIFIC FUNCTIONS
// =============================================================================

/**
 * Generate S3-4 specific PDF HTML
 */
function generateS34PDFHTML($report_data, $academic_year, $term, $school_id) {
    $html = '
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <style>
            @page { margin: 15mm; size: A4; }
            body { font-family: Arial, sans-serif; margin: 0; padding: 20px; }
            .header { text-align: center; border-bottom: 3px solid #2c5aa0; padding-bottom: 15px; margin-bottom: 20px; }
            .student-info { background: #f8f9fa; padding: 15px; border: 1px solid #ddd; margin-bottom: 20px; }
            .summary { display: flex; justify-content: space-around; margin: 20px 0; }
            .summary-item { text-align: center; padding: 10px; border: 1px solid #ddd; background: #fff; }
            .subjects-table { width: 100%; border-collapse: collapse; margin: 20px 0; }
            .subjects-table th, .subjects-table td { border: 1px solid #ddd; padding: 8px; text-align: left; }
            .subjects-table th { background: #495057; color: white; }
            .grade-badge { padding: 4px 8px; border-radius: 4px; font-weight: bold; text-align: center; }
            .grade-a-plus { background: #d4edda; color: #155724; }
            .grade-a { background: #c3e6cb; color: #155724; }
            .grade-b { background: #fff3cd; color: #856404; }
            .grade-c { background: #ffeaa7; color: #856404; }
            .grade-d { background: #f8d7da; color: #721c24; }
            .grade-e { background: #f5c6cb; color: #721c24; }
            .grade-f { background: #f1b0b7; color: #721c24; }
        </style>
    </head>
    <body>
        <div class="header">
            <h1>S3-4 ACADEMIC REPORT</h1>
            <p>' . htmlspecialchars($report_data['student']['class_name']) . ' - ' . htmlspecialchars($term . ' ' . $academic_year) . '</p>
        </div>
        
        <div class="student-info">
            <strong>Student:</strong> ' . htmlspecialchars($report_data['student']['username']) . '<br>
            <strong>Admission No:</strong> ' . htmlspecialchars($report_data['student']['ADM']) . '<br>
            <strong>Class:</strong> ' . htmlspecialchars($report_data['student']['class_name']) . '<br>
            <strong>Stream:</strong> ' . htmlspecialchars($report_data['student']['stream_name']) . '<br>
        </div>
        
        <div class="summary">
            <div class="summary-item">
                <div style="font-size: 20px; font-weight: bold;">' . $report_data['summary']['total_subjects'] . '</div>
                <div>Total Subjects</div>
            </div>
            <div class="summary-item">
                <div style="font-size: 20px; font-weight: bold;">' . $report_data['summary']['compulsory_count'] . '</div>
                <div>Compulsory</div>
            </div>
            <div class="summary-item">
                <div style="font-size: 20px; font-weight: bold;">' . $report_data['summary']['optional_count'] . '</div>
                <div>Optional</div>
            </div>
            <div class="summary-item">
                <div style="font-size: 20px; font-weight: bold;">' . $report_data['summary']['average_mark'] . '%</div>
                <div>Average</div>
            </div>
        </div>
        
        <table class="subjects-table">
            <thead>
                <tr>
                    <th>Subject Code</th>
                    <th>Subject Name</th>
                    <th>Category</th>
                    <th>Marks (%)</th>
                    <th>Grade</th>
                    <th>Teacher</th>
                </tr>
            </thead>
            <tbody>';
    
    foreach ($report_data['subjects'] as $subject) {
        $grade_class = 'grade-na';
        if (strtolower($subject['grade']) == 'a+') $grade_class = 'grade-a-plus';
        elseif (strtolower($subject['grade']) == 'a') $grade_class = 'grade-a';
        elseif (strtolower($subject['grade']) == 'b') $grade_class = 'grade-b';
        elseif (strtolower($subject['grade']) == 'c') $grade_class = 'grade-c';
        elseif (strtolower($subject['grade']) == 'd') $grade_class = 'grade-d';
        elseif (strtolower($subject['grade']) == 'e') $grade_class = 'grade-e';
        elseif (strtolower($subject['grade']) == 'f') $grade_class = 'grade-f';
        
        $html .= '
                <tr>
                    <td>' . htmlspecialchars($subject['subject_code']) . '</td>
                    <td>' . htmlspecialchars($subject['subject_name']) . '</td>
                    <td>' . htmlspecialchars($subject['subject_category']) . '</td>
                    <td>' . ($subject['mark'] !== null ? number_format($subject['mark'], 1) : 'N/A') . '</td>
                    <td><div class="grade-badge ' . $grade_class . '">' . htmlspecialchars($subject['grade']) . '</div></td>
                    <td>' . htmlspecialchars($subject['teacher_name'] ?? 'Not Assigned') . '</td>
                </tr>';
    }
    
    // Calculate average score and grade for S3-4
    $valid_marks_s34 = [];
    $total_subjects_s34 = count($report_data['subjects']); // Total number of subjects student is taking
    foreach ($report_data['subjects'] as $subject) {
        if ($subject['mark'] !== null && is_numeric($subject['mark'])) {
            $valid_marks_s34[] = (float)$subject['mark'];
        }
    }
    
    if (!empty($valid_marks_s34)) {
        $total_marks_s34 = array_sum($valid_marks_s34);
        $average_score_s34 = round($total_marks_s34 / $total_subjects_s34, 1); // Divide by total subjects, not subjects with marks
        
        // Determine grade based on average score
        $average_grade_s34 = 'F';
        if ($average_score_s34 >= 80) $average_grade_s34 = 'A';
        elseif ($average_score_s34 >= 75) $average_grade_s34 = 'B+';
        elseif ($average_score_s34 >= 70) $average_grade_s34 = 'B';
        elseif ($average_score_s34 >= 65) $average_grade_s34 = 'C+';
        elseif ($average_score_s34 >= 60) $average_grade_s34 = 'C';
        elseif ($average_score_s34 >= 55) $average_grade_s34 = 'D+';
        elseif ($average_score_s34 >= 50) $average_grade_s34 = 'D';
        elseif ($average_score_s34 >= 45) $average_grade_s34 = 'E';
        else $average_grade_s34 = 'F';
        
        $html .= '
                <tr style="background-color: #e3f2fd; font-weight: bold; border-top: 2px solid #1976d2;">
                    <td colspan="3" style="text-align: right;"><strong>AVERAGE SCORE:</strong></td>
                    <td style="font-size: 14px;"><strong>' . $average_score_s34 . '</strong></td>
                    <td><div class="grade-badge" style="background: linear-gradient(45deg, #1976d2, #0d47a1); color: white; font-weight: bold; font-size: 12px;">' . $average_grade_s34 . '</div></td>
                    <td><em>System Generated</em></td>
                </tr>';
    }
    
    $html .= '
            </tbody>
        </table>
        
        <div style="margin-top: 30px; text-align: center; color: #666; font-size: 12px;">
            <p>Generated on: ' . date('Y-m-d H:i:s') . '</p>
            <p>This report was generated electronically and is valid without signature.</p>
        </div>
    </body>
    </html>';
    
    return $html;
}

?>

<?php
// Display S3-4 report card if requested
if (!empty($s34_student_adm) && !empty($s34_class_id) && !empty($s34_stream_id)):
    $report_data = $s34_report_data;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>S3-4 Report Card - <?php echo htmlspecialchars($report_data['student']['username'] ?? ''); ?></title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f8f9fa;
            margin: 0;
            padding: 20px;
        }
        .report-container {
            max-width: 1000px;
            margin: 0 auto;
            background: white;
            border-radius: 10px;
            box-shadow: 0 0 20px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        .report-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }
        .school-logo {
            width: 80px;
            height: 80px;
            margin: 0 auto 15px;
            border-radius: 50%;
            background: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 30px;
            color: #667eea;
        }
        .student-info {
            background: #f8f9fa;
            padding: 25px;
            border-bottom: 1px solid #dee2e6;
        }
        .info-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
        }
        .info-item {
            display: flex;
            align-items: center;
        }
        .info-label {
            font-weight: 600;
            color: #495057;
            min-width: 120px;
            margin-right: 15px;
        }
        .info-value {
            color: #212529;
            font-weight: 500;
        }
        .subjects-section {
            padding: 30px;
        }
        .subjects-table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            border-radius: 8px;
            overflow: hidden;
        }
        .subjects-table th {
            background: #495057;
            color: white;
            padding: 15px 12px;
            text-align: left;
            font-weight: 600;
        }
        .subjects-table td {
            padding: 15px 12px;
            border-bottom: 1px solid #dee2e6;
        }
        .subjects-table tbody tr:hover {
            background-color: #f8f9fa;
        }
        .subject-badge {
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 11px;
            font-weight: 600;
            text-transform: uppercase;
        }
        .badge-compulsory {
            background: #dc3545;
            color: white;
        }
        .badge-optional {
            background: #28a745;
            color: white;
        }
        .badge-both {
            background: #6f42c1;
            color: white;
        }
        .grade-display {
            font-weight: 700;
            font-size: 16px;
            text-align: center;
            border-radius: 6px;
            padding: 8px 12px;
        }
        .grade-a-plus { background: #d4edda; color: #155724; }
        .grade-a { background: #c3e6cb; color: #155724; }
        .grade-b { background: #fff3cd; color: #856404; }
        .grade-c { background: #ffeaa7; color: #856404; }
        .grade-d { background: #f8d7da; color: #721c24; }
        .grade-e { background: #f5c6cb; color: #721c24; }
        .grade-f { background: #f1b0b7; color: #721c24; }
        .grade-na { background: #e2e3e5; color: #6c757d; }
        .summary-cards {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin: 30px 0;
        }
        .summary-card {
            background: white;
            border-radius: 10px;
            padding: 20px;
            text-align: center;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            border: 1px solid #dee2e6;
        }
        .summary-number {
            font-size: 2.5rem;
            font-weight: 700;
            color: #495057;
            margin-bottom: 5px;
        }
        .summary-label {
            color: #6c757d;
            font-size: 0.9rem;
            text-transform: uppercase;
            font-weight: 600;
        }
        .action-buttons {
            text-align: center;
            padding: 20px;
            background: #f8f9fa;
            border-top: 1px solid #dee2e6;
        }
        .btn-custom {
            margin: 0 10px;
            padding: 12px 25px;
            border: none;
            border-radius: 6px;
            font-weight: 600;
            text-decoration: none;
            display: inline-block;
            transition: all 0.3s;
        }
        .btn-primary {
            background: #007bff;
            color: white;
        }
        .btn-primary:hover {
            background: #0056b3;
        }
        .btn-success {
            background: #28a745;
            color: white;
        }
        .btn-success:hover {
            background: #1e7e34;
        }
    </style>
</head>
<body>
    <div class="report-container">
        <!-- Header -->
        <div class="report-header">
            <div class="school-logo">
                <i class="fas fa-graduation-cap"></i>
            </div>
            <h1>S3-4 ACADEMIC REPORT</h1>
            <h3><?php echo htmlspecialchars($report_data['student']['class_name'] ?? ''); ?> - <?php echo htmlspecialchars($s34_term . ' ' . $s34_academic_year); ?></h3>
        </div>

        <!-- Student Information -->
        <div class="student-info">
            <div class="info-grid">
                <div class="info-item">
                    <span class="info-label">Student Name:</span>
                    <span class="info-value"><?php echo htmlspecialchars($report_data['student']['username'] ?? ''); ?></span>
                </div>
                <div class="info-item">
                    <span class="info-label">Admission No:</span>
                    <span class="info-value"><?php echo htmlspecialchars($report_data['student']['ADM'] ?? ''); ?></span>
                </div>
                <div class="info-item">
                    <span class="info-label">Class:</span>
                    <span class="info-value"><?php echo htmlspecialchars($report_data['student']['class_name'] ?? ''); ?></span>
                </div>
                <div class="info-item">
                    <span class="info-label">Stream:</span>
                    <span class="info-value"><?php echo htmlspecialchars($report_data['student']['stream_name'] ?? ''); ?></span>
                </div>
            </div>
        </div>

        <!-- Performance Summary -->
        <div class="subjects-section">
            <h3 class="mb-4"><i class="fas fa-chart-line me-2"></i>Performance Summary</h3>
            <div class="summary-cards">
                <div class="summary-card">
                    <div class="summary-number"><?php echo $report_data['summary']['total_subjects']; ?></div>
                    <div class="summary-label">Total Subjects</div>
                </div>
                <div class="summary-card">
                    <div class="summary-number"><?php echo $report_data['summary']['compulsory_count']; ?></div>
                    <div class="summary-label">Compulsory</div>
                </div>
                <div class="summary-card">
                    <div class="summary-number"><?php echo $report_data['summary']['optional_count']; ?></div>
                    <div class="summary-label">Optional</div>
                </div>
                <div class="summary-card">
                    <div class="summary-number"><?php echo $report_data['summary']['average_mark']; ?>%</div>
                    <div class="summary-label">Average</div>
                </div>
            </div>

            <h3 class="mt-5 mb-4"><i class="fas fa-book me-2"></i>Subjects and Grades</h3>
            <table class="subjects-table">
                <thead>
                    <tr>
                        <th>Subject Code</th>
                        <th>Subject Name</th>
                        <th>Category</th>
                        <th>Marks (%)</th>
                        <th>Grade</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($report_data['subjects'] as $subject): ?>
                    <tr>
                        <td><strong><?php echo htmlspecialchars($subject['subject_code'] ?? ''); ?></strong></td>
                        <td><?php echo htmlspecialchars($subject['subject_name']); ?></td>
                        <td>
                            <span class="subject-badge badge-<?php 
                                if ($subject['subject_category'] == 'Compulsory') echo 'compulsory';
                                elseif ($subject['subject_category'] == 'Optional') echo 'optional';
                                else echo 'both';
                            ?>">
                                <?php echo htmlspecialchars($subject['subject_category']); ?>
                            </span>
                        </td>
                        <td><?php echo $subject['mark'] !== null ? number_format($subject['mark'], 1) : 'N/A'; ?></td>
                        <td>
                            <div class="grade-display grade-<?php echo strtolower(str_replace('+', '', $subject['grade'])); ?>">
                                <?php echo htmlspecialchars($subject['grade']); ?>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <!-- Action Buttons -->
        <div class="action-buttons">
            <button onclick="window.print()" class="btn-custom btn-primary">
                <i class="fas fa-print me-2"></i>Print Report
            </button>
            <a href="admin_reports_printouts.php" class="btn-custom btn-primary">
                <i class="fas fa-arrow-left me-2"></i>Back to Reports
            </a>
        </div>
    </div>

    <script>
        // Print functionality
        function printReport() {
            window.print();
        }
    </script>
</body>
</html>
<?php
exit;
endif;
?>

<?php
// =============================================================================
// 6. S3-4 TESTING AND DEMONSTRATION
// =============================================================================

// If this is a test request, show test results
if (isset($_GET['test_s34']) && $_GET['test_s34'] == '1') {
    echo "<!DOCTYPE html><html><head><title>S3-4 Test Results</title>";
    echo "<link rel='stylesheet' href='https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css'>";
    echo "</head><body class='p-4'>";
    
    echo "<div class='container'>";
    echo "<h1 class='mb-4'>S3-4 Report Card System Test</h1>";
    
    // Test with the provided parameters
    $test_student_adm = 'SMK205323';
    $test_class_id = 61;
    $test_stream_id = 41;
    $test_school_id = 2;
    $test_academic_year = '2025';
    $test_term = 'TERM 3';
    
    echo "<h2>Test Parameters</h2>";
    echo "<ul>";
    echo "<li><strong>Student ADM:</strong> " . htmlspecialchars($test_student_adm) . "</li>";
    echo "<li><strong>Class ID:</strong> " . $test_class_id . "</li>";
    echo "<li><strong>Stream ID:</strong> " . $test_stream_id . "</li>";
    echo "<li><strong>School ID:</strong> " . $test_school_id . "</li>";
    echo "<li><strong>Academic Year:</strong> " . htmlspecialchars($test_academic_year) . "</li>";
    echo "<li><strong>Term:</strong> " . htmlspecialchars($test_term) . "</li>";
    echo "</ul>";
    
    // Generate report data
    $test_data = generateS34ReportCard(
        $connection,
        $test_student_adm,
        $test_class_id,
        $test_stream_id,
        $test_school_id,
        $test_academic_year,
        $test_term
    );
    
    if ($test_data['success']) {
        echo "<h2>Test Results - SUCCESS</h2>";
        
        echo "<div class='row mb-4'>";
        echo "<div class='col-md-6'>";
        echo "<h4>Student Information</h4>";
        echo "<p><strong>Name:</strong> " . htmlspecialchars($test_data['student']['username']) . "</p>";
        echo "<p><strong>ADM:</strong> " . htmlspecialchars($test_data['student']['ADM']) . "</p>";
        echo "<p><strong>Class:</strong> " . htmlspecialchars($test_data['student']['class_name']) . "</p>";
        echo "<p><strong>Stream:</strong> " . htmlspecialchars($test_data['student']['stream_name']) . "</p>";
        echo "</div>";
        
        echo "<div class='col-md-6'>";
        echo "<h4>Summary</h4>";
        echo "<p><strong>Total Subjects:</strong> " . $test_data['summary']['total_subjects'] . "</p>";
        echo "<p><strong>Compulsory Subjects:</strong> " . $test_data['summary']['compulsory_count'] . "</p>";
        echo "<p><strong>Optional Subjects:</strong> " . $test_data['summary']['optional_count'] . "</p>";
        echo "<p><strong>Average Mark:</strong> " . $test_data['summary']['average_mark'] . "%</p>";
        echo "</div>";
        echo "</div>";
        
        echo "<h4>Subjects Loaded:</h4>";
        echo "<div class='table-responsive'>";
        echo "<table class='table table-striped'>";
        echo "<thead><tr><th>Code</th><th>Name</th><th>Category</th><th>Mark</th><th>Grade</th></tr></thead>";
        echo "<tbody>";
        
        foreach ($test_data['subjects'] as $subject) {
            $badge_class = $subject['is_compulsory'] ? 'bg-danger' : 'bg-success';
            if ($subject['subject_category'] == 'Compulsory & Optional') $badge_class = 'bg-primary';
            
            echo "<tr>";
            echo "<td>" . htmlspecialchars($subject['subject_code'] ?? '') . "</td>";
            echo "<td>" . htmlspecialchars($subject['subject_name']) . "</td>";
            echo "<td><span class='badge {$badge_class}'>" . htmlspecialchars($subject['subject_category']) . "</span></td>";
            echo "<td>" . ($subject['mark'] !== null ? number_format($subject['mark'], 1) : 'N/A') . "</td>";
            echo "<td>" . htmlspecialchars($subject['grade']) . "</td>";
            echo "</tr>";
        }
        
        echo "</tbody></table>";
        echo "</div>";
        
        echo "<div class='mt-4'>";
        echo "<h4>Test URL:</h4>";
        echo "<a href='?student_adm=" . urlencode($test_student_adm) . "&s34_class_id=" . $test_class_id . "&s34_stream_id=" . $test_stream_id . "&s34_school_id=" . $test_school_id . "&s34_academic_year=" . urlencode($test_academic_year) . "&s34_term=" . urlencode($test_term) . "' class='btn btn-success'>View S3-4 Report Card</a>";
        echo "</div>";
        
    } else {
        echo "<div class='alert alert-danger'>";
        echo "<h4>Test Failed</h4>";
        echo "<p><strong>Error:</strong> " . htmlspecialchars($test_data['error']) . "</p>";
        echo "</div>";
    }
    
    echo "</div></body></html>";
    exit;
}
?>

<?php