<?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 = 'Customer Dashboard';

$requests = [];
$monthParam = trim((string)($_GET['month'] ?? date('Y-m')));
$monthDate = DateTimeImmutable::createFromFormat('Y-m', $monthParam) ?: new DateTimeImmutable('first day of this month');
$monthStart = $monthDate->modify('first day of this month');
$monthEnd = $monthDate->modify('last day of this month');
$filteredRequests = [];
$requestsByDate = [];
$error = '';

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

    $stmt = $pdo->prepare('CALL GetCustomerRequests(:customer_id)');
    $stmt->execute(['customer_id' => (int)$user['user_id']]);
    $requests = $stmt->fetchAll();
    $stmt->closeCursor();

    foreach ($requests as $r) {
        $dRaw = trim((string)($r['preferred_date'] ?? ''));
        if ($dRaw === '') {
            continue;
        }
        $d = DateTimeImmutable::createFromFormat('Y-m-d', $dRaw);
        if (!$d) {
            continue;
        }
        if ($d < $monthStart || $d > $monthEnd) {
            continue;
        }
        $filteredRequests[] = $r;
    }

    usort($filteredRequests, static function (array $a, array $b): int {
        $ad = (string)($a['preferred_date'] ?? '');
        $bd = (string)($b['preferred_date'] ?? '');
        if ($ad !== $bd) {
            return strcmp($bd, $ad);
        }
        return ((int)($b['request_id'] ?? 0)) <=> ((int)($a['request_id'] ?? 0));
    });

    foreach ($filteredRequests as $r) {
        $key = (string)($r['preferred_date'] ?? '');
        if ($key === '') {
            continue;
        }
        if (!isset($requestsByDate[$key])) {
            $requestsByDate[$key] = [];
        }
        $requestsByDate[$key][] = $r;
    }
} catch (Throwable $e) {
    $error = $e->getMessage();
}

$nav = [
    ['label' => 'Overview', 'href' => '/pest/public/customer/overview.php', 'active' => false],
    ['label' => 'My Requests', 'href' => '/pest/public/customer/index.php', 'active' => true],
    ['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' => false],
    ['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 class="flex items-start justify-between gap-4">
        <div>
            <h1 class="text-xl font-semibold">My Service Requests</h1>
            <p class="mt-1 text-sm text-slate-600">Month-wise list (<?= e($monthStart->format('F Y')) ?>).</p>
        </div>
        <div class="text-right">
            <div class="text-xs text-slate-500">Customer ID</div>
            <div class="text-sm font-medium"><?= e((string)$user['user_id']) ?></div>
        </div>
    </div>

    <form class="mt-5 flex flex-col gap-3 sm:flex-row sm:items-end" method="get" action="">
        <div>
            <label class="block text-sm font-medium">Month</label>
            <input class="mt-1 rounded-lg border px-3 py-2 text-sm" type="month" name="month" value="<?= e($monthStart->format('Y-m')) ?>">
        </div>
        <div class="flex gap-2">
            <button class="rounded-lg border px-4 py-2 text-sm hover:bg-slate-50" type="submit">Apply</button>
            <a class="rounded-lg border px-4 py-2 text-sm hover:bg-slate-50" href="<?= e(Constants::APP_ROOT) ?>/customer/index.php">Reset</a>
        </div>
    </form>

    <div class="mt-5 overflow-x-auto">
        <table class="min-w-full text-sm">
            <thead class="text-left text-slate-600">
                <tr class="border-b">
                    <th class="py-2 pr-4">Request ID</th>
                    <th class="py-2 pr-4">Service</th>
                    <th class="py-2 pr-4">Preferred Time</th>
                    <th class="py-2 pr-4">Status</th>
                    <th class="py-2">Action</th>
                </tr>
            </thead>
            <tbody>
                <?php if (!$filteredRequests): ?>
                    <tr class="border-b"><td class="py-3 text-slate-500" colspan="5">No requests found for this month.</td></tr>
                <?php else: ?>
                    <?php foreach ($requestsByDate as $dateKey => $dateRows): ?>
                        <tr class="border-b bg-slate-50">
                            <td class="py-3 pr-4 font-semibold text-slate-900" colspan="5"><?= e((string)$dateKey) ?></td>
                        </tr>
                        <?php foreach ($dateRows as $r): ?>
                            <tr class="border-b last:border-0">
                                <td class="py-3 pr-4 font-medium"><?= e((string)$r['request_id']) ?></td>
                                <td class="py-3 pr-4"><?= e((string)$r['service_name']) ?></td>
                                <td class="py-3 pr-4"><?= e((string)($r['preferred_time'] ?? '')) ?></td>
                                <td class="py-3 pr-4"><?= e((string)$r['request_status']) ?></td>
                                <td class="py-3">
                                    <a class="rounded-lg border px-3 py-1.5 text-xs hover:bg-slate-50" href="<?= e(Constants::APP_ROOT) ?>/customer/request_service.php">View</a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>
<?php
$content = ob_get_clean();

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