<?php  
ob_start();
require_once('tcpdf/tcpdf.php');
require_once('db_connection.php');

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['report_class'], $_POST['student_id'])) {
    $class = $_POST['report_class'];
    $term = $_POST['report_term'] ?? 'N/A';
    $year = $_POST['report_year'] ?? 'N/A';
    $student_id = $_POST['student_id'];

    // Fetch ONLY the selected sponsored student in this class
    $stmt = $pdo->prepare("
        SELECT s.STUDENT_ID, s.STUDENT_NAME, s.CLASS, s.STATUS,
               e.MTC, e.ENG, e.LIT1, e.LIT2, e.RE, e.TOTAL_MARKS, e.REMARKS, e.POSITION
        FROM STUDENTS s
        LEFT JOIN EOT_RANKED_RESULTS e 
            ON s.STUDENT_ID = e.STUDENT_ID AND e.CLASS = s.CLASS AND e.TERM = ?
        WHERE s.CLASS = ? AND s.STUDENT_ID = ? AND s.STATUS = 'Sponsored'
        ORDER BY s.STUDENT_NAME ASC
    ");
    $stmt->execute([$term, $class, $student_id]);
    $students = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if (!$students) {
        ob_end_clean();
        die('No Sponsored student found for the selected student ID.');
    }


    $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);

    $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' => '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' => 'KS', 'ENG' => 'S', 'SST' => 'AS', 'SCI' => 'DM'],
        'P5' => ['MTC' => 'NR', 'ENG' => 'NR', 'SST' => 'AD', 'SCI' => 'RI'],
        'P6' => ['MTC' => 'AH', 'ENG' => 'AJ', 'SST' => 'BI', 'SCI' => 'BJ'],
        'P7' => ['MTC' => 'OD', 'ENG' => 'SE', 'SST' => 'AP', 'SCI' => 'BY']
    ];
    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);

        $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, "STUDENT'S TERMLY PROGRESSIVE REPORT - $term $year", 0, 1, 'C');
        $pdf->Ln(5);

        $id = $student['STUDENT_ID'];
        $name = $student['STUDENT_NAME'];
        $position = $student['POSITION'] ?? 'N/A';
        $status = $student['STATUS'];
        
        $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> $id<br>
            <strong>Name:</strong> $name<br>
            <strong>Class:</strong> $class<br>
            <strong>Position:</strong> $position<br>
            <strong>Status:</strong> $status
            </div>
        ", true, false, false, false, '');

        // MIDTERM Results
        $stmtMid = $pdo->prepare("SELECT * FROM MIDTERM_LOWER WHERE STUDENT_ID = ? AND CLASS = ? AND TERM = ?");
        $stmtMid->execute([$id, $class, $term]);
        $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</th><th>COMMENT</th><th>INITIAL</th></tr></thead><tbody>';

            foreach ($subjects as $code) {
                $rawMark = $midterm[$code] ?? 'X';
                $mark = is_numeric($rawMark) ? (int)$rawMark : $rawMark;
                $comment = is_numeric($rawMark) ? getComment($code, $mark, $commentsMap) : 'Absent';
                $initial = $initials[$class][$code] ?? '';
                $midtermTable .= "<tr><td>$code</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, '');

        if ($midterm_total <= 100) {
            $midtermRemark = "Needs significant improvement. Please work harder.";
        } elseif ($midterm_total <= 200) {
            $midtermRemark = "Below average performance. Keep trying.";
        } elseif ($midterm_total <= 300) {
            $midtermRemark = "Average performance. Good effort.";
        } elseif ($midterm_total <= 400) {
            $midtermRemark = "Above average. Well done!";
        } elseif ($midterm_total <= 500) {
            $midtermRemark = "Excellent performance. Keep it up!";
        } else {
            $midtermRemark = "Invalid total marks.";
        }

        $pdf->writeHTML("<strong>Class Teacher's Comment:</strong> " . htmlspecialchars($midtermRemark), true, false, false, false, '');
    } // 👈 THIS is the missing brace that fixes the parse error


        // EOT Results
        $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</th><th>COMMENT</th><th>INITIAL</th></tr></thead><tbody>';

        foreach ($subjects as $code) {
            $rawMark = $student[$code] ?? 'X';
            $mark = is_numeric($rawMark) ? (int)$rawMark : $rawMark;
            $comment = is_numeric($rawMark) ? getComment($code, $mark, $commentsMap) : 'Absent';
            $initial = $initials[$class][$code] ?? '';
            $eotTable .= "<tr><td>$code</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, '');

        $pdf->writeHTML("<strong>Class Teacher's Comment:</strong> " . htmlspecialchars($student['REMARKS'] ?? ''), true, false, false, false, '');

        // Requirements 
    $pdf->Ln(2);
    $pdf->SetFont('helvetica', 11);
    $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:<br> P1-P2 Ugx75,000 P3-P6 Ugx85,000 P7 Ugx90,000</td><td>Paid at Bank with Pay Code</td></tr><tr><td>A REAM OF DOUBLE A/DOLOPHINE/ROTATRIM 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, '');

        if ($eot_total <= 100) {
    $headteacherRemark = "Needs significant improvement. Please work harder.";
} elseif ($eot_total <= 200) {
    $headteacherRemark = "Below average performance. Keep trying.";
} elseif ($eot_total <= 300) {
    $headteacherRemark = "Average performance. Good effort.";
} elseif ($eot_total <= 400) {
    $headteacherRemark = "Above average. Well done!";
} elseif ($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');

        $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("Sponsored_Reports_$class.pdf", 'I');
    exit;
}
?>
