<?php
/**
 * ENHANCED PDF GENERATION FUNCTIONS FOR ADMIN_EXAM_GRADE_REPORTS.PHP
 * 
 * Include this file at the end of your admin_exam_grade_reports.php file
 * to enable complete PDF generation functionality
 * 
 * Usage: require_once 'enhanced_pdf_functions.php';
 */

// =============================================================================
// 1. MAIN PDF GENERATION FUNCTIONS
// =============================================================================

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

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

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

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

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

        $dompdf = new Dompdf\Dompdf([
            'isRemoteEnabled' => true,
            'isHtml5ParserEnabled' => true,
            'defaultFont' => 'DejaVu Sans'
        ]);
        
        // Get information
        $class_info = getCompleteClassInfo($connection, $class_id);
        $exam_info = getCompleteExamInfo($connection, $exam_id);
        $school_info = getCompleteSchoolInfo($connection, $class_info['school_id']);
        $student_data = getCompleteStudentReportData($connection, $student_id, $exam_id, $class_id, $academic_year, $term);
        
        // Build HTML
        $html = generateCompletePDFCSS() . '<body>';
        $html .= generateCompleteStudentReportCardHTML(
            $student_data, 
            $academic_year, 
            $term, 
            $class_info, 
            $exam_info, 
            $school_info,
            $student_data['student']
        );
        $html .= '</body></html>';
        
        // Generate PDF
        $dompdf->loadHtml($html);
        $dompdf->setPaper('A4', 'portrait');
        $dompdf->render();
        
        $student_name = $student_data['student']['full_name'] ?? 'Student';
        $filename = "Report_Card_{$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.grade,
            s.subject_name,
            s.subject_code,
            sp.paper_name,
            sp.paper_id,
            CONCAT(t.first_name, ' ', t.last_name) 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_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
    $total_marks = array_sum(array_column($grades, 'mark'));
    $grade_count = count($grades);
    $average_mark = $grade_count > 0 ? $total_marks / $grade_count : 0;
    
    // 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) {
    $html = '<div class="report-card" style="page-break-after: always; margin-bottom: 30px;">';
    
    // 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;">Paper</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;">' . htmlspecialchars($grade['paper_name'] ?? 'Main') . '</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>';
        }
        
        $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>';
    
    // Remarks
    $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>';
    
    // 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;
        }
    </style>';
}

// =============================================================================
// 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>';
    
    $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>';
    
    $html .= '</body></html>';
    
    return [
        'success' => true,
        'html_content' => $html,
        'filename' => 'report_preview.html'
    ];
}

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

// =============================================================================
// 5. LEGACY COMPATIBILITY FUNCTIONS
// =============================================================================

/**
 * Legacy function aliases for backward compatibility
 */
function generateReportCardsPDF($connection, $academic_year, $term, $exam_id, $class_id, $student_ids = []) {
    return generateCompleteReportCardsPDF($connection, $academic_year, $term, $exam_id, $class_id, $student_ids);
}

function generateSingleStudentPDF($connection, $student_id, $academic_year, $term, $exam_id, $class_id) {
    return generateCompleteSingleStudentPDF($connection, $student_id, $academic_year, $term, $exam_id, $class_id);
}

function generatePDFCSS() {
    return generateCompletePDFCSS();
}

?>