<?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';

    // EOT_LOWER fetch
    $stmt = $pdo->prepare("SELECT * FROM EOT_RANKED_RESULTS WHERE CLASS = ? AND TERM = ? ORDER BY POSITION ASC");
    $stmt->execute([$class, $term]);
    $students = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if (!$students) {
        ob_end_clean();
        die('No Reports found for this class.');
    }

    // Get total number of students in this class for this term
    $totalStudentsStmt = $pdo->prepare("SELECT COUNT(*) as total FROM EOT_RANKED_RESULTS WHERE CLASS = ? AND TERM = ?");
    $totalStudentsStmt->execute([$class, $term]);
    $totalStudents = $totalStudentsStmt->fetch(PDO::FETCH_ASSOC)['total'] ?? 0;

    $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);

    // Subject codes
    $subjects = ['MTC', 'ENG', 'LIT1', 'LIT2', 'RE'];

    // Mapping subject codes to names
    $subjectNames = [
        'MTC'  => 'Mathematics',
        'ENG'  => 'English',
        'LIT1' => 'Literacy 1',
        'LIT2' => 'Literacy 2',
        'RE'   => 'Religious Education'
    ];

    // Comment ranges
    $commentsMap = [];
    foreach ($subjects as $subject) {
        $commentsMap[$subject] = [
            [0, 39, 'Improve'], 
            [40, 54, 'Tried'], 
            [55, 69, 'Fair'], 
            [70, 89, 'Very Good'], 
            [90, 100, 'Excellent']
        ];
    }

    // Teacher initials
    $initials = [
        'P1' => ['MTC' => 'Bj', 'ENG' => 'Kc', 'LIT1' => 'Bj', 'LIT2' => 'Nr', 'RE' => 'Nr'],
        'P2' => ['MTC' => 'Na', 'ENG' => 'Ne', 'LIT1' => 'As', 'LIT2' => 'As', 'RE' => 'Ne'],
        'P3' => ['MTC' => 'Hr', 'ENG' => 'Km', 'LIT1' => 'Km', 'LIT2' => 'Ke', 'RE' => 'BK']
    ];

    // Function to get comment
    function getComment($subject, $mark, $commentsMap) {
        foreach ($commentsMap[$subject] as $range) {
            if ($mark >= $range[0] && $mark <= $range[1]) return $range[2];
        }
        return '';
    }

    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, 5, 'LUZIRA CHURCH OF UGANDA PRIMARY SCHOOL', 0, 1, 'C');
        $pdf->SetFont('helvetica', 'B', 7);
        $pdf->Cell(0, 5, 'P.O BOX 20061, KAMPALA-UG: Email: luziracouprim@ymail.com Website: https://luziracouprimaryschool.com/', 0, 1, 'C');
        $pdf->SetFont('helvetica', 'B', 12);
        $pdf->Cell(0, 5, "STUDENT'S TERMLY PROGRESSIVE REPORT - $term $year", 0, 1, 'C');
        $pdf->Ln(5);

        // Student details
        $student_id = $student['STUDENT_ID'] ?? 'N/A';
        $student_name = $student['STUDENT_NAME'] ?? 'N/A';
        $student_class = $student['CLASS'] ?? 'N/A';
        $student_position = $student['POSITION'] ?? 'N/A';

        $pdf->Ln(5);
        $pdf->writeHTML("<div style='background-color:#dbe4f3; padding:5px; font-weight:bold; font-size:10pt; 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>ID:</strong> $student_id<br>
<strong>Name:</strong> $student_name<br>
<strong>Class:</strong> $student_class<br>
<strong>Position:</strong> $student_position out of $totalStudents
</div>", true, false, false, false, '');

        // MIDTERM RESULTS
        $pdf->Ln(5);
        $stmtMid = $pdo->prepare("SELECT * FROM MIDTERM_LOWER WHERE STUDENT_ID = ? AND CLASS = ? AND TERM = ?");
        $stmtMid->execute([$student['STUDENT_ID'], $student['CLASS'], $term]);
        $midterm = $stmtMid->fetch(PDO::FETCH_ASSOC);

        if ($midterm) {
            $pdf->writeHTML('<h4 style="color:#007BFF;">MIDTERM RESULTS</h4>', true, false, false, false, '');
            $midtermTable = '<table border="1" cellpadding="4"><thead>
            <tr style="background-color:#eee;"><th>SUBJECT</th><th>MARKS</th><th>COMMENT</th><th>INITIAL</th></tr></thead><tbody>';

            foreach ($subjects as $code) {
                $rawMark = $midterm[$code] ?? 'X';
                if (is_numeric($rawMark)) {
                    $mark = (int)$rawMark;
                    $comment = getComment($code, $mark, $commentsMap);
                } else {
                    $mark = $rawMark;
                    $comment = 'Absent';
                }
                $initial = $initials[$class][$code] ?? '';
                $subjectName = $subjectNames[$code] ?? $code;
                $midtermTable .= "<tr><td>$subjectName</td><td>$mark</td><td>$comment</td><td>$initial</td></tr>";
            }
            $midterm_total = isset($midterm['TOTAL_MARKS']) ? (int)$midterm['TOTAL_MARKS'] : 0;
            $midtermTable .= "<tr style='font-weight:bold; background-color:#ddd;'><td>Total Marks</td><td>$midterm_total</td><td colspan='2'></td></tr>";
            $midtermTable .= "</tbody></table>";
            $pdf->writeHTML($midtermTable, true, false, false, false, '');
        }

        // END OF TERM RESULTS
        $pdf->writeHTML('<h4 style="color:#28A745;">END OF TERM RESULTS</h4>', true, false, false, false, '');
        $eotTable = '<table border="1" cellpadding="4"><thead>
        <tr style="background-color:#eee;"><th>SUBJECT</th><th>MARKS</th><th>COMMENT</th><th>INITIAL</th></tr></thead><tbody>';

        foreach ($subjects as $code) {
            $rawMark = $student[$code] ?? 'X';
            if (is_numeric($rawMark)) {
                $mark = (int)$rawMark;
                $comment = getComment($code, $mark, $commentsMap);
            } else {
                $mark = $rawMark;
                $comment = 'Absent';
            }
            $initial = $initials[$class][$code] ?? '';
            $subjectName = $subjectNames[$code] ?? $code;
            $eotTable .= "<tr><td>$subjectName</td><td>$mark</td><td>$comment</td><td>$initial</td></tr>";
        }
        $eot_total = isset($student['TOTAL_MARKS']) ? (int)$student['TOTAL_MARKS'] : 0;
        $eotTable .= "<tr style='font-weight:bold; background-color:#ddd;'><td>Total Marks</td><td>$eot_total</td><td colspan='2'></td></tr>";
        $eotTable .= "</tbody></table>";
        $pdf->writeHTML($eotTable, true, false, false, false, '');

        // Class Teacher's remarks
        $classTeacherComment = $student['REMARKS'] ?? '';
        $pdf->writeHTML("<strong>Class Teacher's Comment:</strong> " . htmlspecialchars($classTeacherComment), true, false, false, false, '');

        // Requirements
        $pdf->Ln(1);
        $pdf->SetFont('helvetica', 'B', 9);
        $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: Ugshs75,000 p1-P2, Ugshs85,000 P3-P5 and Ugshs115,000 for P6-P7</td><td>Should be paid with school pay code at the bank.</td></tr>
        <tr><td>A REAM OF PAPER</td><td>Should be provided by the parent.</td></tr>
        <tr><td>TOILET PAPER</td><td>Should be provided by the parent.</td></tr></table>';
        $pdf->writeHTML($requirementsTable, true, false, false, false, '');

        // Headteacher's comment based on EOT marks
        if ($eot_total >= 0 && $eot_total <= 100) {
            $headteacherRemark = "Needs significant improvement. Please work harder.";
        } elseif ($eot_total >= 101 && $eot_total <= 200) {
            $headteacherRemark = "Below average performance. Keep trying.";
        } elseif ($eot_total >= 201 && $eot_total <= 300) {
            $headteacherRemark = "Average performance. Good effort.";
        } elseif ($eot_total >= 301 && $eot_total <= 400) {
            $headteacherRemark = "Above average. Well done!";
        } elseif ($eot_total >= 401 && $eot_total <= 500) {
            $headteacherRemark = "Excellent performance. Keep it up!";
        } else {
            $headteacherRemark = "Invalid total marks.";
        }
        $pdf->writeHTML('<strong>Headteacher\'s Comment:</strong> ' . $headteacherRemark, true, false, false, false, '');

        // Signature
        $pdf->Ln(1);
        $yBefore = $pdf->GetY();
        $pdf->Image('signature.png', $pdf->GetX(), $yBefore, 20);
        $pdf->SetY($yBefore + 20);
        $pdf->Cell(20, 3, 'Headteacher', 0, 1, 'L');

        // Footer
        $pdf->Ln(1);
        $pdf->SetFont('', 'BI');
        $pdf->SetTextColor(255, 255, 255);
        $pdf->SetFillColor(0, 0, 0);
        $pdf->Cell(0, 6, 'Results can be verified at https://luziracouprimaryschool.com', 0, 1, 'R', true);
        $pdf->SetTextColor(0, 0, 0);
        $pdf->SetFont('', '');
    }

    ob_end_clean();
    $pdf->Output("Lower_Class_Report_$class.pdf", 'I');
    exit;
}
?>
