<?php

declare(strict_types=1);

date_default_timezone_set('Asia/Colombo');

require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../includes/role_filter.php';
require_once __DIR__ . '/../includes/report_helper.php';
require_once __DIR__ . '/../vendor/autoload.php';

use Dompdf\Dompdf;
use Dompdf\Options;

if (!isset($_SESSION['role']) || !in_array($_SESSION['role'], ['admin', 'zonal_director'], true)) {
    http_response_code(403);
    exit('Access denied.');
}

$dataset = buildReportDataset($conn, $_GET);
$fields = $dataset['fields'];
$equipment = $dataset['equipment'];
$surveys = $dataset['surveys'];
$equipmentTotals = $dataset['equipment_totals'];

ob_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
@page{size:A3 landscape;margin:8px}
body{font-family:DejaVu Sans,sans-serif;font-size:8px}
h2{text-align:center;margin:0 0 10px}
table{width:100%;border-collapse:collapse;table-layout:fixed}
th,td{padding:3px;border:1px solid #000;font-size:7px;text-align:center;vertical-align:middle;word-break:break-word}
th{background:#eee}
</style>
</head>
<body>
<h2>Sabaragamuwa Province School Computer Hardware Inventory Report</h2>
<table>
<thead><tr>
<?php foreach ($fields as $field): ?>
<th><?= htmlspecialchars(ucwords(str_replace('_', ' ', $field)), ENT_QUOTES, 'UTF-8') ?></th>
<?php endforeach; ?>
<?php foreach ($equipment as $equipmentName): ?>
<th><?= htmlspecialchars($equipmentName, ENT_QUOTES, 'UTF-8') ?> Working</th>
<th><?= htmlspecialchars($equipmentName, ENT_QUOTES, 'UTF-8') ?> Not Working</th>
<th><?= htmlspecialchars($equipmentName, ENT_QUOTES, 'UTF-8') ?> Repair</th>
<?php endforeach; ?>
</tr></thead>
<tbody>
<?php if ($surveys === []): ?>
<tr><td colspan="<?= max(1, count($fields) + count($equipment) * 3) ?>">No matching survey records found.</td></tr>
<?php else: ?>
<?php foreach ($surveys as $survey): ?>
<tr>
<?php foreach ($fields as $field): ?>
<td><?= htmlspecialchars((string)($survey[$field] ?? ''), ENT_QUOTES, 'UTF-8') ?></td>
<?php endforeach; ?>
<?php $surveyId = (int)$survey['id']; ?>
<?php foreach ($equipment as $equipmentId => $equipmentName): ?>
<?php $totals = $equipmentTotals[$surveyId][$equipmentId] ?? ['working'=>0,'not_working'=>0,'repair'=>0]; ?>
<td><?= $totals['working'] ?></td>
<td><?= $totals['not_working'] ?></td>
<td><?= $totals['repair'] ?></td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
<?php endif; ?>
</tbody>
</table>
</body>
</html>
<?php
$html = (string)ob_get_clean();

$options = new Options();
$options->set('isRemoteEnabled', false);
$options->set('isHtml5ParserEnabled', true);

$dompdf = new Dompdf($options);
$dompdf->loadHtml($html, 'UTF-8');
$dompdf->setPaper('A3', 'landscape');
$dompdf->render();
$dompdf->stream('survey_report_' . date('Ymd_His') . '.pdf', ['Attachment' => true]);
exit();
