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

ob_clean();

$q = trim($_GET['q'] ?? '');
$category = $_GET['category'] ?? '';
$status = $_GET['status'] ?? '';

$where = [];
$params = [];

if ($q !== '') {
  $where[] = "(d.title LIKE :q OR d.unit_owner LIKE :q)";
  $params[':q'] = "%$q%";
}
if ($category !== '') {
  $where[] = "d.category = :category";
  $params[':category'] = $category;
}
if ($status !== '') {
  $where[] = "d.status = :status";
  $params[':status'] = $status;
}
$whereSql = $where ? "WHERE " . implode(" AND ", $where) : "";

$stmt = $pdo->prepare("SELECT d.*, u.full_name AS author 
                       FROM documents d 
                       LEFT JOIN users u ON d.created_by = u.id 
                       $whereSql ORDER BY d.created_at DESC");
$stmt->execute($params);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

// generate HTML
ob_start();
?>
<style>
  body { font-family: DejaVu Sans, sans-serif; font-size: 12px; }
  h3, h4 { text-align: center; margin: 0; }
  table { border-collapse: collapse; width: 100%; margin-top: 15px; }
  th, td { border: 1px solid #000; padding: 6px; text-align: left; }
  th { background-color: #ddd; }
</style>

<h3>LAPORAN DOKUMEN MUTU</h3>
<h4>Universitas Riyadlul Ulum</h4>
<p style="text-align:center; font-size:11px;">
Dicetak pada: <?= date('d M Y H:i') ?>
</p>

<table>
  <thead>
    <tr>
      <th>No</th><th>Judul</th><th>Kategori</th><th>Unit</th>
      <th>Status</th><th>Visibilitas</th><th>Pembuat</th><th>Tanggal</th>
    </tr>
  </thead>
  <tbody>
    <?php $no=1; foreach($rows as $r): ?>
    <tr>
      <td><?= $no++ ?></td>
      <td><?= htmlspecialchars($r['title']) ?></td>
      <td><?= $r['category'] ?></td>
      <td><?= $r['unit_owner'] ?></td>
      <td><?= $r['status'] ?></td>
      <td><?= $r['visibility'] ?></td>
      <td><?= $r['author'] ?></td>
      <td><?= date('d M Y', strtotime($r['created_at'])) ?></td>
    </tr>
    <?php endforeach; ?>
  </tbody>
</table>

<p style="margin-top:10px;"><b>Total Dokumen:</b> <?= count($rows) ?></p>
<?php
$html = ob_get_clean();

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