<?php
ob_start();
require_once('tcpdf/tcpdf.php');
require_once('db_connection.php');

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['report_class'], $_POST['report_term'], $_POST['report_year'], $_POST['student_id'])) {
    $class = $_POST['report_class'];
    $term = $_POST['report_term'];
    $year = $_POST['report_year'];
    $student_id = $_POST['student_id'];

    $stmt = $pdo->prepare("
        SELECT r.*, s.STUDENT_NAME, s.CLASS, s.SEX
        FROM RANKED_RESULTS r
        INNER JOIN STUDENTS s ON r.STUDENT_ID = s.STUDENT_ID
        WHERE s.STATUS = 'Sponsored'
          AND r.STUDENT_ID = ?
          AND r.TERM = ?
          AND r.YEAR = ?
    ");
    $stmt->execute([$student_id, $term, $year]);
    $student = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$student) {
        ob_end_clean();
        die('No report found for the selected student.');
    }

    // PDF Setup
    $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("Student Report - {$student['STUDENT_NAME']}");
    $pdf->setPrintHeader(false);
    $pdf->setPrintFooter(false);
    $pdf->SetMargins(5, 4, 5);
    $pdf->SetAutoPageBreak(TRUE, 10);
    $pdf->SetFont('helvetica', '', 10);

    $commentsMap = [
        'MTC' => [[0, 39, 'IMPROVE'], [40, 54, 'TRIED'], [55, 69, 'FAIR'], [70, 89, 'VGOOD'], [90, 100, 'EXCELLENT']],
        'ENG' => [[0, 39, 'IMPROVE'], [40, 54, 'TRIED'], [55, 69, 'FAIR'], [70, 89, 'VGOOD'], [90, 100, 'EXCELLENT']],
        'SST' => [[0, 39, 'IMPROVE'], [40, 54, 'TRIED'], [55, 69, 'FAIR'], [70, 89, 'VGOOD'], [90, 100, 'EXCELLENT']],
        'SCI' => [[0, 39, 'IMPROVE'], [40, 54, 'TRIED'], [55, 69, 'FAIR'], [70, 89, 'VGOOD'], [90, 100, 'EXCELLENT']]
    ];

    $initials = [
        'P1' => ['MTC' => 'KA', 'ENG' => 'MA', 'SST' => 'JJ', 'SCI' => 'LL'],
        'P2' => ['MTC' => 'KK', 'ENG' => 'HH', 'SST' => 'QQ', 'SCI' => 'DD'],
        'P3' => ['MTC' => 'MN', 'ENG' => 'PA', 'SST' => 'RR', 'SCI' => 'EE'],
        'P4' => ['MTC' => 'ZA', 'ENG' => 'ZA', 'SST' => 'ZA', 'SCI' => 'ZA'],
        'P5' => ['MTC' => 'ZA', 'ENG' => 'ZA', 'SST' => 'ZA', 'SCI' => 'ZA'],
        'P6' => ['MTC' => 'ZA', 'ENG' => 'ZA', 'SST' => 'ZA', 'SCI' => 'ZA'],
        'P7' => ['MTC' => 'ZA', 'ENG' => 'ZA', 'SST' => 'ZA', 'SCI' => 'ZA']
    ];

    function getComment($subject, $mark, $commentsMap) {
        foreach ($commentsMap[$subject] as $range) {
            if ($mark >= $range[0] && $mark <= $range[1]) return $range[2];
        }
        return '';
    }

    // START PAGE
    $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 Details
    $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>ID:</strong> {$student['STUDENT_ID']}<br>
        <strong>Name:</strong> {$student['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, '');

    // Midterm Results
    $stmtMid = $pdo->prepare("SELECT * FROM midterm_results WHERE STUDENT_ID = ? AND CLASS = ? AND TERM = ? AND YEAR = ?");
    $stmtMid->execute([$student_id, $class, $term, $year]);
    $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>';
        foreach ($commentsMap as $code => $ranges) {
            $mark = $midterm[$code] ?? 0;
            $agg = $midterm[$code.'_AGG'] ?? '';
            $comment = getComment($code, $mark, $commentsMap);
            $initial = $initials[$class][$code] ?? '';
            $midtermTable .= "<tr><td>$code</td><td>$mark</td><td>100</td><td>$agg</td><td>$comment</td><td>$initial</td></tr>";
        }
        $midtermTable .= "<tr style='background-color:#f0f0f0; font-weight:bold; font-family:cursive;'> 
            <td>TOTAL MARKS</td><td>{$midterm['TOTAL_MARKS']}</td><td>TOTAL AGG</td><td>{$midterm['TOTAL_AGG']}</td><td>DIVISION</td><td>{$midterm['DIVISION']}</td>
        </tr></tbody></table>";
        $pdf->writeHTML($midtermTable, true, false, false, false, '');
    }

    // End of Term
    $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 ($commentsMap as $code => $ranges) {
        $mark = $student[$code] ?? 0;
        $agg = $student[$code.'_AGG'] ?? '';
        $comment = getComment($code, $mark, $commentsMap);
        $initial = $initials[$class][$code] ?? '';
        $eotTable .= "<tr><td>$code</td><td>$mark</td><td>100</td><td>$agg</td><td>$comment</td><td>$initial</td></tr>";
    }
    $eotTable .= "<tr style='border: 1px solid black; font-weight: bold; text-align: center;'>
        <td>TOTAL MARKS</td><td>{$student['TOTAL_MARKS']}</td><td>TOTAL AGG</td><td>{$student['TOTAL_AGG']}</td><td>DIVISION</td><td>{$student['DIVISION']}</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, '');

    // 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 by parent</td></tr>
        <tr><td>4 ROLLS OF TOILET PAPER</td><td>Provided by parent</td></tr>
    </table>';
    $pdf->writeHTML($requirementsTable, true, false, false, false, '');

    // Headteacher's 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 = 'Avoid missing exams.';
    }
    $pdf->writeHTML('<strong>Headteacher\'s Comment:</strong> ' . $ht_comment, true, false, false, false, '');

    // Signature and Footer
    $yBefore = $pdf->GetY();
    $pdf->Image('signature.png', $pdf->GetX(), $yBefore, 20);
    $pdf->SetY($yBefore + 20);
    $pdf->Cell(20, 3, 'Headteacher', 0, 1, 'L');

    $pdf->Ln(1);
    $pdf->SetFont('', 'BI');
    $pdf->SetTextColor(255, 255, 255);
    $pdf->SetFillColor(0, 0, 0);
    $pdf->Cell(0, 6, 'Disclaimer: These results can be verified via our website https://luziracouprimaryschool.com/', 0, 1, 'R', true);
    $pdf->SetTextColor(0, 0, 0);
    $pdf->SetFont('', '');

    ob_end_clean();
    $pdf->Output("Student_Report_{$student['STUDENT_ID']}.pdf", 'I');
    exit;
}
?>
