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

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

$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);

// ==== Buat Spreadsheet ====
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();

// Judul laporan
$sheet->setCellValue('A1', 'LAPORAN DOKUMEN MUTU');
$sheet->mergeCells('A1:H1');
$sheet->getStyle('A1')->getFont()->setBold(true)->setSize(16);
$sheet->getStyle('A1')->getAlignment()->setHorizontal('center');

$sheet->setCellValue('A2', 'Universitas Riyadlul Ulum');
$sheet->mergeCells('A2:H2');
$sheet->getStyle('A2')->getAlignment()->setHorizontal('center');

$sheet->setCellValue('A3', 'Tanggal Cetak: ' . date('d M Y H:i'));
$sheet->mergeCells('A3:H3');
$sheet->getStyle('A3')->getAlignment()->setHorizontal('center');

// Header kolom
$header = ['No', 'Judul', 'Kategori', 'Unit', 'Status', 'Visibilitas', 'Pembuat', 'Tanggal'];
$sheet->fromArray($header, NULL, 'A5');
$sheet->getStyle('A5:H5')->getFont()->setBold(true);
$sheet->getStyle('A5:H5')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
      ->getStartColor()->setARGB('FFDDDDDD');

// Isi data
$rowNum = 6;
$no = 1;
foreach ($rows as $r) {
    $sheet->fromArray([
        $no++,
        $r['title'],
        $r['category'],
        $r['unit_owner'],
        $r['status'],
        $r['visibility'],
        $r['author'],
        date('d M Y', strtotime($r['created_at']))
    ], NULL, "A{$rowNum}");
    $rowNum++;
}

// Total data
$sheet->setCellValue("A{$rowNum}", 'Total Dokumen: ' . count($rows));
$sheet->mergeCells("A{$rowNum}:H{$rowNum}");
$sheet->getStyle("A{$rowNum}")->getFont()->setBold(true);

// Atur lebar kolom otomatis
foreach (range('A', 'H') as $col) {
    $sheet->getColumnDimension($col)->setAutoSize(true);
}

// ==== Output ke browser ====
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename="dokumen_mutu_' . date('Ymd_His') . '.xlsx"');

$writer = new Xlsx($spreadsheet);
$writer->save('php://output');
exit;
