<?php
require_once('tcpdf/tcpdf.php');
require_once('db_connection.php');

if (!isset($_POST['CLASS'])) {
    die('Class not specified.');
}

$class = $_POST['CLASS'];
$stmt = $pdo->prepare("SELECT * FROM RESULTS WHERE CLASS = ? ORDER BY STUDENT_NAME");
$stmt->execute([$class]);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

if (!$results) {
    die('No results found for selected class.');
}

// Column headers in order
$headers = ['STUDENT_ID', 'STUDENT_NAME', 'SEX', 'CLASS', 'MTC', 'MTC_AGG', 'ENG', 'ENG_AGG', 'SST', 'SST_AGG', 'SCI', 'SCI_AGG', 'TOTAL_MARKS', 'TOTAL_AGG', 'DIVISION', 'REMARKS'];

// Calculate dynamic column widths
$colWidths = array_fill_keys($headers, 0);
foreach ($headers as $header) {
    $colWidths[$header] = strlen($header);
}
foreach ($results as $row) {
    foreach ($headers as $header) {
        $colWidths[$header] = max($colWidths[$header], strlen($row[$header]));
    }
}
foreach ($colWidths as $key => $len) {
    $colWidths[$key] = $len * 2.5 + 5;
}

// Generate PDF
$pdf = new TCPDF('L', PDF_UNIT, 'A3', true, 'UTF-8', false);
$pdf->SetCreator('Luzira COU Primary School');
$pdf->SetAuthor('Luzira COU Primary School');
$pdf->SetTitle('Results for Class ' . $class);
$pdf->SetMargins(5, 25, 5);
$pdf->SetAutoPageBreak(TRUE, 10);
$pdf->SetFont('helvetica', '', 11);
$pdf->AddPage();

// Add Logo
$logoPath = 'logo.png'; // Use local file for guaranteed display
if (file_exists($logoPath)) {
    $pdf->Image($logoPath, 7, 2, 20);
}
$pdf->SetY(10);
$pdf->SetFont('helvetica', 'B', 14);
$pdf->Cell(0, 10, "Luzira COU Primary School", 0, 1, 'C');
$pdf->SetFont('helvetica', '', 11);
$pdf->Cell(0, 10, "Class: $class Results", 0, 1, 'C');
$pdf->Ln(2);

// Headers
$pdf->SetFont('helvetica', 'B', 9);
foreach ($headers as $header) {
    $pdf->Cell($colWidths[$header], 7, str_replace('_', ' ', $header), 1, 0, 'C');
}
$pdf->Ln();

// Data
$pdf->SetFont('helvetica', 'B', 9);
foreach ($results as $row) {
    foreach ($headers as $header) {
        $align = ($header == 'STUDENT_NAME') ? 'L' : 'C';
        $pdf->Cell($colWidths[$header], 7, $row[$header], 1, 0, $align);
    }
    $pdf->Ln();
}

// Output to browser
$pdf->Output("Class_{$class}_Results.pdf", 'I');
exit;
?>
