<?php
ob_start();
chdir('../');
session_start();
require_once('public/connection.php');
require_once('tcpdf/tcpdf.php'); 

if (!isset($_SESSION['staff_id'])) {
    header("Location: ../index.php");
    exit;
}

// Filters
$filter_class   = $_GET['class'] ?? '';
$filter_term    = $_GET['term'] ?? '';
$filter_session = $_GET['session'] ?? '';
$filter_subject = $_GET['subject_id'] ?? '';
$filter_exam_type = $_GET['exam_type'] ?? '';

$where = [];
if ($filter_class) $where[] = "r.class = '" . $conn->real_escape_string($filter_class) . "'";
if ($filter_term) $where[] = "r.term = '" . $conn->real_escape_string($filter_term) . "'";
if ($filter_session) $where[] = "r.session = '" . $conn->real_escape_string($filter_session) . "'";
if ($filter_subject) $where[] = "r.subject = (SELECT subjects FROM school_subjects WHERE id = '" . $conn->real_escape_string($filter_subject) . "')";
if ($filter_exam_type) $where[] = "r.exam_type = '" . $conn->real_escape_string($filter_exam_type) . "'";
$where_sql = $where ? 'WHERE ' . implode(' AND ', $where) : '';

$sql = "
    SELECT 
        r.*, s.firstname, s.lastname, s.othername, s.reg_number, s.class AS student_class
    FROM exam_group_results r
    JOIN students s ON r.student_id = s.id
    $where_sql
    ORDER BY r.student_id DESC
";
$results = $conn->query($sql);

// ✅ Init PDF in Landscape mode
$pdf = new TCPDF('L', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

$pdf->AddPage();
$pdf->SetFont('helvetica','',10);

// Title
$pdf->Cell(0, 10, 'Student Exam Results', 0, 1, 'C');

// Table
$html = '<table border="1" cellspacing="0" cellpadding="4">
<tr style="background-color:#f2f2f2; font-weight:bold;">
  <th>Student</th><th>Reg. Number</th><th>Class</th><th>Subject</th>
  <th>Term</th><th>Session</th><th>OBJ</th><th>Theory</th><th>Total</th>
</tr>';

while ($row = $results->fetch_assoc()) {
    $name = $row['lastname'].' '.$row['firstname'].' '.$row['othername'];
    $html .= '<tr>
        <td>'.htmlspecialchars($name).'</td>
        <td>'.htmlspecialchars($row['reg_number']).'</td>
        <td>'.htmlspecialchars($row['student_class']).'</td>
        <td>'.htmlspecialchars($row['subject']).'</td>
        <td>'.htmlspecialchars($row['term']).'</td>
        <td>'.htmlspecialchars($row['session']).'</td>
        <td>'.htmlspecialchars($row['mcq_score']).'</td>
        <td>'.htmlspecialchars($row['theory_score']).'</td>
        <td>'.htmlspecialchars($row['total']).'</td>
    </tr>';
}
$html .= '</table>';

$pdf->writeHTML($html, true, false, true, false, '');

// Clean buffer before sending
ob_end_clean();
$pdf->Output('exam_results.pdf','I');
exit;
