<?php
/**
 * Single-student terminal report PDF download.
 *
 * Thin HTTP wrapper around renderReportPdfBytes(). All rendering logic lives in
 * lib/report_pdf_render.php so batch generation can reuse it without going
 * through HTTP.
 *
 * Requires are absolute: the previous relative paths resolved against the entry
 * script rather than this file, so any caller outside this directory failed
 * with "Failed to open stream: ../../vendor/autoload.php".
 */

require_once dirname(__DIR__, 2) . '/config.php';
require_once __DIR__ . '/lib/report_pdf_render.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
if (!isset($_SESSION['user_id'])) {
    http_response_code(403);
    exit('Access denied.');
}

$conn = getDBConnection();

$student_id    = (int) ($_GET['student_id'] ?? 0);
$term          = (string) ($_GET['term']          ?? getCurrentTerm());
$academic_year = (string) ($_GET['academic_year'] ?? getAcademicYear());
$template      = isset($_GET['template']) ? (string) $_GET['template'] : null;

try {
    $pdf = renderReportPdfBytes($conn, $student_id, $term, $academic_year, $template);
} catch (Throwable $e) {
    error_log('report_pdf.php: ' . $e->getMessage());
    http_response_code(404);
    exit('Report could not be generated.');
}

// Re-read the student purely for the filename. Cheap, and keeps the renderer
// free of presentation concerns.
$stmt = $conn->prepare("SELECT id, first_name, last_name FROM students WHERE id = ?");
$stmt->bind_param('i', $student_id);
$stmt->execute();
$student = $stmt->get_result()->fetch_assoc() ?: [];
$stmt->close();

$filename = reportPdfFilename($student, '');

header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Content-Length: ' . strlen($pdf));
header('Cache-Control: no-cache, must-revalidate');
echo $pdf;
exit;
