<?php

declare(strict_types=1);

require_once __DIR__ . '/../../includes/bootstrap.php';

$config = require __DIR__ . '/../../config/config.php';

auth_start_session();
auth_require_role(['customer']);

$user = auth_user();
$title = 'Gap Analysis Report';

$customerId = (int)($user['user_id'] ?? 0);

$error = '';
$rows = [];

try {
    $pdo = Database::pdo();
    $rows = CustomerReportsService::listReports($pdo, $customerId, CustomerReportsService::TYPE_GAP_ANALYSIS);
} catch (Throwable $e) {
    $error = $e->getMessage();
}

$current = $rows[0] ?? null;
$previous = $rows ? array_slice($rows, 1) : [];

$nav = [
    ['label' => 'Overview', 'href' => '/pest/public/customer/overview.php', 'active' => false],
    ['label' => 'My Requests', 'href' => '/pest/public/customer/index.php', 'active' => false],
    ['label' => 'Request Service', 'href' => '/pest/public/customer/request_service.php', 'active' => false],
    ['label' => 'My Services', 'href' => '/pest/public/customer/my_services.php', 'active' => false],
    ['label' => 'Service Reports', 'href' => '/pest/public/customer/reports.php', 'active' => false],
    ['label' => 'IPM Map', 'href' => '/pest/public/customer/ipm_map.php', 'active' => false],
    ['label' => 'Gap Analysis Report', 'href' => '/pest/public/customer/gap_analysis_report.php', 'active' => true],
    ['label' => 'Trend Analysis Report', 'href' => '/pest/public/customer/trend_analysis_report.php', 'active' => false],
    ['label' => 'Complaints', 'href' => '/pest/public/customer/complaints.php', 'active' => false],
    ['label' => 'Payments', 'href' => '/pest/public/customer/payments.php', 'active' => false],
];

ob_start();
?>
<?php if ($error !== ''): ?>
    <div class="rounded-xl border border-red-200 bg-red-50 p-4 text-sm text-red-700">
        <?= e($error) ?>
    </div>
<?php endif; ?>

<div class="rounded-xl border bg-white p-6">
    <div>
        <h1 class="text-xl font-semibold">Gap Analysis Report</h1>
        <p class="mt-1 text-sm text-slate-600">Latest monthly report is shown below. Previous months appear underneath.</p>
    </div>

    <?php if (!$current): ?>
        <div class="mt-6 text-sm text-slate-500">No Gap Analysis Report uploaded yet.</div>
    <?php else: ?>
        <?php
            $p = CustomerReportsService::publicUrl((string)$current['file_path']);
            $mime = (string)($current['mime_type'] ?? '');
            $isPdf = (stripos($mime, 'pdf') !== false) || (strtolower(pathinfo($p, PATHINFO_EXTENSION)) === 'pdf');
            $monthLabel = '';
            if (!empty($current['report_month'])) {
                $monthLabel = date('Y-m', strtotime((string)$current['report_month']));
            }
        ?>

        <div class="mt-6 rounded-xl border bg-white overflow-hidden">
            <div class="flex items-center justify-between border-b px-4 py-3">
                <div class="text-sm font-semibold">Current <?= $monthLabel ? '(' . e($monthLabel) . ')' : '' ?></div>
                <a class="text-sm text-blue-700 hover:underline" href="<?= e($p) ?>" target="_blank" rel="noopener">Open</a>
            </div>
            <div class="p-4">
                <?php if ($isPdf): ?>
                    <iframe class="w-full" style="height: 70vh" src="<?= e($p) ?>"></iframe>
                <?php else: ?>
                    <img class="w-full max-h-[70vh] object-contain" src="<?= e($p) ?>" alt="Gap Analysis Report">
                <?php endif; ?>
            </div>
        </div>

        <div class="mt-8">
            <div class="text-sm font-semibold">Previous</div>
            <div class="mt-3 grid grid-cols-2 gap-3 md:grid-cols-4">
                <?php if (!$previous): ?>
                    <div class="col-span-full text-sm text-slate-500">No previous uploads.</div>
                <?php else: ?>
                    <?php foreach ($previous as $r): ?>
                        <?php
                            $pp = CustomerReportsService::publicUrl((string)$r['file_path']);
                            $mm = (string)($r['mime_type'] ?? '');
                            $pdf = (stripos($mm, 'pdf') !== false) || (strtolower(pathinfo($pp, PATHINFO_EXTENSION)) === 'pdf');
                            $label = '';
                            if (!empty($r['report_month'])) {
                                $label = date('Y-m', strtotime((string)$r['report_month']));
                            } else {
                                $label = date('Y-m-d', strtotime((string)$r['uploaded_at']));
                            }
                        ?>
                        <a class="block overflow-hidden rounded-lg border bg-white" href="<?= e($pp) ?>" target="_blank" rel="noopener">
                            <?php if ($pdf): ?>
                                <div class="h-28 w-full bg-slate-50 flex items-center justify-center text-slate-600 text-xs font-medium">PDF</div>
                            <?php else: ?>
                                <img class="h-28 w-full object-cover" src="<?= e($pp) ?>" alt="Gap Analysis Report">
                            <?php endif; ?>
                            <div class="border-t px-2 py-1 text-[11px] text-slate-600"><?= e($label) ?></div>
                        </a>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
    <?php endif; ?>
</div>
<?php
$content = ob_get_clean();

require __DIR__ . '/../../includes/dashboard_layout.php';
