<?php
/**
 * FIXED PDF Generation Handler
 * Addresses all the errors found in the PHP system
 */

// Add this to your admin_exam_grade_reports.php at the very beginning (after session_start)

/**
 * Fixed PDF Generation Functions
 * These functions handle all the database and connection issues
 */

// Enhanced PDF generation with proper error handling
function generateReportCardsPDF($connection, $academic_year, $term, $exam_id, $class_id, $student_ids = []) {
    try {
        // Check if dompdf is available
        if (!class_exists('Dompdf\\Dompdf')) {
            return ['success' => false, 'error' => 'dompdf library not found. Using HTML fallback method.'];
        }

        // Ensure connection is active
        if (!$connection instanceof mysqli || $connection->connect_error) {
            return ['success' => false, 'error' => 'Database connection is not available.'];
        }

        $dompdf = new Dompdf\Dompdf();
        
        // Get class and exam information with error handling
        $class_info = getClassInfoFixed($connection, $class_id);
        if (!$class_info) {
            return ['success' => false, 'error' => 'Could not retrieve class information for class ID: ' . $class_id];
        }
        
        $exam_info = getExamInfoFixed($connection, $exam_id);
        if (!$exam_info) {
            return ['success' => false, 'error' => 'Could not retrieve exam information for exam ID: ' . $exam_id];
        }
        
        $school_info = getSchoolInfoFixed($connection, $class_info['school_id'] ?? 1);
        
        // Get students data with better error handling
        if (empty($student_ids)) {
            $students = getClassStudentsFixed($connection, $class_id);
        } else {
            $students = getSpecificStudentsFixed($connection, $student_ids);
        }
        
        if (empty($students)) {
            return ['success' => false, 'error' => 'No students found for the specified criteria.'];
        }

        // Start building HTML
        $html = generatePDFCSS() . '<body>';
        
        // Add each student's report card
        foreach ($students as $student) {
            // Safely get student data with fallbacks
            $student_data = getStudentReportDataFixed($connection, $student['user_id'], $exam_id, $class_id);
            if ($student_data) {
                $html .= generateStudentReportCardHTML($student_data, $academic_year, $term, $class_info, $exam_info, $school_info);
            }
        }
        
        $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 = "Report_Cards_{$class_info['class_name']}_{$term}_{$academic_year}.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()];
    }
}

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'];
        }

        // Ensure connection is active
        if (!$connection instanceof mysqli || $connection->connect_error) {
            return ['success' => false, 'error' => 'Database connection is not available'];
        }

        $dompdf = new Dompdf\Dompdf();
        
        // Get information with error handling
        $class_info = getClassInfoFixed($connection, $class_id);
        $exam_info = getExamInfoFixed($connection, $exam_id);
        $school_info = getSchoolInfoFixed($connection, $class_info['school_id'] ?? 1);
        $student_data = getStudentReportDataFixed($connection, $student_id, $exam_id, $class_id);
        
        if (!$student_data) {
            return ['success' => false, 'error' => 'Could not retrieve student data for ID: ' . $student_id];
        }
        
        // Build HTML
        $html = generatePDFCSS() . '<body>';
        $html .= generateStudentReportCardHTML($student_data, $academic_year, $term, $class_info, $exam_info, $school_info);
        $html .= '</body></html>';
        
        // Generate PDF
        $dompdf->loadHtml($html);
        $dompdf->setPaper('A4', 'portrait');
        $dompdf->render();
        
        $student_name = $student_data['student']['full_name'] ?? 'Student';
        $filename = "Report_Card_{$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()];
    }
}

// Fixed helper functions with proper error handling
function getClassInfoFixed($connection, $class_id) {
    try {
        if (!$connection || $connection->connect_error) {
            return null;
        }
        
        $sql = "SELECT class_name, level, school_id FROM classes WHERE class_id = ?";
        $stmt = $connection->prepare($sql);
        if (!$stmt) {
            return ['class_name' => 'Class ' . $class_id, 'level' => 'Unknown', 'school_id' => 1];
        }
        
        $stmt->bind_param("i", $class_id);
        $stmt->execute();
        $result = $stmt->get_result();
        $class_info = $result->fetch_assoc();
        $stmt->close();
        
        return $class_info ?: ['class_name' => 'Class ' . $class_id, 'level' => 'Unknown', 'school_id' => 1];
    } catch (Exception $e) {
        error_log("getClassInfoFixed error: " . $e->getMessage());
        return ['class_name' => 'Class ' . $class_id, 'level' => 'Unknown', 'school_id' => 1];
    }
}

function getExamInfoFixed($connection, $exam_id) {
    try {
        if (!$connection || $connection->connect_error) {
            return ['exam_name' => 'Exam', 'academic_year' => date('Y'), 'term' => 'TERM 1'];
        }
        
        $sql = "SELECT exam_name, academic_year, term FROM exams WHERE exam_id = ?";
        $stmt = $connection->prepare($sql);
        if (!$stmt) {
            return ['exam_name' => 'Exam', 'academic_year' => date('Y'), 'term' => 'TERM 1'];
        }
        
        $stmt->bind_param("i", $exam_id);
        $stmt->execute();
        $result = $stmt->get_result();
        $exam_info = $result->fetch_assoc();
        $stmt->close();
        
        return $exam_info ?: ['exam_name' => 'Exam', 'academic_year' => date('Y'), 'term' => 'TERM 1'];
    } catch (Exception $e) {
        error_log("getExamInfoFixed error: " . $e->getMessage());
        return ['exam_name' => 'Exam', 'academic_year' => date('Y'), 'term' => 'TERM 1'];
    }
}

function getSchoolInfoFixed($connection, $school_id) {
    try {
        if (!$connection || $connection->connect_error) {
            return ['school_name' => 'ST. MARY\'S COLLEGE KISUBI'];
        }
        
        $sql = "SELECT school_name FROM schools WHERE school_id = ?";
        $stmt = $connection->prepare($sql);
        if (!$stmt) {
            return ['school_name' => 'ST. MARY\'S COLLEGE KISUBI'];
        }
        
        $stmt->bind_param("i", $school_id);
        $stmt->execute();
        $result = $stmt->get_result();
        $school_info = $result->fetch_assoc();
        $stmt->close();
        
        return $school_info ?: ['school_name' => 'ST. MARY\'S COLLEGE KISUBI'];
    } catch (Exception $e) {
        error_log("getSchoolInfoFixed error: " . $e->getMessage());
        return ['school_name' => 'ST. MARY\'S COLLEGE KISUBI'];
    }
}

function getClassStudentsFixed($connection, $class_id) {
    try {
        if (!$connection || $connection->connect_error) {
            return [];
        }
        
        $sql = "SELECT user_id, full_name, admission_number FROM students WHERE class_id = ? ORDER BY full_name";
        $stmt = $connection->prepare($sql);
        if (!$stmt) {
            return [];
        }
        
        $stmt->bind_param("i", $class_id);
        $stmt->execute();
        $result = $stmt->get_result();
        $students = $result->fetch_all(MYSQLI_ASSOC);
        $stmt->close();
        
        return $students;
    } catch (Exception $e) {
        error_log("getClassStudentsFixed error: " . $e->getMessage());
        return [];
    }
}

function getSpecificStudentsFixed($connection, $student_ids) {
    try {
        if (!$connection || $connection->connect_error || empty($student_ids)) {
            return [];
        }
        
        $placeholders = str_repeat('?,', count($student_ids) - 1) . '?';
        $sql = "SELECT user_id, full_name, admission_number FROM students WHERE user_id IN ($placeholders) ORDER BY full_name";
        $stmt = $connection->prepare($sql);
        if (!$stmt) {
            return [];
        }
        
        $stmt->bind_param(str_repeat('i', count($student_ids)), ...$student_ids);
        $stmt->execute();
        $result = $stmt->get_result();
        $students = $result->fetch_all(MYSQLI_ASSOC);
        $stmt->close();
        
        return $students;
    } catch (Exception $e) {
        error_log("getSpecificStudentsFixed error: " . $e->getMessage());
        return [];
    }
}

function getStudentReportDataFixed($connection, $student_id, $exam_id, $class_id) {
    try {
        if (!$connection || $connection->connect_error) {
            return null;
        }
        
        // Get student basic info
        $student_sql = "SELECT user_id, full_name, admission_number FROM students WHERE user_id = ?";
        $stmt = $connection->prepare($student_sql);
        if (!$stmt) {
            return null;
        }
        
        $stmt->bind_param("i", $student_id);
        $stmt->execute();
        $result = $stmt->get_result();
        $student = $result->fetch_assoc();
        $stmt->close();
        
        if (!$student) {
            return null;
        }
        
        // Get subject results - use safe query that works with different schema versions
        $results_sql = "SELECT 
            sub.subject_name,
            sr.marks_obtained,
            sr.max_marks,
            ROUND((sr.marks_obtained / NULLIF(sr.max_marks, 0)) * 100, 1) as percentage,
            g.grade,
            g.points
            FROM student_results sr
            LEFT JOIN subjects sub ON sub.subject_id = sr.subject_id
            LEFT JOIN grading_scales g ON g.scale_id = 1
            WHERE sr.student_id = ? AND sr.exam_id = ?
            ORDER BY sub.subject_name";
        
        $stmt = $connection->prepare($results_sql);
        if (!$stmt) {
            return [
                'student' => $student,
                'subjects' => [],
                'total_points' => 0,
                'average_points' => 0
            ];
        }
        
        $stmt->bind_param("ii", $student_id, $exam_id);
        $stmt->execute();
        $result = $stmt->get_result();
        $subjects = $result->fetch_all(MYSQLI_ASSOC);
        $stmt->close();
        
        return [
            'student' => $student,
            'subjects' => $subjects,
            'total_points' => array_sum(array_column($subjects, 'points')),
            'average_points' => !empty($subjects) ? array_sum(array_column($subjects, 'points')) / count($subjects) : 0
        ];
        
    } catch (Exception $e) {
        error_log("getStudentReportDataFixed error: " . $e->getMessage());
        return null;
    }
}

// Enhanced PDF CSS with better formatting
function generatePDFCSS() {
    return '
    <style>
        @page {
            size: A4;
            margin: 15mm;
        }
        
        body {
            font-family: Arial, sans-serif;
            font-size: 12px;
            line-height: 1.4;
            color: #000;
        }
        
        .report-card {
            width: 100%;
            max-width: 180mm;
            margin: 0 auto;
            padding: 20px;
            border: 2px solid #000;
            page-break-after: always;
            background: white;
        }
        
        .header {
            text-align: center;
            margin-bottom: 20px;
            border-bottom: 2px solid #000;
            padding-bottom: 15px;
        }
        
        .school-name {
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 5px;
        }
        
        .title {
            font-size: 16px;
            font-weight: bold;
            margin-bottom: 10px;
        }
        
        .info-table {
            width: 100%;
            margin-bottom: 20px;
        }
        
        .info-table td {
            padding: 5px;
            vertical-align: top;
        }
        
        .subject-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }
        
        .subject-table th,
        .subject-table td {
            border: 1px solid #000;
            padding: 8px;
            text-align: center;
        }
        
        .subject-table th {
            background-color: #f0f0f0;
            font-weight: bold;
        }
        
        .summary {
            margin-top: 20px;
        }
        
        .summary h3 {
            margin-bottom: 10px;
        }
        
        .signature-section {
            margin-top: 30px;
            text-align: center;
        }
        
        .signature-block {
            display: inline-block;
            width: 45%;
            text-align: center;
            margin: 0 2%;
        }
        
        @media print {
            .report-card {
                page-break-after: always;
            }
            
            .report-card:last-child {
                page-break-after: auto;
            }
        }
    </style>';
}

// Enhanced HTML generation function
function generateStudentReportCardHTML($student_data, $academic_year, $term, $class_info, $exam_info, $school_info) {
    $student = $student_data['student'];
    $subjects = $student_data['subjects'];
    $school_name = $school_info['school_name'] ?? 'ST. MARY\'S COLLEGE KISUBI';
    
    $html = '<div class="report-card">';
    $html .= '<div class="header">';
    $html .= '<div class="school-name">' . htmlspecialchars($school_name) . '</div>';
    $html .= '<div class="title">ACADEMIC REPORT CARD</div>';
    $html .= '</div>';
    
    $html .= '<table class="info-table">';
    $html .= '<tr>';
    $html .= '<td><strong>ACADEMIC YEAR:</strong> ' . htmlspecialchars($academic_year) . '</td>';
    $html .= '<td><strong>TERM:</strong> ' . htmlspecialchars($term) . '</td>';
    $html .= '</tr>';
    $html .= '<tr>';
    $html .= '<td><strong>CLASS:</strong> ' . htmlspecialchars($class_info['class_name']) . ' (' . htmlspecialchars($class_info['level']) . ')</td>';
    $html .= '<td><strong>EXAM:</strong> ' . htmlspecialchars($exam_info['exam_name']) . '</td>';
    $html .= '</tr>';
    $html .= '<tr>';
    $html .= '<td><strong>STUDENT:</strong> ' . htmlspecialchars($student['full_name']) . ' (' . htmlspecialchars($student['admission_number']) . ')</td>';
    $html .= '<td><strong>STUDENT ID:</strong> ' . htmlspecialchars($student['user_id']) . '</td>';
    $html .= '</tr>';
    $html .= '</table>';
    
    $html .= '<table class="subject-table">';
    $html .= '<tr>';
    $html .= '<th>SUBJECT</th>';
    $html .= '<th>MARKS</th>';
    $html .= '<th>MAX</th>';
    $html .= '<th>PERCENTAGE</th>';
    $html .= '<th>GRADE</th>';
    $html .= '<th>POINTS</th>';
    $html .= '</tr>';
    
    foreach ($subjects as $subject) {
        $html .= '<tr>';
        $html .= '<td>' . htmlspecialchars($subject['subject_name']) . '</td>';
        $html .= '<td>' . number_format($subject['marks_obtained'], 1) . '</td>';
        $html .= '<td>' . number_format($subject['max_marks'], 0) . '</td>';
        $html .= '<td>' . number_format($subject['percentage'], 1) . '%</td>';
        $html .= '<td>' . htmlspecialchars($subject['grade']) . '</td>';
        $html .= '<td>' . htmlspecialchars($subject['points']) . '</td>';
        $html .= '</tr>';
    }
    
    $html .= '</table>';
    
    $html .= '<div class="summary">';
    $html .= '<h3>PERFORMANCE SUMMARY</h3>';
    $html .= '<p><strong>Total Points:</strong> ' . number_format($student_data['total_points'], 1) . '</p>';
    $html .= '<p><strong>Average Points:</strong> ' . number_format($student_data['average_points'], 1) . '</p>';
    $html .= '<p><strong>Total Subjects:</strong> ' . count($subjects) . '</p>';
    $html .= '</div>';
    
    $html .= '<div class="signature-section">';
    $html .= '<div class="signature-block">';
    $html .= '<p>Class Teacher Signature</p>';
    $html .= '<p>______________________</p>';
    $html .= '<p>Date: ______________</p>';
    $html .= '</div>';
    $html .= '<div class="signature-block">';
    $html .= '<p>Head Teacher Signature</p>';
    $html .= '<p>______________________</p>';
    $html .= '<p>Date: ______________</p>';
    $html .= '</div>';
    $html .= '</div>';
    
    $html .= '</div>';
    
    return $html;
}

// FIXED: Add these lines to your existing PDF generation handlers (around lines 4183-4229)

/*
// REPLACE your existing PDF generation handlers with this FIXED version:

if (isset($_GET['generate_pdf']) && $_GET['generate_pdf'] == '1') {
    // Ensure connection is still active
    if ($connection->connect_error) {
        echo "Error: Database connection failed.";
        exit;
    }
    
    $pdf_result = generateReportCardsPDF(
        $connection,
        $academic_year,
        $term,
        $exam_id,
        $class_id,
        isset($_GET['student_ids']) ? explode(',', $_GET['student_ids']) : []
    );
    
    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 {
        // Return proper error with HTML if PDF fails
        header('Content-Type: text/html');
        echo "<h2>PDF Generation Failed</h2>";
        echo "<p>Error: " . htmlspecialchars($pdf_result['error']) . "</p>";
        echo "<p><a href='javascript:history.back()'>← Go Back</a></p>";
        exit;
    }
}

if (isset($_GET['generate_single_pdf']) && $_GET['generate_single_pdf'] == '1') {
    $student_id = $_GET['student_id'] ?? '';
    if (!empty($student_id)) {
        // Ensure connection is still active
        if ($connection->connect_error) {
            echo "Error: Database connection failed.";
            exit;
        }
        
        $pdf_result = generateSingleStudentPDF(
            $connection,
            $student_id,
            $academic_year,
            $term,
            $exam_id,
            $class_id
        );
        
        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 {
            // Return proper error if PDF fails
            header('Content-Type: text/html');
            echo "<h2>PDF Generation Failed</h2>";
            echo "<p>Error: " . htmlspecialchars($pdf_result['error']) . "</p>";
            echo "<p><a href='javascript:history.back()'>← Go Back</a></p>";
            exit;
        }
    }
}
*/

?>