<?php
session_start();
include 'config.php';
require_once 'vendor/autoload.php';

use Dompdf\Dompdf;
use Dompdf\Options;

// Create database connection
$connection = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);

if ($connection->connect_error) {
    die("Connection failed: " . $connection->connect_error);
}

// 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'] ?? '';
$download_type = $_GET['download_type'] ?? 'all';

if (empty($academic_year) || empty($term) || empty($exam_id) || empty($class_id)) {
    die("Missing required parameters");
}

// 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) {
    die("Class not found");
}

$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) {
    die("School not found");
}

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

if (!$exam) {
    die("Exam not found");
}

// Get students
if ($download_type === 'single' && !empty($student_id)) {
    $sql_students = "SELECT id as user_id, username as student_name, ADM, parent_name, parent_phone, role, class_id, school_id, photo
                     FROM users WHERE id = ? AND class_id = ? AND school_id = ? AND role != 1";
    $stmt_students = $connection->prepare($sql_students);
    $stmt_students->bind_param("iii", $student_id, $class_id, $class_school_id);
} else {
    $sql_students = "SELECT id as user_id, username as student_name, ADM, parent_name, parent_phone, role, class_id, school_id, photo
                     FROM users WHERE class_id = ? AND school_id = ? AND role != 1 ORDER BY 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;
}

// Grade function - exact copy from original
function getGradeFromScale($mark, $subject_id, $class_id, $academic_year, $term, $school_id, $connection) {
    $grade_info = ['grade' => '', 'remarks' => ''];
    
    if ($mark === null) return $grade_info;
    
    try {
        $term_variations = [
            $term,
            ucfirst(strtolower($term)),
            str_replace('TERM', 'Term', $term),
            str_replace('Term', 'TERM', $term),
            'Term 2',
            'TERM 2'
        ];
        
        $found_grade = false;
        
        foreach ($term_variations as $term_variant) {
            $sql_grade = "
            SELECT grade_letter, remarks, term_name
            FROM grading_scales 
            WHERE school_id = ? 
            AND academic_year = ? 
            AND term_name = ? 
            AND (class_id = ? OR class_id = 0)
            AND (subject_id = ? OR subject_id = 0)
            AND ? >= min_score AND ? <= max_score
            ORDER BY subject_id DESC, class_id DESC
            LIMIT 1";
            
            $stmt_grade = $connection->prepare($sql_grade);
            $stmt_grade->bind_param("issiidi", $school_id, $academic_year, $term_variant, $class_id, $subject_id, $mark, $mark);
            $stmt_grade->execute();
            $result_grade = $stmt_grade->get_result();
            
            if ($row = $result_grade->fetch_assoc()) {
                $grade_info['grade'] = $row['grade_letter'];
                $grade_info['remarks'] = $row['remarks'];
                $found_grade = true;
                break;
            }
        }
        
        if (!$found_grade) {
            if ($mark >= 90) { $grade_info['grade'] = 'A+'; $grade_info['remarks'] = 'Excellent'; }
            elseif ($mark >= 80) { $grade_info['grade'] = 'A'; $grade_info['remarks'] = 'Very Good'; }
            elseif ($mark >= 70) { $grade_info['grade'] = 'B'; $grade_info['remarks'] = 'Good'; }
            elseif ($mark >= 60) { $grade_info['grade'] = 'C'; $grade_info['remarks'] = 'Average'; }
            elseif ($mark >= 50) { $grade_info['grade'] = 'D'; $grade_info['remarks'] = 'Below Average'; }
            else { $grade_info['grade'] = 'F'; $grade_info['remarks'] = 'Needs Improvement'; }
        }
    } catch (Exception $e) {
        if ($mark >= 80) { $grade_info['grade'] = 'A'; $grade_info['remarks'] = 'Excellent'; }
        elseif ($mark >= 70) { $grade_info['grade'] = 'B'; $grade_info['remarks'] = 'Good'; }
        elseif ($mark >= 60) { $grade_info['grade'] = 'C'; $grade_info['remarks'] = 'Average'; }
        else { $grade_info['grade'] = 'D'; $grade_info['remarks'] = 'Needs Improvement'; }
    }
    
    return $grade_info;
}

// Generate HTML exactly matching original design
function generateExactPDFHTML($students, $school, $class_name, $exam, $academic_year, $term, $class_id, $class_school_id, $connection) {
    $html = '
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Report Cards - ' . htmlspecialchars($class_name) . '</title>
        <style>
            @page {
                size: A4;
                margin: 0;
            }
            
            body { 
                font-family: "Arial", sans-serif; 
                margin: 0; 
                padding: 0;
                min-height: 100vh;
                background: white;
            }

            /* New LORIKA-style Report Card - EXACT COPY */
            .report-card { 
                background: white; 
                margin: 0; 
                page-break-after: always;
                position: relative;
                /* A4 page sizing */
                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;
                /* Blue-Green Gradient Left Border */
                border-left: 20px solid;
                border-image: linear-gradient(to bottom, #28a745 0%, #20c997 50%, #007bff 100%) 1;
                box-shadow: none;
            }

            /* Header Section with Logo and School Details */
            .report-card-header {
                display: table;
                width: 100%;
                padding: 15mm 15mm 8mm 15mm;
                border-bottom: 2px solid #2c5aa0;
                table-layout: fixed;
            }

            .school-logo {
                display: table-cell;
                width: 60px;
                vertical-align: top;
            }

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

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

            .school-details {
                display: table-cell;
                text-align: right;
                color: black;
                font-weight: bold;
                vertical-align: top;
                padding-left: 20px;
            }

            .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, #2c5aa0 0%, #007bff 100%);
                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;
            }

            /* Performance Statistics Buttons */
            .performance-stats {
                display: table;
                width: calc(100% - 30mm);
                margin: 10px 15mm;
                table-layout: fixed;
                border-spacing: 10px;
            }

            .stat-btn {
                display: table-cell;
                background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
                color: white;
                padding: 8px 12px;
                border-radius: 8px;
                text-align: center;
                border: none;
                font-size: 9px;
                width: 33.33%;
            }

            .stat-value {
                display: block;
                font-size: 14px;
                font-weight: bold;
                margin-bottom: 2px;
            }

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

            /* Student Details and Performance Graph Section */
            .student-section {
                display: table;
                width: calc(100% - 30mm);
                padding: 8mm 15mm;
                table-layout: fixed;
                align-items: flex-start;
                border-left: 1px solid #007bff;
                background: linear-gradient(135deg, #e4ebf8ff 0%, #ffffff 100%);
            }

            .student-photo-column {
                display: table-cell;
                width: 80px;
                vertical-align: top;
            }

            .student-details {
                display: table-cell;
                padding-top: 10px;
                font-weight: bold;
                vertical-align: top;
                padding-left: 20px;
            }

            .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;
                border: 1px solid #ddd;
            }

            .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;
                margin-bottom: 8px;
            }

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

            .performance-graph {
                display: table-cell;
                width: 200px;
                background: #f8f9fb;
                border: 1px solid #ddd;
                border-radius: 8px;
                padding: 8px;
                height: 80px;
                vertical-align: top;
            }

            .chart-container {
                position: relative;
                height: 60px;
                margin: 2px 0;
                background: white;
                border-radius: 4px;
                display: flex;
                align-items: end;
                justify-content: space-around;
                padding: 5px;
            }

            .chart-bar {
                width: 12px;
                background: #2c5aa0;
                border-radius: 2px 2px 0 0;
                margin: 0 1px;
            }

            /* Examination Results Table */
            .results-section {
                margin: 0 15mm 10mm 15mm;
                border-left: 2px solid #28a745;
                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 #ddd;
                font-weight: bold;
            }

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

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

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

            /* Performance and Remarks Horizontal Container */
            .performance-remarks-container {
                display: table;
                width: calc(100% - 30mm);
                margin: 0 15mm 10mm 15mm;
                table-layout: fixed;
                border-spacing: 15px;
            }

            .performance-trends {
                display: table-cell;
                width: 300px;
                background: #f8f9fb;
                border: 1px solid #ddd;
                border-radius: 8px;
                padding: 10px;
                border-left: 4px solid #007bff;
                vertical-align: top;
            }

            .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;
                overflow: hidden;
            }

            .trend-line {
                position: absolute;
                bottom: 15px;
                left: 10%;
                right: 10%;
                height: 2px;
                background: linear-gradient(to right, #dc3545 0%, #ffc107 50%, #28a745 100%);
                border-radius: 1px;
            }

            .trend-point {
                position: absolute;
                width: 6px;
                height: 6px;
                background: #28a745;
                border-radius: 50%;
                border: 2px solid white;
                bottom: 13px;
            }

            .trend-point:nth-child(1) { left: 15%; }
            .trend-point:nth-child(2) { left: 50%; }
            .trend-point:nth-child(3) { left: 85%; }

            /* Remarks Section */
            .remarks-section {
                display: table-cell;
                vertical-align: top;
            }

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

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

            .remark-content {
                font-size: 9px;
                min-height: 25px;
                line-height: 1.3;
                border: 1px solid #ddd;
                padding: 8px;
                border-radius: 4px;
                background: #f9f9f9;
            }

            /* Footer Section */
            .report-footer {
                position: absolute;
                bottom: 10mm;
                left: 15mm;
                right: 15mm;
                display: table;
                width: calc(100% - 30mm);
            }

            .school-motto-footer {
                display: table-cell;
                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);
                width: 60%;
                vertical-align: middle;
            }

            .qr-code {
                display: table-cell;
                width: 50px;
                height: 50px;
                text-align: center;
                vertical-align: middle;
            }

            .qr-code-inner {
                width: 50px;
                height: 50px;
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                font-size: 8px;
                color: #2c5aa0;
                text-align: center;
                border: 2px solid #2c5aa0;
                border-radius: 8px;
                background: white;
                margin: 0 auto;
            }
            
            .qr-code img {
                max-width: 45px;
                max-height: 45px;
                border-radius: 4px;
            }

            /* School Logo Watermark */
            .report-card-watermark {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                z-index: -1;
                opacity: 0.05;
                width: 400px;
                height: 400px;
                background-size: contain;
                background-repeat: no-repeat;
                background-position: center;
                pointer-events: none;
                font-size: 48px;
                font-weight: bold;
                color: #000;
                text-align: center;
                line-height: 400px;
            }

            /* Ensure everything prints */
            * {
                -webkit-print-color-adjust: exact !important;
                color-adjust: exact !important;
                print-color-adjust: exact !important;
            }
        </style>
    </head>
    <body>';
    
    foreach ($students as $student) {
        // Get student's stream_id and prepare data - EXACT COPY
        $student_stream_id = null;
        try {
            $sql_stream = "SELECT stream_id FROM users WHERE id = ?";
            $stmt_stream = $connection->prepare($sql_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;
        } catch (Exception $e) {
            // Error getting stream ID
        }
        
        // Get ALL subjects for this class with marks, grading scales, and teachers - EXACT COPY
        $grades_data = [];
        $total_marks = 0;
        $total_subjects = 0;
        $subjects_with_marks = 0;
        $highest_mark = 0;
        $lowest_mark = 100;
        $grades_by_subject = [];
        
        try {
            $actual_exam_id = 17; // ASSESSMENT 6 has marks for TERM 3, stream 32
            $sql_all_subjects = "
            SELECT 
                s.subject_name,
                s.subject_id,
                m.mark,
                -- Get teacher information
                u.username as teacher_name,
                cst.teacher_user_id
            FROM class_subjects cs
            JOIN subjects s ON cs.subject_id = s.subject_id
            LEFT JOIN marks m ON (m.subject_id = s.subject_id 
                                 AND m.student_id = ? 
                                 AND m.exam_id = ? 
                                 AND m.school_id = ?"
                                 . ($student_stream_id ? " AND m.stream_id = ?" : "") . ")
            LEFT JOIN class_subject_teachers cst ON (cst.subject_id = s.subject_id 
                                                   AND cst.class_id = ? 
                                                   AND cst.academic_year = ? 
                                                   AND cst.term = ? 
                                                   AND cst.school_id = ?"
                                                   . ($student_stream_id ? " AND cst.stream_id = ?" : "") . ")
            LEFT JOIN users u ON cst.teacher_user_id = u.id
            WHERE cs.class_id = ?
            ORDER BY s.subject_name";
            
            $stmt_all_subjects = $connection->prepare($sql_all_subjects);
            if ($student_stream_id) {
                $stmt_all_subjects->bind_param("iiiisiisii", 
                    $student['user_id'], $actual_exam_id, $class_school_id, $student_stream_id,
                    $class_id, $academic_year, $term, $class_school_id, $student_stream_id,
                    $class_id);
            } else {
                $stmt_all_subjects->bind_param("iiiisisi", 
                    $student['user_id'], $actual_exam_id, $class_school_id,
                    $class_id, $academic_year, $term, $class_school_id,
                    $class_id);
            }
            $stmt_all_subjects->execute();
            $result_all_subjects = $stmt_all_subjects->get_result();
            
            while ($subject_data = $result_all_subjects->fetch_assoc()) {
                $grades_data[] = $subject_data;
                $total_subjects++;
                
                if ($subject_data['mark'] !== null) {
                    $total_marks += $subject_data['mark'];
                    $subjects_with_marks++;
                    $highest_mark = max($highest_mark, $subject_data['mark']);
                    if ($lowest_mark == 100) {
                        $lowest_mark = $subject_data['mark'];
                    } else {
                        $lowest_mark = min($lowest_mark, $subject_data['mark']);
                    }
                    $grades_by_subject[] = [
                        'subject' => $subject_data['subject_name'],
                        'mark' => $subject_data['mark']
                    ];
                }
            }
        } catch (Exception $e) {
            error_log("Error fetching subject marks: " . $e->getMessage());
        }
        
        $average_mark = $subjects_with_marks > 0 ? round($total_marks / $subjects_with_marks, 1) : 0;
        
        // Calculate overall grade using grading scales - EXACT COPY
        $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);
            $overall_grade = $overall_grade_info['grade'];
            $overall_remarks = $overall_grade_info['remarks'];
            
            // Fallback if no overall grading scale found
            if (empty($overall_grade)) {
                if ($average_mark >= 90) { $overall_grade = 'A+'; $overall_remarks = 'Excellent Performance! Keep it up!'; }
                elseif ($average_mark >= 80) { $overall_grade = 'A'; $overall_remarks = 'Very Good Performance!'; }
                elseif ($average_mark >= 70) { $overall_grade = 'B'; $overall_remarks = 'Good Performance!'; }
                elseif ($average_mark >= 60) { $overall_grade = 'C'; $overall_remarks = 'Average Performance. Work harder!'; }
                elseif ($average_mark >= 50) { $overall_grade = 'D'; $overall_remarks = 'Below Average. Needs more effort!'; }
                else { $overall_grade = 'F'; $overall_remarks = 'Poor Performance. Seek extra help!'; }
            }
        }

        // Get stream name
        $stream_name = '';
        if ($student_stream_id) {
            try {
                $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_data_name = $result_stream_name->fetch_assoc();
                $stream_name = $stream_data_name['stream_name'] ?? '';
            } catch (Exception $e) {
                $stream_name = '';
            }
        }

        $html .= '
        <div class="report-card">
            <!-- School Logo Watermark for this Report Card -->
            <div class="report-card-watermark">';
            
        if (!empty($school['logo']) && file_exists($school['logo'])) {
            $html .= '<div style="background-image: url(\'' . htmlspecialchars($school['logo']) . '\'); width: 100%; height: 100%; background-size: contain; background-repeat: no-repeat; background-position: center;"></div>';
        } else {
            $html .= strtoupper(htmlspecialchars($school['school_name']));
        }
        
        $html .= '</div>

            <!-- Header Section with School Details -->
            <div class="report-card-header">
                <div class="school-logo">
                    <div class="school-logo-inner">';
                    
        // Handle school logo exactly like original
        $logo_displayed = false;
        if (!empty($school['logo']) && file_exists($school['logo'])) {
            $html .= '<img src="' . htmlspecialchars($school['logo']) . '" alt="School Logo">';
            $logo_displayed = true;
        }
        
        if (!$logo_displayed) {
            $html .= strtoupper(substr($school['school_name'], 0, 1));
        }
        
        $html .= '</div>
                </div>
                <div class="school-details">
                    <div class="school-name">' . htmlspecialchars($school['school_name']) . '</div>
                    <div class="school-address">' . htmlspecialchars($school['address'] ?? 'Address not available') . '</div>
                    <div class="school-contact">';
                    
        if (!empty($school['phone'])) {
            $html .= 'Tel: ' . htmlspecialchars($school['phone']);
        }
        if (!empty($school['phone']) && !empty($school['email'])) {
            $html .= ' | ';
        }
        if (!empty($school['email'])) {
            $html .= 'Email: ' . htmlspecialchars($school['email']);
        }
        
        $html .= '</div>
                </div>
            </div>

            <!-- Academic Report Form Button -->
            <div class="academic-report-button">
                ACADEMIC REPORT FORM - ' . strtoupper(htmlspecialchars($class_name)) . ' - ' . strtoupper(htmlspecialchars($exam['exam_name'])) . ' - (' . htmlspecialchars($academic_year . ' ' . $term) . ')
            </div>

            <!-- Performance Statistics Buttons -->
            <div class="performance-stats">
                <div class="stat-btn">
                    <span class="stat-value">' . $total_marks . '</span>
                    <span class="stat-label">Total Marks</span>
                </div>
                <div class="stat-btn">
                    <span class="stat-value">' . $average_mark . '%</span>
                    <span class="stat-label">Average Marks</span>
                </div>
                <div class="stat-btn">
                    <span class="stat-value">' . $overall_grade . '</span>
                    <span class="stat-label">Results</span>
                </div>
            </div>

            <!-- Student Details and Performance Graph Section -->
            <div class="student-section">
                <!-- Student Photo Column -->
                <div class="student-photo-column">
                    <div class="student-photo">';
                    
        // Handle student photo exactly like original
        $photo_exists = false;
        $photo_path = '';
        
        if (!empty($student['photo'])) {
            // Check multiple possible photo locations
            if (file_exists($student['photo'])) {
                $photo_exists = true;
                $photo_path = $student['photo'];
            }
            elseif (file_exists('uploads/students/' . $student['photo'])) {
                $photo_exists = true;
                $photo_path = 'uploads/students/' . $student['photo'];
            }
            elseif (file_exists('photos/' . $student['photo'])) {
                $photo_exists = true;
                $photo_path = 'photos/' . $student['photo'];
            }
            elseif (file_exists('uploads/students/' . $student['user_id'] . '.jpg')) {
                $photo_exists = true;
                $photo_path = 'uploads/students/' . $student['user_id'] . '.jpg';
            }
            elseif (file_exists('uploads/students/' . $student['user_id'] . '.png')) {
                $photo_exists = true;
                $photo_path = 'uploads/students/' . $student['user_id'] . '.png';
            }
        }
        
        if ($photo_exists) {
            $html .= '<img src="' . htmlspecialchars($photo_path) . '" alt="Student Photo">';
        } else {
            $html .= '<div class="student-photo-placeholder">👤<br><small style="font-size: 8px;">Student<br>Photo</small></div>';
        }
        
        $html .= '</div>
                </div>

                <!-- Student Details Column -->
                <div class="student-details">
                    <div class="student-info-vertical">
                        <div class="student-info-item">
                            <strong>NAME:</strong> ' . strtoupper(htmlspecialchars($student['student_name'])) . '
                        </div>
                        <div class="student-info-item">
                            <strong>ADMNO:</strong> ' . htmlspecialchars($student['ADM'] ?? 'N/A') . '
                        </div>
                        <div class="student-info-item">
                            <strong>CLASS:</strong> ' . htmlspecialchars($class_name . ($stream_name ? ' ' . $stream_name : '')) . '
                        </div>
                    </div>
                </div>

                <!-- Performance Graph Column -->
                <div class="performance-graph">
                    <div style="text-align: center; font-weight: bold; margin-bottom: 5px; color: #2c5aa0;">Performance Overview</div>
                    <div class="chart-container">';
                    
        // Create chart bars using actual subject marks
        $chart_marks = [];
        $subject_count = 0;
        foreach ($grades_data as $subject_data) {
            if ($subject_data['mark'] !== null && $subject_count < 5) {
                $chart_marks[] = $subject_data['mark'];
                $subject_count++;
            }
        }
        
        // Fill with average if not enough subjects
        while (count($chart_marks) < 5) {
            $chart_marks[] = $average_mark;
        }
        
        foreach ($chart_marks as $mark) {
            $height = max(($mark / 100) * 45, 5); // Scale to chart height
            $html .= '<div class="chart-bar" style="height: ' . $height . 'px;"></div>';
        }
        
        $html .= '</div>
                </div>
            </div>

            <!-- Examination Results Table -->
            <div class="results-section">
                <h3 class="results-title">EXAMINATION RESULTS</h3>
                <table class="results-table">
                    <thead>
                        <tr>
                            <th>SUBJECTS</th>
                            <th>MARKS</th>
                            <th>GRADE</th>
                            <th>COMMENTS</th>
                            <th>TEACHER</th>
                        </tr>
                    </thead>
                    <tbody>';
                    
        if (!empty($grades_data)) {
            foreach ($grades_data as $subject_data) {
                $mark = $subject_data['mark'];
                $grade = '';
                $comments = '';
                $teacher_name = '';
                
                // Get teacher name
                if (!empty($subject_data['teacher_name'])) {
                    $teacher_name = $subject_data['teacher_name'];
                } else {
                    $teacher_name = "Not Assigned";
                }
                
                if ($mark !== null) {
                    // Get grade and comments from grading scales
                    $grade_info = getGradeFromScale($mark, $subject_data['subject_id'], $class_id, $academic_year, $term, $class_school_id, $connection);
                    $grade = $grade_info['grade'];
                    $comments = $grade_info['remarks'];
                    
                    $html .= "<tr>";
                    $html .= "<td>" . htmlspecialchars($subject_data['subject_name']) . "</td>";
                    $html .= "<td>" . htmlspecialchars($mark) . "</td>";
                    $html .= "<td><span class='grade-badge'>" . htmlspecialchars($grade) . "</span></td>";
                    $html .= "<td>" . htmlspecialchars($comments) . "</td>";
                    $html .= "<td>" . htmlspecialchars($teacher_name) . "</td>";
                    $html .= "</tr>";
                } else {
                    $html .= "<tr>";
                    $html .= "<td>" . htmlspecialchars($subject_data['subject_name']) . "</td>";
                    $html .= "<td style='color: #999;'>-</td>";
                    $html .= "<td><span class='grade-badge' style='background: #6c757d;'>N/A</span></td>";
                    $html .= "<td style='color: #999;'>No marks recorded</td>";
                    $html .= "<td>" . htmlspecialchars($teacher_name) . "</td>";
                    $html .= "</tr>";
                }
            }
        } else {
            $html .= "<tr><td colspan='5' style='text-align: center; color: #999;'>No subjects found for this class</td></tr>";
        }
        
        $html .= '
                    </tbody>
                </table>
            </div>

            <!-- Performance and Remarks Horizontal Container -->
            <div class="performance-remarks-container">
                <!-- Performance Over Time Chart -->
                <div class="performance-trends">
                    <div class="trends-title">STUDENT\'S PERFORMANCE OVER TIME</div>
                    <div class="trends-chart">
                        <div class="trend-line"></div>
                        <div class="trend-point"></div>
                        <div class="trend-point"></div>
                        <div class="trend-point"></div>
                    </div>
                </div>

                <!-- Remarks Section -->
                <div class="remarks-section">
                    <div class="remark-box">
                        <div class="remark-title">CLASS TEACHER\'S REMARKS</div>
                        <div class="remark-content">' . htmlspecialchars($overall_remarks) . '</div>
                        <div style="margin-top: 5px; font-size: 8px;">
                            Signature: ________________<br>
                            Date: ' . 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 good work and strive for excellence in all your endeavors.</div>
                        <div style="margin-top: 5px; font-size: 8px;">
                            Signature: ________________<br>
                            Date: ' . date('Y-m-d') . '
                        </div>
                    </div>
                </div>
            </div>

            <!-- Footer Section -->
            <div class="report-footer">
                <div class="school-motto-footer">';
                
        if (!empty($school['motto'])) {
            $html .= '<strong>School Motto:</strong> "' . htmlspecialchars($school['motto']) . '"';
        } else {
            $html .= '<strong>School Motto:</strong> "Excellence in Education"';
        }
        
        $html .= '</div>
                <div class="qr-code">
                    <div class="qr-code-inner">
                        📱<br>
                        <div style="font-size: 7px; margin-top: 2px;">Scan for Details</div>
                    </div>
                </div>
            </div>
        </div>';
    }
    
    $html .= '</body></html>';
    return $html;
}

// Generate PDF
try {
    $options = new Options();
    $options->set('defaultFont', 'Arial');
    $options->set('isHtml5ParserEnabled', true);
    $options->set('isPhpEnabled', true);
    $options->set('isRemoteEnabled', true);
    $options->set('isJavascriptEnabled', false);
    
    $dompdf = new Dompdf($options);
    
    $html = generateExactPDFHTML($students, $school, $class_name, $exam, $academic_year, $term, $class_id, $class_school_id, $connection);
    
    $dompdf->loadHtml($html);
    $dompdf->setPaper('A4', 'portrait');
    $dompdf->render();
    
    // Generate filename
    if ($download_type === 'single' && !empty($student_id)) {
        $student_name = $students[0]['student_name'] ?? 'Student';
        $filename = "Report_Card_" . preg_replace('/[^a-zA-Z0-9_-]/', '_', $student_name) . "_" . date('Y-m-d') . ".pdf";
    } else {
        $filename = "Report_Cards_" . preg_replace('/[^a-zA-Z0-9_-]/', '_', $class_name) . "_" . date('Y-m-d') . ".pdf";
    }
    
    $dompdf->stream($filename, array("Attachment" => true));
    
} catch (Exception $e) {
    echo "Error generating PDF: " . $e->getMessage();
}

$connection->close();
?>