<?php
/**
 * Terminal report PDF renderer.
 *
 * Returns the PDF as a byte string. Deliberately does NOT echo, exit, send
 * headers, or close the connection — so it is safe to call in a loop (batch
 * generation) as well as from a single-download HTTP endpoint.
 *
 * This is the single source of truth for "turn a student into a PDF".
 * report_pdf.php is a thin HTTP wrapper around it.
 */

require_once __DIR__ . '/report_data.php';
require_once __DIR__ . '/../templates/registry.php';

if (!function_exists('renderReportPdfBytes')) {
    /**
     * Render one student's terminal report to PDF bytes.
     *
     * @param mysqli      $conn          Caller owns the connection lifecycle.
     * @param int         $student_id
     * @param string      $term
     * @param string      $academic_year
     * @param string|null $templateKey   Override; null uses the school default.
     *
     * @return string Raw PDF bytes.
     *
     * @throws RuntimeException When the student does not exist, or Dompdf is unavailable.
     */
    function renderReportPdfBytes(
        mysqli  $conn,
        int     $student_id,
        string  $term,
        string  $academic_year,
        ?string $templateKey = null
    ): string {
        if (!class_exists('Dompdf\Dompdf')) {
            // Absolute path — a relative require here resolves against the
            // entry script, which breaks the moment this is called from
            // anywhere other than modules/reports/.
            $autoload = dirname(__DIR__, 3) . '/vendor/autoload.php';
            if (is_file($autoload)) {
                require_once $autoload;
            }
        }
        if (!class_exists('Dompdf\Dompdf')) {
            throw new RuntimeException('Dompdf is not installed (vendor/autoload.php missing).');
        }

        $data = getReportData($conn, $student_id, $term, $academic_year);
        if (empty($data['student'])) {
            throw new RuntimeException("Student {$student_id} not found.");
        }

        $key    = $templateKey ?? ($data['settings']['report_template'] ?? 'ges_standard');
        $render = resolveReportRenderer($key);
        $html   = $render($data, 'pdf');

        $options = new \Dompdf\Options();
        $options->set('isHtml5ParserEnabled', true);
        // Images are base64-embedded by the template; no remote fetches.
        $options->set('isRemoteEnabled', false);

        $dompdf = new \Dompdf\Dompdf($options);
        $dompdf->loadHtml($html);
        $dompdf->setPaper('A4', 'portrait');
        $dompdf->render();

        return (string) $dompdf->output();
    }
}

if (!function_exists('reportPdfFilename')) {
    /**
     * Filesystem-safe filename for a student's report PDF.
     */
    function reportPdfFilename(array $student, string $term = ''): string
    {
        $name = trim(($student['first_name'] ?? '') . '_' . ($student['last_name'] ?? ''));
        $name = preg_replace('/[^A-Za-z0-9_\-]/', '_', str_replace(' ', '_', $name));
        $name = trim((string) $name, '_') ?: ('student_' . (int) ($student['id'] ?? 0));

        $suffix = $term !== ''
            ? '_' . trim((string) preg_replace('/[^A-Za-z0-9_\-]/', '_', $term), '_')
            : '';

        return $name . $suffix . '_Report.pdf';
    }
}
