<?php
// Improved PDF Generator - Optimized for PDF printing
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();
}

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

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

// 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);
}

// Get all necessary data (same as DOMPDF version)
$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'];

$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();

$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();

// 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, 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 {
    $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");
}

// Get subjects with teacher information
$sql_subjects = "
SELECT s.subject_id, s.subject_name, 
       COALESCE(u.username, 'Not Assigned') as teacher_name
FROM subjects s 
LEFT JOIN class_subject_teachers cst ON s.subject_id = cst.subject_id AND cst.class_id = ?
LEFT JOIN users u ON cst.teacher_id = u.id 
WHERE s.school_id = ? 
ORDER BY s.subject_name";

$stmt_subjects = $connection->prepare($sql_subjects);
$stmt_subjects->bind_param("ii", $class_id, $class_school_id);
$stmt_subjects->execute();
$result_subjects = $stmt_subjects->get_result();

$subjects = [];
while ($row = $result_subjects->fetch_assoc()) {
    $subjects[] = $row;
}

?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Report Cards - PDF Download</title>
    <style>
        /* PDF-Optimized CSS */
        @page {
            size: A4;
            margin: 15mm;
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: Arial, sans-serif;
            font-size: 12px;
            line-height: 1.4;
            color: black;
            background: white;
        }
        
        /* Print-specific styles */
        @media print {
            body { -webkit-print-color-adjust: exact; }
            .page-break { page-break-before: always; }
            .no-print { display: none !important; }
        }
        
        /* Report card container */
        .report-card {
            width: 100%;
            max-width: 210mm;
            margin: 0 auto 20px auto;
            background: white;
            padding: 15px;
            border: 2px solid black;
        }
        
        /* Header styles - using table for better PDF compatibility */
        .header-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 15px;
        }
        
        .header-table td {
            vertical-align: top;
            padding: 5px;
        }
        
        .logo-cell {
            width: 80px;
            text-align: center;
            border: 1px solid black;
        }
        
        .school-info-cell {
            text-align: center;
            border: 1px solid black;
        }
        
        .school-name {
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 5px;
        }
        
        .school-details {
            font-size: 10px;
            margin-bottom: 3px;
        }
        
        .motto {
            font-style: italic;
            font-size: 10px;
            margin-top: 5px;
        }
        
        /* Academic report title */
        .academic-report-title {
            text-align: center;
            background: black;
            color: white;
            padding: 8px;
            margin: 10px 0;
            font-weight: bold;
            font-size: 14px;
        }
        
        /* Student info table */
        .student-info-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 15px;
        }
        
        .student-info-table td {
            border: 1px solid black;
            padding: 8px;
            vertical-align: top;
        }
        
        .photo-cell {
            width: 80px;
            text-align: center;
            height: 100px;
        }
        
        .student-photo {
            width: 70px;
            height: 90px;
            border: 1px solid black;
            object-fit: cover;
        }
        
        .photo-placeholder {
            width: 70px;
            height: 90px;
            border: 1px solid black;
            display: flex;
            align-items: center;
            justify-content: center;
            background: #f0f0f0;
            font-size: 24px;
        }
        
        .info-label {
            font-weight: bold;
            font-size: 10px;
            margin-bottom: 2px;
        }
        
        .info-value {
            font-size: 11px;
            margin-bottom: 5px;
        }
        
        /* Performance stats table */
        .stats-table {
            width: 100%;
            border-collapse: collapse;
            margin: 15px 0;
        }
        
        .stats-table td {
            border: 1px solid black;
            padding: 8px;
            text-align: center;
            background: #f0f0f0;
        }
        
        .stat-value {
            font-size: 14px;
            font-weight: bold;
        }
        
        .stat-label {
            font-size: 9px;
        }
        
        /* Results table */
        .results-title {
            background: black;
            color: white;
            text-align: center;
            padding: 8px;
            margin: 15px 0 5px 0;
            font-size: 12px;
            font-weight: bold;
        }
        
        .results-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 15px;
        }
        
        .results-table th,
        .results-table td {
            border: 1px solid black;
            padding: 6px 4px;
            text-align: center;
            font-size: 9px;
        }
        
        .results-table th {
            background: #f0f0f0;
            font-weight: bold;
        }
        
        .subject-cell {
            text-align: left;
            font-size: 8px;
        }
        
        .teacher-cell {
            text-align: left;
            font-size: 8px;
        }
        
        .grade-cell {
            font-weight: bold;
            background: #f8f8f8;
        }
        
        /* Remarks section */
        .remarks-table {
            width: 100%;
            border-collapse: collapse;
            margin: 15px 0;
        }
        
        .remarks-table td {
            border: 1px solid black;
            padding: 8px;
            vertical-align: top;
        }
        
        .remark-title {
            font-weight: bold;
            font-size: 10px;
            margin-bottom: 5px;
        }
        
        .remark-content {
            font-size: 9px;
            min-height: 40px;
            line-height: 1.3;
        }
        
        /* Footer */
        .footer-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        
        .footer-table td {
            border: 1px solid black;
            padding: 8px;
            text-align: center;
            font-size: 9px;
        }
        
        .qr-cell {
            width: 80px;
            height: 60px;
        }
        
        /* Print instructions */
        .print-instructions {
            text-align: center;
            padding: 20px;
            background: #ffffcc;
            border: 2px solid #ff9900;
            margin: 20px 0;
            font-weight: bold;
        }
        
        /* Watermark */
        .watermark {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%) rotate(-45deg);
            font-size: 48px;
            color: rgba(0,0,0,0.1);
            z-index: -1;
            pointer-events: none;
        }
    </style>
</head>
<body>
    <div class="watermark">REPORT CARD</div>
    
    <div class="print-instructions no-print">
        <h3>📄 PDF Download Instructions</h3>
        <p>Press <strong>Ctrl+P</strong> (Windows) or <strong>Cmd+P</strong> (Mac) to print</p>
        <p>In the print dialog, select <strong>"Save as PDF"</strong> as your destination</p>
        <p>Choose <strong>"A4"</strong> paper size for best results</p>
        <button onclick="window.print()" style="padding: 10px 20px; font-size: 14px; margin-top: 10px;">🖨️ Print / Save as PDF</button>
    </div>

    <?php foreach ($students as $index => $student): ?>
        <?php if ($index > 0): ?>
            <div class="page-break"></div>
        <?php endif; ?>
        
        <div class="report-card">
            <!-- Header -->
            <table class="header-table">
                <tr>
                    <td class="logo-cell">
                        <?php if (!empty($school['logo'])): ?>
                            <img src="<?php echo htmlspecialchars($school['logo']); ?>" style="max-width: 60px; max-height: 60px;" alt="School Logo">
                        <?php else: ?>
                            <div style="width: 60px; height: 60px; border: 1px solid black; display: flex; align-items: center; justify-content: center; font-size: 20px;">📚</div>
                        <?php endif; ?>
                    </td>
                    <td class="school-info-cell">
                        <div class="school-name"><?php echo htmlspecialchars($school['school_name']); ?></div>
                        <div class="school-details"><?php echo htmlspecialchars($school['address']); ?></div>
                        <div class="school-details">Tel: <?php echo htmlspecialchars($school['phone']); ?> | Email: <?php echo htmlspecialchars($school['email']); ?></div>
                        <div class="motto">"<?php echo htmlspecialchars($school['motto']); ?>"</div>
                    </td>
                    <td class="logo-cell">
                        <!-- Space for additional logo or decoration -->
                        <div style="width: 60px; height: 60px; border: 1px solid black; display: flex; align-items: center; justify-content: center; font-size: 20px;">🎓</div>
                    </td>
                </tr>
            </table>

            <!-- Academic Report Title -->
            <div class="academic-report-title">
                ACADEMIC REPORT FOR <?php echo strtoupper(htmlspecialchars($term)); ?> - <?php echo htmlspecialchars($academic_year); ?>
            </div>

            <!-- Student Information -->
            <table class="student-info-table">
                <tr>
                    <td class="photo-cell" rowspan="3">
                        <?php if (!empty($student['photo'])): ?>
                            <img src="<?php echo htmlspecialchars($student['photo']); ?>" class="student-photo" alt="Student Photo">
                        <?php else: ?>
                            <div class="photo-placeholder">👤</div>
                        <?php endif; ?>
                    </td>
                    <td style="width: 25%;">
                        <div class="info-label">STUDENT NAME:</div>
                        <div class="info-value"><?php echo htmlspecialchars($student['student_name']); ?></div>
                    </td>
                    <td style="width: 25%;">
                        <div class="info-label">ADMISSION NO:</div>
                        <div class="info-value"><?php echo htmlspecialchars($student['ADM']); ?></div>
                    </td>
                    <td style="width: 25%;">
                        <div class="info-label">CLASS:</div>
                        <div class="info-value"><?php echo htmlspecialchars($class_name); ?></div>
                    </td>
                </tr>
                <tr>
                    <td>
                        <div class="info-label">PARENT/GUARDIAN:</div>
                        <div class="info-value"><?php echo htmlspecialchars($student['parent_name']); ?></div>
                    </td>
                    <td>
                        <div class="info-label">PHONE:</div>
                        <div class="info-value"><?php echo htmlspecialchars($student['parent_phone']); ?></div>
                    </td>
                    <td>
                        <div class="info-label">EXAM:</div>
                        <div class="info-value"><?php echo htmlspecialchars($exam['exam_name'] ?? 'Academic Report'); ?></div>
                    </td>
                </tr>
                <tr>
                    <td colspan="3">
                        <div class="info-label">PERFORMANCE CHART:</div>
                        <div style="height: 40px; border: 1px solid black; background: #f8f8f8; display: flex; align-items: center; justify-content: center; font-size: 10px;">
                            [Performance Chart Area]
                        </div>
                    </td>
                </tr>
            </table>

            <?php
            // Get student results
            $sql_results = "
            SELECT s.subject_name, s.subject_id, er.mark, 
                   COALESCE(u.username, 'Not Assigned') as teacher_name
            FROM exam_results er
            JOIN subjects s ON er.subject_id = s.subject_id
            LEFT JOIN class_subject_teachers cst ON s.subject_id = cst.subject_id AND cst.class_id = er.class_id
            LEFT JOIN users u ON cst.teacher_id = u.id
            WHERE er.user_id = ? AND er.exam_id = ? AND er.academic_year = ? AND er.term = ?
            ORDER BY s.subject_name";
            
            $stmt_results = $connection->prepare($sql_results);
            $stmt_results->bind_param("iiss", $student['user_id'], $exam_id, $academic_year, $term);
            $stmt_results->execute();
            $result_results = $stmt_results->get_result();
            
            $results = [];
            $total_marks = 0;
            $total_subjects = 0;
            
            while ($row = $result_results->fetch_assoc()) {
                $results[] = $row;
                if ($row['mark'] !== null) {
                    $total_marks += $row['mark'];
                    $total_subjects++;
                }
            }
            
            $average = $total_subjects > 0 ? round($total_marks / $total_subjects, 1) : 0;
            ?>

            <!-- Performance Statistics -->
            <table class="stats-table">
                <tr>
                    <td>
                        <div class="stat-value"><?php echo $total_subjects; ?></div>
                        <div class="stat-label">SUBJECTS</div>
                    </td>
                    <td>
                        <div class="stat-value"><?php echo $total_marks; ?></div>
                        <div class="stat-label">TOTAL MARKS</div>
                    </td>
                    <td>
                        <div class="stat-value"><?php echo $average; ?>%</div>
                        <div class="stat-label">AVERAGE</div>
                    </td>
                    <td>
                        <?php
                        $overall_grade = getGradeFromScale($average, null, $class_id, $academic_year, $term, $class_school_id, $connection);
                        ?>
                        <div class="stat-value"><?php echo htmlspecialchars($overall_grade['grade']); ?></div>
                        <div class="stat-label">GRADE</div>
                    </td>
                </tr>
            </table>

            <!-- Results Table -->
            <div class="results-title">SUBJECT PERFORMANCE</div>
            <table class="results-table">
                <thead>
                    <tr>
                        <th style="width: 25%;">SUBJECT</th>
                        <th style="width: 20%;">TEACHER</th>
                        <th style="width: 10%;">MARK</th>
                        <th style="width: 8%;">GRADE</th>
                        <th style="width: 37%;">COMMENTS</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($results as $result): ?>
                        <?php
                        $grade_info = getGradeFromScale($result['mark'], $result['subject_id'], $class_id, $academic_year, $term, $class_school_id, $connection);
                        ?>
                        <tr>
                            <td class="subject-cell"><?php echo htmlspecialchars($result['subject_name']); ?></td>
                            <td class="teacher-cell"><?php echo htmlspecialchars($result['teacher_name']); ?></td>
                            <td><?php echo $result['mark'] !== null ? $result['mark'] : '-'; ?></td>
                            <td class="grade-cell"><?php echo htmlspecialchars($grade_info['grade']); ?></td>
                            <td style="text-align: left; font-size: 8px;"><?php echo htmlspecialchars($grade_info['remarks']); ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>

            <!-- Remarks Section -->
            <table class="remarks-table">
                <tr>
                    <td style="width: 33%;">
                        <div class="remark-title">CLASS TEACHER'S COMMENTS:</div>
                        <div class="remark-content">
                            <?php echo htmlspecialchars($overall_grade['remarks']); ?>
                        </div>
                    </td>
                    <td style="width: 33%;">
                        <div class="remark-title">HEAD TEACHER'S COMMENTS:</div>
                        <div class="remark-content">
                            [Head Teacher Comments]
                        </div>
                    </td>
                    <td style="width: 34%;">
                        <div class="remark-title">PARENT'S COMMENTS:</div>
                        <div class="remark-content">
                            [Parent Comments]
                        </div>
                    </td>
                </tr>
            </table>

            <!-- Footer -->
            <table class="footer-table">
                <tr>
                    <td style="width: 30%;">
                        <strong>Next Term Begins:</strong><br>
                        _______________
                    </td>
                    <td style="width: 40%;">
                        <strong>Generated:</strong> <?php echo date('d/m/Y H:i'); ?><br>
                        <strong>Report ID:</strong> <?php echo strtoupper(substr(md5($student['user_id'] . $term . $academic_year), 0, 8)); ?>
                    </td>
                    <td class="qr-cell">
                        <div style="border: 1px solid black; height: 50px; display: flex; align-items: center; justify-content: center; font-size: 8px;">
                            QR CODE
                        </div>
                    </td>
                </tr>
            </table>
        </div>
    <?php endforeach; ?>

    <script>
        // Auto-print when page loads (optional)
        // window.onload = function() { window.print(); };
        
        // Hide print instructions when printing
        window.onbeforeprint = function() {
            document.querySelectorAll('.no-print').forEach(el => el.style.display = 'none');
        };
        
        window.onafterprint = function() {
            document.querySelectorAll('.no-print').forEach(el => el.style.display = 'block');
        };
    </script>
</body>
</html>