<?php
ob_start(); // Prevent premature output

require_once('tcpdf/tcpdf.php');
require_once('db_connection.php');

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['report_class'])) {
    $class = $_POST['report_class'];

    // Fetch ranked results
    $stmt = $pdo->prepare("SELECT * FROM RANKED_RESULTS WHERE CLASS = ? ORDER BY POSITION ASC");
    $stmt->execute([$class]);
    $students = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if (!$students) {
        ob_end_clean();
        die('No students found for this class.');
    }

    $pdf = new TCPDF('L', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
    $pdf->SetCreator('Luzira COU Primary School');
    $pdf->SetAuthor('Luzira COU Primary School');
    $pdf->SetTitle("Class Report - $class");
    $pdf->setPrintHeader(false);
    $pdf->setPrintFooter(false);
    $pdf->SetMargins(5, 4, 5);
    $pdf->SetAutoPageBreak(TRUE, 10);
    $pdf->SetFont('helvetica', '', 10);

    foreach ($students as $student) {
        $pdf->AddPage();
        $pdf->Rect(5, 5, $pdf->getPageWidth() - 10, $pdf->getPageHeight() - 10);

        // Header
        $pdf->Image('logo.png', 7, 5, 20);
        $pdf->SetFont('helvetica', 'B', 16);
        $pdf->Cell(0, 10, 'LUZIRA CHURCH OF UGANDA PRIMARY SCHOOL', 0, 1, 'C');
        $pdf->SetFont('helvetica', 'B', 12);
        $pdf->Cell(0, 5, "P.O.BOX 20061, KAMPALA -Uganda", 0, 1, 'C');
        $pdf->Cell(0, 5, "STUDENT'S TERMLY PROGRESSIVE REPORT FOR - " . $student['STUDENT_ID'], 0, 1, 'C');

        // Student Info
        $student_name = $student['STUDENT_NAME'] ?? 'N/A';
        $student_class = $student['CLASS'] ?? 'N/A';
        $student_sex = $student['SEX'] ?? 'N/A';
        $student_position = $student['POSITION'] ?? 'N/A';

       $pdf->writeHTML("
    <div style='background-color:#dbe4f3; padding:5px; font-weight:bold; font-size:12pt; color:#003366;'>
        Pupil's Details
    </div>
    <div style='line-height:1.5; font-size:10pt; padding-left:5px; padding-top:4px;'>
        <strong>Name:</strong> $student_name<br>
        <strong>Class:</strong> $student_class<br>
        <strong>Sex:</strong> $student_sex<br>
        <strong>Position:</strong> $student_position
    </div>
    <hr style='border:1px solidrgb(182, 15, 140);'>", true, false, false, false, '');


        // Midterm Results
        $stmtMid = $pdo->prepare("SELECT * FROM midterm_results WHERE STUDENT_ID = ?");
        $stmtMid->execute([$student['STUDENT_ID']]);
        $midterm = $stmtMid->fetch(PDO::FETCH_ASSOC);

        if ($midterm) {
            $pdf->writeHTML('<h3 style="color:#007BFF;">Midterm Results</h3>', true, false, false, false, '');
            $pdf->writeHTML('
                <table border="1" cellpadding="1">
                    <tr>
                        <th>ENG</th><th>ENG_AGG</th>
                        <th>MTC</th><th>MTC_AGG</th>
                        <th>SST</th><th>SST_AGG</th>
                        <th>SCI</th><th>SCI_AGG</th>
                        <th>Total</th><th>T_Agg</th><th>Division</th>
                    </tr>
                    <tr>
                        <td>' . ($midterm['ENG'] ?? '') . '</td><td>' . ($midterm['ENG_AGG'] ?? '') . '</td>
                        <td>' . ($midterm['MTC'] ?? '') . '</td><td>' . ($midterm['MTC_AGG'] ?? '') . '</td>
                        <td>' . ($midterm['SST'] ?? '') . '</td><td>' . ($midterm['SST_AGG'] ?? '') . '</td>
                        <td>' . ($midterm['SCI'] ?? '') . '</td><td>' . ($midterm['SCI_AGG'] ?? '') . '</td>
                        <td>' . ($midterm['TOTAL_MARKS'] ?? '') . '</td>
                        <td>' . ($midterm['TOTAL_AGG'] ?? '') . '</td>
                        <td>' . ($midterm['DIVISION'] ?? '') . '</td>
                    </tr>
                </table>', true, false, false, false, '');
        }

        // End of Term Results
        $pdf->writeHTML('<h3 style="color:#28A745;">End of Term Results</h3>', true, false, false, false, '');
        $pdf->writeHTML('
            <table border="1" cellpadding="1">
                    <tr>
                        <th>ENG</th><th>ENG_AGG</th>
                        <th>MTC</th><th>MTC_AGG</th>
                        <th>SST</th><th>SST_AGG</th>
                        <th>SCI</th><th>SCI_AGG</th>
                        <th>Total</th><th>T_Agg</th><th>Division</th>
                    </tr>
                    <tr>
                        <td>' . ($student['ENG'] ?? '') . '</td><td>' . ($student['ENG_AGG'] ?? '') . '</td>
                        <td>' . ($student['MTC'] ?? '') . '</td><td>' . ($student['MTC_AGG'] ?? '') . '</td>
                        <td>' . ($student['SST'] ?? '') . '</td><td>' . ($student['SST_AGG'] ?? '') . '</td>
                        <td>' . ($student['SCI'] ?? '') . '</td><td>' . ($student['SCI_AGG'] ?? '') . '</td>
                        <td>' . ($student['TOTAL_MARKS'] ?? '') . '</td>
                        <td>' . ($student['TOTAL_AGG'] ?? '') . '</td>
                        <td>' . ($student['DIVISION'] ?? '') . '</td>
                    </tr>
                </table>', true, false, false, false, '');

        $pdf->writeHTML('<strong>Class Teacher\'s Comment:</strong> ' . ($student['REMARKS'] ?? ''), true, false, false, false, '');

        // Requirements
        $pdf->Ln(1);
        $pdf->SetFont('helvetica', 'B', 12);
        $pdf->writeHTML('<strong>Requirements</strong>', true, false, false, false, '');

        $requirementsTable = '
        <table border="1" cellpadding="2">
            <tr><th width="65%">Item</th><th width="35%">Status</th></tr>
            <tr><td>PARENTS CONTRIBUTION</td><td>Paid at Bank with Pay Code</td></tr>
            <tr><td>A REAM OF DOUBLE A PAPER</td><td>Provided</td></tr>
            <tr><td>4 ROLLS OF TOILET PAPER</td><td>Provided</td></tr>
        </table>';
        $pdf->writeHTML($requirementsTable, true, false, false, false, '');

        // Headteacher Comment
$div = $student['DIVISION'];
if ($div == '1') {
    $ht_comment = 'Excellent performance. Keep it up.';
} elseif ($div == '2') {
    $ht_comment = 'Good work. Aim higher.';
} elseif ($div == '3') {
    $ht_comment = 'Fair performance. Needs improvement.';
} elseif ($div == '4' || $div == 'U') {
    $ht_comment = 'Work harder next time.';
} else {
    $ht_comment = 'No comment available.';
}
$pdf->writeHTML('<strong>Headteacher\'s Comment:</strong> ' . $ht_comment, true, false, false, false, '');

        $yBefore = $pdf->GetY();
        $pdf->Image('signature.png', $pdf->GetX(), $yBefore, 20);
        $pdf->SetY($yBefore + 20);
        $pdf->Cell(20, 3, 'Headteacher', 0, 1, 'L');
    }

    ob_end_clean(); // Clear any output to avoid header issues
    $pdf->Output("Class_Report_$class.pdf", 'I');
    exit;
}
?>
