<?php
require_once __DIR__ . '/../../config/secure_bootstrap.php';
require_once __DIR__ . '/../../vendor/autoload.php';
use Dompdf\Dompdf;

$stmt = $pdo->query("SELECT a.*, u.full_name AS creator FROM accreditation a LEFT JOIN users u ON a.created_by = u.id ORDER BY a.created_at DESC");
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

$html = '<h3 style="text-align:center;">LAPORAN DATA AKREDITASI UNIVERSITAS & PROGRAM STUDI</h3>';
$html .= '<p style="text-align:center;font-size:12px;">Tanggal Cetak: '.date('d F Y, H:i').'</p>';
$html .= '<table border="1" cellspacing="0" cellpadding="5" width="100%">
<thead style="background-color:#d9ead3;text-align:center;font-weight:bold;">
<tr><td>No</td><td>Jenis</td><td>Nama Institusi/Prodi</td><td>Lembaga</td><td>Level</td><td>Nilai</td><td>Status</td><td>Nomor SK</td><td>Masa Berlaku</td><td>Pembuat</td></tr>
</thead><tbody>';

foreach($rows as $i=>$r){
  $html.="<tr>
    <td align='center'>".($i+1)."</td>
    <td>".ucfirst($r['type'])."</td>
    <td>".htmlspecialchars($r['type']=='universitas'?$r['institution_name']:$r['program_studi'])."</td>
    <td>".htmlspecialchars($r['accreditation_body'])."</td>
    <td>".htmlspecialchars($r['level'])."</td>
    <td align='center'>".htmlspecialchars($r['score'])."</td>
    <td>".htmlspecialchars($r['status'])."</td>
    <td>".htmlspecialchars($r['decision_number'])."</td>
    <td>".htmlspecialchars($r['valid_from'].' s.d '.$r['valid_until'])."</td>
    <td>".htmlspecialchars($r['creator'])."</td>
  </tr>";
}

$html .= '</tbody></table>';

$dompdf = new Dompdf();
$dompdf->loadHtml($html);
$dompdf->setPaper('A4','landscape');
$dompdf->render();
$dompdf->stream('Laporan_Akreditasi_'.date('Ymd_His').'.pdf',['Attachment'=>true]);
exit;
