<?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';

    // Fetch from ranked view for midterm
    $stmt = $pdo->prepare("SELECT * FROM RANKED_MIDTERM_LOWER 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.');
    }

    $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("Midterm Report - $class");
    $pdf->setPrintHeader(false);
    $pdf->setPrintFooter(false);
    $pdf->SetMargins(5, 4, 5);
    $pdf->SetAutoPageBreak(TRUE, 10);
    $pdf->SetFont('helvetica', '', 10);

    $subjects = ['MTC', 'ENG', 'LIT1', 'LIT2', 'RE'];
    $commentsMap = [];
    foreach ($subjects as $subject) {
        $commentsMap[$subject] = [
            [0, 39, 'IMPROVE'], 
            [40, 54, 'TRIED'], 
            [55, 69, 'FAIR'], 
            [70, 89, 'VGOOD'], 
            [90, 100, 'EXCELLENT']
        ];
    }

    $initials = [
        'P1' => ['MTC' => 'MK', 'ENG' => 'MS', 'LIT1' => 'LR', 'LIT2' => 'LD', 'RE' => 'RK'],
        'P2' => ['MTC' => 'AK', 'ENG' => 'AS', 'LIT1' => 'AR', 'LIT2' => 'AD', 'RE' => 'AK'],
        'P3' => ['MTC' => 'BK', 'ENG' => 'BS', 'LIT1' => 'BR', 'LIT2' => 'BD', 'RE' => 'BK']
    ];

    function getComment($subject, $mark, $commentsMap) {
        foreach ($commentsMap[$subject] as $range) {
            if ($mark >= $range[0] && $mark <= $range[1]) return $range[2];
        }
        return '';
    }

    $counter = 0;
    foreach ($students as $student) {
        if ($counter % 2 == 0) {
            $pdf->AddPage();
            $yStart = 10;
        } else {
            $yStart = ($pdf->getPageHeight() / 2) + 5;
        }

        $pdf->SetY($yStart);
        $pdf->SetFont('helvetica', '', 10);
        $pdf->writeHTML('<hr>', true, false, false, false, '');

        // Student info
        $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->SetFont('helvetica', 'B', 12);
        $pdf->Cell(0, 6, 'LUZIRA CHURCH OF UGANDA PRIMARY SCHOOL', 0, 1, 'C');
        $pdf->SetFont('helvetica', 'B', 10);
        $pdf->Cell(0, 5, "MIDTERM REPORT - $term $year", 0, 1, 'C');

        $pdf->writeHTML("<strong>ID:</strong> $student_id<br>
<strong>Name:</strong> $student_name<br>
<strong>Class:</strong> $student_class<br>
<strong>Position:</strong> $student_position", true, false, false, false, '');

        // Results Table
        $midtermTable = '<table border="1" cellpadding="4"><thead><tr style="background-color:#eee;">
<th>LEARNING AREA</th><th>MARKS</th><th>COMMENT</th><th>INITIAL</th></tr></thead><tbody>';

        $midterm_total = 0;

        foreach ($subjects as $code) {
            $rawMark = $student[$code] ?? 'X';
            if (is_numeric($rawMark)) {
                $mark = (int)$rawMark;
                $comment = getComment($code, $mark, $commentsMap);
                $midterm_total += $mark;
            } else {
                $mark = 'X';
                $comment = 'Absent';
            }
            $initial = $initials[$class][$code] ?? '';
            $midtermTable .= "<tr><td>$code</td><td>$mark</td><td>$comment</td><td>$initial</td></tr>";
        }

        $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, '');

        // Headteacher's Comment
        if ($midterm_total >= 0 && $midterm_total <= 100) {
            $remark = "Needs significant improvement. Please work harder.";
        } elseif ($midterm_total >= 101 && $midterm_total <= 200) {
            $remark = "Below average performance. Keep trying.";
        } elseif ($midterm_total >= 201 && $midterm_total <= 300) {
            $remark = "Average performance. Good effort.";
        } elseif ($midterm_total >= 301 && $midterm_total <= 400) {
            $remark = "Above average. Well done!";
        } elseif ($midterm_total >= 401 && $midterm_total <= 500) {
            $remark = "Excellent performance. Keep it up!";
        } else {
            $remark = "Invalid total marks.";
        }

        $pdf->writeHTML('<strong>Headteacher\'s Comment:</strong> ' . $remark, true, false, false, false, '');

        $pdf->Ln(1);
        $pdf->Image('signature.png', $pdf->GetX(), $pdf->GetY(), 20);
        $pdf->SetY($pdf->GetY() + 20);
        $pdf->Cell(20, 3, 'Headteacher', 0, 1, 'L');

        $pdf->SetFont('', 'BI');
        $pdf->SetTextColor(255, 255, 255);
        $pdf->SetFillColor(0, 0, 0);
        $pdf->Cell(0, 6, 'Verify at https://luziracouprimaryschool.com', 0, 1, 'R', true);
        $pdf->SetTextColor(0, 0, 0);
        $pdf->SetFont('', '');

        $counter++;
    }

    ob_end_clean();
    $pdf->Output("Midterm_Reports_$class.pdf", 'I');
    exit;
}
?>
