<?php
require __DIR__ . '/../src/auth.php';
require_login();
require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/../src/db.php';

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

$reportId = (int)($_GET['id'] ?? 0);
if (!$reportId) { header('Location: dashboard.php'); exit; }

$stmt = $pdo->prepare('SELECT * FROM pms_backlog WHERE report_id = ? ORDER BY count_value DESC');
$stmt->execute([$reportId]);
$rows = $stmt->fetchAll();

$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'Property ID');
$sheet->setCellValue('B1', 'Property Name');
$sheet->setCellValue('C1', 'Count');

$r = 2;
foreach ($rows as $row) {
    $sheet->setCellValue("A$r", $row['property_id']);
    $sheet->setCellValue("B$r", $row['prop_name']);
    $sheet->setCellValue("C$r", $row['count_value']);
    $r++;
}

$writer = new Xlsx($spreadsheet);
$filename = "pms_report_{$reportId}.xlsx";

header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="'. $filename .'"');
header('Cache-Control: max-age=0');
$writer->save('php://output');
exit;
