<?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 midterm_results WHERE CLASS = ? AND TERM = ? AND YEAR = ? ORDER BY DIVISION ASC");
    $stmt->execute([$class, $term, $year]);
    $students = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if (!$students) {
        ob_end_clean();
        die('No Reports 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(7, 8, 7);
    $pdf->SetAutoPageBreak(false);
    $pdf->SetFont('helvetica', '', 9);

    $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, $map) {
        foreach ($map[$subject] as $range) {
            if ($mark >= $range[0] && $mark <= $range[1]) return $range[2];
        }
        return '';
    }

    $reportCount = 0;
    $reportsPerPage = 2;
    $reportHeight = 145; // fits 2 on A4 (297mm)

    foreach ($students as $student) {
        if ($reportCount % $reportsPerPage === 0) {
            $pdf->AddPage();
        }

        $startY = 8 + ($reportHeight * ($reportCount % $reportsPerPage));
        $pdf->SetY($startY);
        $pdf->SetFont('helvetica', '', 9);

        // Header & Logo
       // Centered logo + text block using a table
$headerHTML = '
<table cellpadding="4" style="margin:auto; text-align:center;">
    <tr>
        <td width="20%">
            <img src="logo.png" width="40">
        </td>
        <td width="80%" style="line-height:1.3;">
            <span style="font-size:13pt; font-weight:bold;">LUZIRA CHURCH OF UGANDA PRIMARY SCHOOL</span><br>
            <span style="font-size:10pt;">P.O.BOX 20061, KAMPALA - Uganda</span><br>
            <span style="font-size:10pt; font-weight:bold;">STUDENT\'S MIDTERM RESULTS - '.htmlspecialchars($term).' '.htmlspecialchars($year).'</span>
        </td>
    </tr>
</table>
';

// Write the header table
$pdf->writeHTML($headerHTML, true, false, false, false, '');

// Add a bit of spacing below to avoid overlap with next content
$pdf->Ln(3);


        // Student Info
        $student_id = $student['STUDENT_ID'] ?? 'N/A';
        $student_name = $student['STUDENT_NAME'] ?? 'N/A';
        $student_class = $student['CLASS'] ?? 'N/A';
        $student_sex = $student['SEX'] ?? 'N/A';
        $pdf->writeHTML("<strong>ID:</strong> $student_id &nbsp;&nbsp; <strong>Name:</strong> $student_name &nbsp;&nbsp; <strong>Class:</strong> $student_class &nbsp;&nbsp; <strong>Sex:</strong> $student_sex", true, false, false, false, '');

        // Midterm Data
        $stmtMid = $pdo->prepare("SELECT * FROM midterm_results WHERE STUDENT_ID = ? AND CLASS = ? AND TERM = ? AND YEAR = ?");
        $stmtMid->execute([$student['STUDENT_ID'], $student['CLASS'], $term, $year]);
        $midterm = $stmtMid->fetch(PDO::FETCH_ASSOC);
        $midterm_total = $midterm['TOTAL_MARKS'] ?? '';
        $midterm_agg = $midterm['TOTAL_AGG'] ?? '';
        $midterm_div = $midterm['DIVISION'] ?? '';

        if ($midterm) {
            $midtermTable = '<table border="1" cellpadding="2" cellspacing="0">
            <thead><tr style="background-color:#eee;">
            <th>SUBJECT</th><th>MARK</th><th>OUT OF</th><th>AGG</th><th>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='font-weight:bold; background-color:#f5f5f5;'>
            <td>Total</td><td>$midterm_total</td><td>400</td><td>$midterm_agg</td><td>Div: $midterm_div</td><td></td>
            </tr></tbody></table>";
            $pdf->writeHTML($midtermTable, true, false, false, false, '');
        }

        // Class teacher comment
        $pdf->writeHTML("<strong>Class Teacher's Comment:</strong> " . ($student['REMARKS'] ?? ''), true, false, false, false, '');

        // Add spacing and title before Requirements table
$pdf->Ln(2); // vertical space before the title
$pdf->writeHTML('<h3 style="color:#003366; font-size:12pt;">Requirements</h3>', true, false, false, false, '');

// Now the table
$requirements = '<table border="1" cellpadding="1.5" cellspacing="0">
<tr style="background-color:#f2f2f2;"><th width="70%">Item</th><th width="30%">Status</th></tr>
<tr><td>PARENTS CONTRIBUTION</td><td>Bank</td></tr>
<tr><td>REAM OF DOUBLE A PAPER</td><td>Provided</td></tr>
<tr><td>4 ROLLS OF TISSUE</td><td>Provided</td></tr>
</table>';
$pdf->writeHTML($requirements, 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 = 'Avoid missing exams.';

        $pdf->writeHTML('<strong>Headteacher\'s Comment:</strong> ' . $ht_comment, true, false, false, false, '');

        // Signature and footer
        $sigY = $pdf->GetY();
        $pdf->Image('signature.png', $pdf->GetX(), $sigY, 15);
        $pdf->SetY($sigY + 12);
        $pdf->Cell(30, 5, 'Headteacher', 0, 1, 'L');

        $pdf->SetFont('', 'BI');
        $pdf->SetTextColor(255, 255, 255);
        $pdf->SetFillColor(0, 0, 0);
        $pdf->Cell(0, 5, 'Verify results via https://luziracouprimaryschool.com/', 0, 1, 'R', true);
        $pdf->SetTextColor(0, 0, 0);
        $pdf->SetFont('', '');

        $reportCount++;
    }

    ob_end_clean();
    $pdf->Output("Class_Report_$class.pdf", 'I');
    exit;
}
?>
