<?php
// PDF Report Generator
session_start();
include 'config.php';

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

// Check if DOMPDF is available
function isDompdfAvailable() {
    if (file_exists(__DIR__ . '/vendor/autoload.php')) {
        require_once __DIR__ . '/vendor/autoload.php';
        return class_exists('Dompdf\Dompdf');
    }
    return class_exists('Dompdf\Dompdf') || class_exists('Dompdf\Options');
}

// If DOMPDF is not available, redirect to fallback
if (!isDompdfAvailable()) {
    $query_string = $_SERVER['QUERY_STRING'];
    header("Location: generate_pdf_fallback.php?" . $query_string);
    exit();
}

// Load DOMPDF
if (file_exists(__DIR__ . '/vendor/autoload.php')) {
    require_once __DIR__ . '/vendor/autoload.php';
}

use Dompdf\Dompdf;
use Dompdf\Options;

// Get parameters
$academic_year = $_GET['academic_year'] ?? '';
$term = $_GET['term'] ?? '';
$exam_id = $_GET['exam_id'] ?? '';
$class_id = $_GET['class_id'] ?? '';
$download_type = $_GET['download_type'] ?? 'all'; // 'all' or 'single'
$student_id = $_GET['student_id'] ?? ''; // For single student download

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

// 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 if DOMPDF is available, if not, use fallback
if (!file_exists('vendor/autoload.php')) {
    // Use fallback HTML-to-PDF approach
    include 'generate_pdf_fallback.php';
    exit();
}

// Include shared grading functions
require_once 'shared_grading_functions.php';

// 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 based on download type
if ($download_type === 'single' && !empty($student_id)) {
    // Single student
    $sql_students = "
    SELECT id as user_id, username as student_name, ADM, parent_name, parent_phone, role, class_id, school_id, photo, stream_id
    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 {
    // All students in class
    $sql_students = "
    SELECT id as user_id, username as student_name, ADM, parent_name, parent_phone, role, class_id, school_id, photo, stream_id
    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;
}

if (empty($students)) {
    die("No students found");
}

// Initialize DOMPDF
$options = new Options();
$options->set('defaultFont', 'Arial');
$options->set('isRemoteEnabled', true);
$options->set('isHtml5ParserEnabled', true);

$dompdf = new Dompdf($options);

// Start building HTML for PDF
ob_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Report Cards - <?php echo htmlspecialchars($class_name); ?></title>
    <style>
        body { 
            font-family: Arial, sans-serif; 
            margin: 0; 
            padding: 0;
            font-size: 10px;
            line-height: 1.2;
        }
        
        .report-card { 
            page-break-after: always;
            width: 210mm;
            height: 297mm;
            padding: 10mm;
            box-sizing: border-box;
            position: relative;
        }
        
        .report-card:last-child {
            page-break-after: avoid;
        }
        
        .report-card-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            padding-bottom: 10px;
            border-bottom: 2px solid #2c5aa0;
            margin-bottom: 10px;
        }
        
        .school-logo {
            width: 50px;
            height: 50px;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .school-logo img {
            width: 50px;
            height: 50px;
            object-fit: contain;
        }
        
        .school-details {
            text-align: right;
            color: black;
            font-weight: bold;
        }
        
        .school-name {
            font-size: 16px;
            font-weight: bold;
            margin-bottom: 3px;
        }
        
        .school-address {
            font-size: 9px;
            line-height: 1.2;
            margin-bottom: 2px;
        }
        
        .school-contact {
            font-size: 8px;
        }
        
        .academic-report-button {
            text-align: center;
            padding: 10px;
            margin: 10px 0;
            background: #2c5aa0;
            color: white;
            border-radius: 5px;
            font-weight: bold;
            font-size: 11px;
        }
        
        .performance-stats {
            display: flex;
            justify-content: space-around;
            margin: 10px 0;
            gap: 10px;
        }
        
        .stat-btn {
            background: linear-gradient(45deg, #007bff, #28a745);
            color: white;
            padding: 8px;
            border-radius: 5px;
            text-align: center;
            flex: 1;
        }
        
        .stat-value {
            display: block;
            font-size: 14px;
            font-weight: bold;
        }
        
        .stat-label {
            display: block;
            font-size: 8px;
        }
        
        .student-section {
            display: flex;
            gap: 10px;
            margin: 10px 0;
        }
        
        .student-photo {
            width: 60px;
            height: 70px;
            border: 1px solid #ccc;
            display: flex;
            align-items: center;
            justify-content: center;
            background: #f8f9fa;
        }
        
        .student-photo img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        
        .student-photo-placeholder {
            font-size: 24px;
            color: #6c757d;
            text-align: center;
        }
        
        .student-details {
            flex: 1;
            padding: 5px;
        }
        
        .student-info-item {
            margin-bottom: 3px;
            font-size: 9px;
        }
        
        .performance-graph {
            width: 150px;
            height: 80px;
            border: 1px solid #ccc;
            display: flex;
            align-items: center;
            justify-content: center;
            background: #f8f9fa;
            font-size: 8px;
            text-align: center;
        }
        
        .results-section {
            margin: 10px 0;
        }
        
        .results-title {
            background: #2c5aa0;
            color: white;
            text-align: center;
            padding: 5px;
            margin: 0 0 5px 0;
            font-size: 12px;
        }
        
        .results-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 9px;
        }
        
        .results-table th {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            padding: 5px;
            text-align: center;
            font-weight: bold;
        }
        
        .results-table td {
            border: 1px solid #dee2e6;
            padding: 5px;
            text-align: center;
        }
        
        .grade-badge {
            background: #28a745;
            color: white;
            padding: 2px 5px;
            border-radius: 3px;
            font-weight: bold;
        }
        
        .performance-container {
            display: flex;
            gap: 10px;
            margin: 10px 0;
        }
        
        .trends-section {
            flex: 1;
            border: 1px solid #ccc;
            padding: 5px;
            background: #f8f9fa;
        }
        
        .remarks-section {
            flex: 1;
        }
        
        .remark-box {
            border: 1px solid #ccc;
            padding: 5px;
            margin-bottom: 5px;
            background: white;
        }
        
        .remark-title {
            font-weight: bold;
            font-size: 8px;
            margin-bottom: 3px;
        }
        
        .remark-content {
            font-size: 8px;
            line-height: 1.3;
        }
        
        .report-footer {
            position: absolute;
            bottom: 10mm;
            left: 10mm;
            right: 10mm;
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 8px;
        }
        
        .qr-code {
            text-align: center;
            border: 1px solid #ccc;
            padding: 5px;
            width: 60px;
            height: 60px;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .report-card-watermark {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            z-index: -1;
            opacity: 0.05;
            width: 200px;
            height: 200px;
            background-size: contain;
            background-repeat: no-repeat;
            background-position: center;
        }
    </style>
</head>
<body>

<?php foreach ($students as $student): ?>
    <div class="report-card">
        <?php
        // Get student data (same logic as main report)
        $student_stream_id = $student['stream_id'] ?? null;
        
        // Get grades data
        $grades_data = [];
        $total_marks = 0;
        $total_subjects = 0;
        $subjects_with_marks = 0;
        $highest_mark = 0;
        $lowest_mark = 100;
        
        try {
            $actual_exam_id = 17;
            $sql_all_subjects = "
            SELECT 
                s.subject_name,
                s.subject_id,
                m.mark,
                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']);
                    }
                }
            }
        } catch (Exception $e) {
            // Handle error silently for PDF
        }
        
        $average_mark = $subjects_with_marks > 0 ? round($total_marks / $subjects_with_marks, 1) : 0;
        
        // Calculate overall grade
        $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'];
        
        if (empty($overall_grade) && $subjects_with_marks > 0) {
            if ($average_mark >= 90) { $overall_grade = 'A+'; $overall_remarks = 'Excellent Performance!'; }
            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!'; }
            elseif ($average_mark >= 50) { $overall_grade = 'D'; $overall_remarks = 'Below Average!'; }
            else { $overall_grade = 'F'; $overall_remarks = 'Needs Improvement!'; }
        }
        ?>
        
        <!-- Watermark -->
        <?php if (!empty($school['logo'])): ?>
            <div class="report-card-watermark" style="background-image: url('<?php echo htmlspecialchars($school['logo']); ?>');"></div>
        <?php endif; ?>
        
        <!-- Header -->
        <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 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">
                    Tel: <?php echo htmlspecialchars($school['phone'] ?? 'N/A'); ?> | 
                    Email: <?php echo htmlspecialchars($school['email'] ?? 'N/A'); ?>
                </div>
            </div>
        </div>
        
        <!-- Academic Report Button -->
        <div class="academic-report-button">
            ACADEMIC REPORT FORM - <?php echo strtoupper(htmlspecialchars($class_name)); ?> - <?php echo strtoupper(htmlspecialchars($exam['exam_name'])); ?> - (<?php echo htmlspecialchars($academic_year . ' ' . $term); ?>)
        </div>
        
        <!-- Performance Statistics -->
        <div class="performance-stats">
            <div class="stat-btn">
                <span class="stat-value"><?php echo $total_marks; ?></span>
                <span class="stat-label">Total Marks</span>
            </div>
            <div class="stat-btn">
                <span class="stat-value"><?php echo $average_mark; ?>%</span>
                <span class="stat-label">Average Marks</span>
            </div>
            <div class="stat-btn">
                <span class="stat-value"><?php echo $overall_grade; ?></span>
                <span class="stat-label">Results</span>
            </div>
        </div>
        
        <!-- Student Details Section -->
        <div class="student-section">
            <div class="student-photo">
                <?php 
                $photo_exists = false;
                if (!empty($student['photo']) && file_exists($student['photo'])) {
                    $photo_exists = true;
                }
                
                if ($photo_exists): ?>
                    <img src="<?php echo htmlspecialchars($student['photo']); ?>" alt="Student Photo">
                <?php else: ?>
                    <div class="student-photo-placeholder">👤</div>
                <?php endif; ?>
            </div>
            
            <div class="student-details">
                <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); ?>
                </div>
            </div>
            
            <div class="performance-graph">
                Performance Graph<br>
                (Chart visualization)
            </div>
        </div>
        
        <!-- Examination Results -->
        <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>
                    <?php
                    if (!empty($grades_data)) {
                        foreach ($grades_data as $subject_data) {
                            $mark = $subject_data['mark'];
                            $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);
                                $grade = $grade_info['grade'];
                                $comments = $grade_info['remarks'];
                                
                                echo "<tr>";
                                echo "<td>" . htmlspecialchars($subject_data['subject_name']) . "</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 {
                                echo "<tr>";
                                echo "<td>" . htmlspecialchars($subject_data['subject_name']) . "</td>";
                                echo "<td>-</td>";
                                echo "<td><span class='grade-badge' style='background: #6c757d;'>N/A</span></td>";
                                echo "<td>No marks recorded</td>";
                                echo "<td>" . htmlspecialchars($teacher_name) . "</td>";
                                echo "</tr>";
                            }
                        }
                    } else {
                        echo "<tr><td colspan='5'>No subjects found for this class</td></tr>";
                    }
                    ?>
                </tbody>
            </table>
        </div>
        
        <!-- Performance and Remarks -->
        <div class="performance-container">
            <div class="trends-section">
                <div style="font-weight: bold; margin-bottom: 5px;">Performance Trends</div>
                <div>Performance trend visualization would appear here</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: 7px;">
                        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 good work and strive for excellence in all your endeavors.</div>
                    <div style="margin-top: 5px; font-size: 7px;">
                        Signature: ________________<br>
                        Date: <?php echo date('Y-m-d'); ?>
                    </div>
                </div>
            </div>
        </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">
                QR Code<br>
                Here
            </div>
        </div>
    </div>
<?php endforeach; ?>

</body>
</html>

<?php
$html = ob_get_clean();

// Load HTML into DOMPDF
$dompdf->loadHtml($html);

// Set paper size and orientation
$dompdf->setPaper('A4', 'portrait');

// Render PDF
$dompdf->render();

// Generate filename
if ($download_type === 'single') {
    $filename = "Report_Card_" . str_replace(' ', '_', $students[0]['student_name']) . "_" . $academic_year . "_" . $term . ".pdf";
} else {
    $filename = "Report_Cards_" . str_replace(' ', '_', $class_name) . "_" . $academic_year . "_" . $term . ".pdf";
}

// Output PDF
$dompdf->stream($filename, [
    'Attachment' => true
]);

$connection->close();
?>