<?php
require __DIR__ . '/../vendor/autoload.php';  // PhpSpreadsheet autoload

require_once __DIR__ . '/../src/config.php';
require_once __DIR__ . '/../src/db.php';      // MUST load DB class

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

$db = new DB();          // ← This must exist in /src/db.php
$pdo = $db->connect();

$report_id = $_GET["report_id"] ?? null;

if (!$report_id) {
    die("Report ID missing.");
}

// Fetch grouped RT offline data
$stmt = $pdo->prepare("
    SELECT service_provider, property_id, prop_name, rt_name
    FROM offline_rt1000
    WHERE report_id = ?
    ORDER BY service_provider, property_id
");

$stmt->execute([$report_id]);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

// Header row
$sheet->setCellValue("A1", "Service Provider");
$sheet->setCellValue("B1", "Property ID");
$sheet->setCellValue("C1", "Property Name");
$sheet->setCellValue("D1", "RT Number");

$sheet->getStyle("A1:D1")->getFont()->setBold(true);

$rowNum = 2;
$currentProvider = null;

foreach ($rows as $row) {

    if ($row['service_provider'] !== $currentProvider) {
        $currentProvider = $row['service_provider'];

        $sheet->setCellValue("A$rowNum", $currentProvider);
        $sheet->getStyle("A$rowNum")->getFont()->setBold(true);
        $rowNum++;
    }

    $sheet->setCellValue("B$rowNum", $row['property_id']);
    $sheet->setCellValue("C$rowNum", $row['prop_name']);
    $sheet->setCellValue("D$rowNum", $row['rt_name']);

    $rowNum++;
}

$writer = new Xlsx($spreadsheet);

header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
header("Content-Disposition: attachment; filename=\"offline_rt_export.xlsx\"");

$writer->save("php://output");
exit;
?>
