<?php
session_start();
ob_start();
chdir('../');

require_once('assets/vendor/tcpdf/tcpdf.php');
require_once('public/connection.php');

if (!isset($_SESSION['view_data'])) {
    die("No data provided for printing.");
}

$data = $_SESSION['view_data'];
$class = $data['class'];
$subject = $data['subject'];
$term = $data['term'];
$session = $data['session'];

// Get school info
$school = mysqli_fetch_assoc(mysqli_query($connection, "SELECT * FROM administratives LIMIT 1"));
$short_name = $school['school_short_name'] ?? 'SCHOOL NAME';

$query = "SELECT * FROM results1 WHERE class=? AND subjects=? AND term=? AND session=? ORDER BY reg_number ASC";
$stmt = $connection->prepare($query);
$stmt->bind_param("ssss", $class, $subject, $term, $session);
$stmt->execute();
$result = $stmt->get_result();

// PDF
$pdf = new TCPDF();
$pdf->AddPage();
$pdf->SetFont('Helvetica', '', 10);

$html = "<h3 style='text-align:center;'>{$short_name}</h3>
         <h4 style='text-align:center;'>Exam Score Sheet</h4>
         <p><b>Class:</b> $class &nbsp; <b>Subject:</b> $subject &nbsp; <b>Term:</b> $term &nbsp; <b>Session:</b> $session</p>";

$html .= "<table border='1' cellpadding='4'><thead><tr>
    <th>S/N</th><th>Reg No</th><th>Name</th><th>1ST CA</th><th>2ND CA</th><th>Exam</th><th>Total</th><th>Rank</th>
</tr></thead><tbody>";

$i = 1;
while ($row = $result->fetch_assoc()) {
    $html .= "<tr>
        <td>{$i}</td>
        <td>{$row['reg_number']}</td>
        <td>{$row['name']}</td>
        <td>{$row['ca1']}</td>
        <td>{$row['ca2']}</td>
        <td>{$row['exam']}</td>
        <td>{$row['subject_total']}</td>
        <td>{$row['subject_rank']}</td>
    </tr>";
    $i++;
}
$html .= "</tbody></table>";

$pdf->writeHTML($html, true, false, true, false, '');
$pdf->Output("uploaded_exam_result.pdf", 'I');

