<?php
/**
 * Progress Analytics — PDF export (admin app).
 *
 * Streams a printable PDF of the current scope via Dompdf (the same engine the
 * terminal reports use). Same auth, module gate and role scoping as the data
 * endpoint — the scope is rebuilt through the access context, so a tutor can
 * only ever export their own classes.
 *
 * Optional ?include_ai=1 appends the premium AI summary (when licensed).
 */
declare(strict_types=1);

require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/lib/progress_query.php';
require_once __DIR__ . '/lib/progress_access.php';
require_once __DIR__ . '/lib/progress_export.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Auth first (this is a page, not JSON — fail with a plain message).
if (empty($_SESSION['user_id'])) {
    http_response_code(401);
    exit('Please sign in.');
}
requireModule('progress_analytics'); // redirects on role/license failure

$conn = getDBConnection();
if (!$conn instanceof mysqli) {
    http_response_code(500);
    exit('Database unavailable.');
}

$context = progressAccessContext();
$scope   = progressBuildScope($_GET, $context);

// Optional AI narrative.
$narrative = null;
if (!empty($_GET['include_ai'])) {
    require_once __DIR__ . '/lib/progress_insight.php';
    if (progressInsightAvailable()) {
        $ins = progressInsightGenerate($conn, $scope);
        if ($ins['success']) { $narrative = $ins['narrative']; }
    }
}

$school = function_exists('getSettingValue') ? (string) (getSettingValue('school_name') ?: 'EduTrack School') : 'EduTrack School';

$html = progressExportHtml($conn, $scope, [
    'school'       => $school,
    'narrative'    => $narrative,
    'generated_by' => (string) ($_SESSION['full_name'] ?? ''),
]);

// ── Render via Dompdf ───────────────────────────────────────────────────────
if (!class_exists('Dompdf\\Dompdf')) {
    $autoload = dirname(__DIR__) . '/vendor/autoload.php';
    if (is_file($autoload)) { require_once $autoload; }
}
if (!class_exists('Dompdf\\Dompdf')) {
    http_response_code(500);
    exit('PDF engine is not installed.');
}

$options = new \Dompdf\Options();
// Legacy parser, deliberately: this report's HTML is simple and valid, and the
// HTML5 parser (masterminds/html5) is ~4× slower here (≈15s vs ≈4s) for
// byte-identical output. isRemoteEnabled off — everything is inlined.
$options->set('isHtml5ParserEnabled', false);
$options->set('isRemoteEnabled', false);

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

$slug = preg_replace('/[^A-Za-z0-9]+/', '-', trim(
    $scope['level'] . ' ' . implode('-', $scope['classes']) . ' ' . $scope['term']
));
$slug = trim((string) $slug, '-') ?: 'report';
$filename = 'progress-' . $slug . '.pdf';

// Stream inline so the browser opens it; Content-Disposition names the download.
$dompdf->stream($filename, ['Attachment' => false]);
exit;
