<?php
// /elms/lecturer/assessments/report.pdf.php
// Generates a PDF using Dompdf if available; else falls back to prompting the user to use Print-to-PDF.
declare(strict_types=1);
if (session_status()===PHP_SESSION_NONE) session_start();
date_default_timezone_set('Asia/Colombo');

$id = (int)($_GET['id'] ?? 0);
if ($id<=0){ http_response_code(400); echo "Missing id"; exit; }

$ROOT = rtrim($_SERVER['DOCUMENT_ROOT'] ?? dirname(__DIR__,2), '/');

// Get the HTML from report.php (server-side)
$scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS']!=='off') ? 'https' : 'http';
$base   = $scheme.'://'.$_SERVER['HTTP_HOST'];
$reportUrl = $base.dirname($_SERVER['REQUEST_URI']).'/report.php?id='.$id;

// If Dompdf available, render PDF
$autoload = $ROOT.'/vendor/autoload.php';
if (is_file($autoload)) {
  require_once $autoload;
  if (class_exists('Dompdf\Dompdf')) {
    $html = @file_get_contents($reportUrl);
    if(!$html){ $html='<h3>Report</h3><p>Please open the HTML report and print as PDF.</p>'; }
    $dompdf = new Dompdf\Dompdf(['isRemoteEnabled'=>true]);
    $dompdf->loadHtml($html, 'UTF-8');
    $dompdf->setPaper('A4', 'portrait');
    $dompdf->render();
    $fname='Assessment-Report-'.$id.'.pdf';
    header('Content-Type: application/pdf');
    header('Content-Disposition: inline; filename="'.$fname.'"');
    echo $dompdf->output();
    exit;
  }
}

// Fallback when Dompdf not installed
header('Content-Type: text/html; charset=utf-8');
?>
<!doctype html><meta charset="utf-8"><title>Download PDF</title>
<style>body{font:14px system-ui,Arial;margin:20px}</style>
<h3>PDF generator not installed</h3>
<p>Please open the <a href="<?= htmlspecialchars($reportUrl) ?>">HTML report</a> and use <b>Print → Save as PDF</b>.</p>
