<?php 
ob_start();
require_once('tcpdf/tcpdf.php');
require_once('db_connection.php');

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['report_class'])) {
    $class = $_POST['report_class'];
    $term = $_POST['report_term'] ?? 'N/A';
    $year = $_POST['report_year'] ?? 'N/A';

    $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('P', 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);

        $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 - $term $year", 0, 1, 'C');

        $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>", true, false, false, false, '');
        $pdf->writeHTML("<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>", true, false, false, false, '');
        $pdf->writeHTML("<hr style='border:1px solid rgb(182, 15, 140);'>", true, false, false, false, '');

        $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, '');
            $midtermTable = '<table border="1" cellpadding="4">
            <thead>
                <tr style="background-color:#eee;">
                    <th>LEARNING AREA</th><th>MARKS OBTAINED</th><th>OUT OF</th><th>AGG</th><th>TEACHER\'S COMMENT</th><th>INITIAL</th>
                </tr>
            </thead>
            <tbody>';
            $subjects = ['MTC' => 'MATHS', 'ENG' => 'ENGLISH', 'SST' => 'SST', 'SCI' => 'SCIENCE'];
            foreach ($subjects as $code => $name) {
                $agg = $midterm[$code.'_AGG'] ?? '';
                $mark = $midterm[$code] ?? '';
                $midtermTable .= "<tr><td>$name</td><td>$mark</td><td>100</td><td>$agg</td><td></td><td></td></tr>";
            }
            $midtermTable .= '<tr><td colspan="6"><strong>GENERAL COMMENT:</strong></td></tr></tbody></table>';
            $pdf->writeHTML($midtermTable, true, false, false, false, '');
        }

        $pdf->writeHTML('<h3 style="color:#28A745;">END OF TERM RESULTS</h3>', true, false, false, false, '');
        $eotTable = '<table border="1" cellpadding="4">
        <thead>
            <tr style="background-color:#eee;">
                <th>LEARNING AREA</th><th>MARKS OBTAINED</th><th>OUT OF</th><th>AGG</th><th>TEACHER\'S COMMENT</th><th>INITIAL</th>
            </tr>
        </thead>
        <tbody>';
        foreach ($subjects as $code => $name) {
            $agg = $student[$code.'_AGG'] ?? '';
            $mark = $student[$code] ?? '';
            $eotTable .= "<tr><td>$name</td><td>$mark</td><td>100</td><td>$agg</td><td></td><td></td></tr>";
        }
        $eotTable .= '<tr><td colspan="6"><strong>GENERAL COMMENT:</strong></td></tr></tbody></table>';
        $pdf->writeHTML($eotTable, true, false, false, false, '');

        $pdf->writeHTML("<strong>Class Teacher's Comment:</strong> " . ($student['REMARKS'] ?? ''), true, false, false, false, '');

        $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, '');

        $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 = 'Avoid missing exams.';
        }
        $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();
    $pdf->Output("Class_Report_$class.pdf", 'I');
    exit;
}
?>
