<?php

declare(strict_types=1);

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

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

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

$user = auth_user();
$title = 'Customer Reports';

$customerId = (int)($_GET['customer_id'] ?? 0);
$type = (string)($_GET['type'] ?? CustomerReportsService::TYPE_IPM_MAP);

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

$types = [
    CustomerReportsService::TYPE_IPM_MAP,
    CustomerReportsService::TYPE_GAP_ANALYSIS,
    CustomerReportsService::TYPE_TREND_ANALYSIS,
];

if (!in_array($type, $types, true)) {
    $type = CustomerReportsService::TYPE_IPM_MAP;
}

try {
    $pdo = Database::pdo();
    CustomerReportsService::ensureTable($pdo);

    if ($customerId > 0) {
        $stmt = $pdo->prepare("SELECT user_id, full_name, email FROM users WHERE user_id = :id AND user_type = 'customer' LIMIT 1");
        $stmt->execute(['id' => $customerId]);
        $customer = $stmt->fetch();

        if (!$customer) {
            $error = 'Customer not found.';
        } else {
            $rows = CustomerReportsService::listReports($pdo, $customerId, $type);
        }
    } else {
        $error = 'Missing customer.';
    }
} catch (Throwable $e) {
    $error = $e->getMessage();
}

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

$nav = [
    ['label' => 'Overview', 'href' => '/pest/public/admin/index.php', 'active' => false],
    ['label' => 'Customers', 'href' => '/pest/public/admin/customers.php', 'active' => true],
    ['label' => 'Staff', 'href' => '/pest/public/admin/staff.php', 'active' => false],
    ['label' => 'Staff Locations', 'href' => '/pest/public/admin/staff_locations.php', 'active' => false],
    ['label' => 'Services', 'href' => '/pest/public/admin/services.php', 'active' => false],
    ['label' => 'Task Assignment', 'href' => '/pest/public/admin/task_assignment.php', 'active' => false],
    ['label' => 'Payments', 'href' => '/pest/public/admin/payments.php', 'active' => false],
    ['label' => 'Complaints', 'href' => '/pest/public/admin/complaints.php', 'active' => false],
    ['label' => 'Reports', 'href' => '/pest/public/admin/reports.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 class="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
        <div>
            <h1 class="text-xl font-semibold">Customer Reports</h1>
            <?php if ($customer): ?>
                <p class="mt-1 text-sm text-slate-600">
                    <?= e((string)$customer['full_name']) ?> (<?= e((string)$customer['email']) ?>) — Customer #<?= e((string)$customer['user_id']) ?>
                </p>
            <?php endif; ?>
        </div>
        <div class="flex flex-wrap gap-2">
            <?php if ($customerId > 0): ?>
                <a class="rounded-lg border px-4 py-2 text-sm hover:bg-slate-50" href="/pest/public/admin/customer_reports_upload.php?customer_id=<?= e((string)$customerId) ?>">Upload</a>
            <?php endif; ?>
            <a class="rounded-lg border px-4 py-2 text-sm hover:bg-slate-50" href="/pest/public/admin/customers.php">Back</a>
        </div>
    </div>

    <?php if ($customer): ?>
        <div class="mt-6 flex flex-wrap gap-2">
            <?php foreach ($types as $t): ?>
                <?php $isActive = ($t === $type); ?>
                <a class="rounded-lg border px-4 py-2 text-sm <?= $isActive ? 'bg-slate-900 text-white border-slate-900' : 'hover:bg-slate-50' ?>"
                   href="/pest/public/admin/customer_reports_view.php?customer_id=<?= e((string)$customerId) ?>&type=<?= e($t) ?>">
                    <?= e(CustomerReportsService::typeLabel($t)) ?>
                </a>
            <?php endforeach; ?>
        </div>

        <div class="mt-6">
            <?php if (!$current): ?>
                <div class="text-sm text-slate-500">No uploads for <?= e(CustomerReportsService::typeLabel($type)) ?>.</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');
                    $label = !empty($current['report_month'])
                        ? date('Y-m', strtotime((string)$current['report_month']))
                        : date('Y-m-d', strtotime((string)$current['uploaded_at']));
                ?>

                <div class="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 <?= $label ? '(' . e($label) . ')' : '' ?></div>
                        <div class="flex items-center gap-3">
                            <a class="text-sm text-blue-700 hover:underline" href="<?= e($p) ?>" target="_blank" rel="noopener">Open</a>
                            <a class="text-sm hover:underline" href="/pest/public/admin/customer_report_edit.php?customer_id=<?= e((string)$customerId) ?>&type=<?= e((string)$type) ?>&report_id=<?= e((string)$current['report_id']) ?>">Edit</a>
                            <form method="post" action="/pest/public/admin/customer_report_delete.php" onsubmit="return confirm('Delete this report?');">
                                <input type="hidden" name="report_id" value="<?= e((string)$current['report_id']) ?>">
                                <input type="hidden" name="customer_id" value="<?= e((string)$customerId) ?>">
                                <input type="hidden" name="type" value="<?= e((string)$type) ?>">
                                <button class="text-sm text-red-700 hover:underline" type="submit">Delete</button>
                            </form>
                        </div>
                    </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="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');
                                    $lb = !empty($r['report_month'])
                                        ? date('Y-m', strtotime((string)$r['report_month']))
                                        : date('Y-m-d', strtotime((string)$r['uploaded_at']));
                                ?>
                                <div class="overflow-hidden rounded-lg border bg-white">
                                    <a class="block" 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="Report">
                                        <?php endif; ?>
                                    </a>
                                    <div class="border-t px-2 py-1 text-[11px] text-slate-600 flex items-center justify-between gap-2">
                                        <span><?= e($lb) ?></span>
                                        <span class="flex items-center gap-2">
                                            <a class="text-[11px] hover:underline" href="/pest/public/admin/customer_report_edit.php?customer_id=<?= e((string)$customerId) ?>&type=<?= e((string)$type) ?>&report_id=<?= e((string)$r['report_id']) ?>">Edit</a>
                                            <form method="post" action="/pest/public/admin/customer_report_delete.php" onsubmit="return confirm('Delete this report?');">
                                                <input type="hidden" name="report_id" value="<?= e((string)$r['report_id']) ?>">
                                                <input type="hidden" name="customer_id" value="<?= e((string)$customerId) ?>">
                                                <input type="hidden" name="type" value="<?= e((string)$type) ?>">
                                                <button class="text-[11px] text-red-700 hover:underline" type="submit">Delete</button>
                                            </form>
                                        </span>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endif; ?>
        </div>
    <?php endif; ?>
</div>
<?php
$content = ob_get_clean();

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