<?php

declare(strict_types=1);

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

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

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

$user = auth_user();
$title = 'Staff Dashboard';

$tasks = [];
$monthParam = trim((string)($_GET['month'] ?? date('Y-m')));
$monthStart = null;
$monthEnd = null;
$monthTitle = '';
$tasksByDay = [];
$error = '';

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

    if (!preg_match('/^\d{4}-\d{2}$/', $monthParam)) {
        $monthParam = date('Y-m');
    }

    $monthStart = new DateTimeImmutable($monthParam . '-01 00:00:00');
    $monthEnd = $monthStart->modify('last day of this month');
    $monthTitle = $monthStart->format('F Y');

    $from = $monthStart->format('Y-m-d');
    $to = $monthEnd->format('Y-m-d');

    $stmt = $pdo->prepare(
        "SELECT
            t.task_id,
            t.scheduled_date,
            t.scheduled_time,
            t.status,
            s.service_name,
            u.full_name AS customer_name
         FROM tasks t
         JOIN service_requests sr ON t.request_id = sr.request_id
         JOIN services s ON sr.service_id = s.service_id
         JOIN users u ON sr.customer_id = u.user_id
         WHERE t.assigned_staff_id = :staff_id
           AND t.scheduled_date BETWEEN :from AND :to
         ORDER BY t.scheduled_date ASC, t.scheduled_time ASC, t.task_id ASC"
    );
    $stmt->execute([
        'staff_id' => (int)($user['user_id'] ?? 0),
        'from' => $from,
        'to' => $to,
    ]);
    $tasks = $stmt->fetchAll();

    foreach ($tasks as $t) {
        $d = (string)($t['scheduled_date'] ?? '');
        if ($d === '') {
            continue;
        }
        if (!isset($tasksByDay[$d])) {
            $tasksByDay[$d] = [];
        }
        $tasksByDay[$d][] = $t;
    }
} catch (Throwable $e) {
    $error = $e->getMessage();
}

$nav = [
    ['label' => 'Overview', 'href' => '/pest/public/staff/overview.php', 'active' => false],
    ['label' => 'My Tasks', 'href' => '/pest/public/staff/index.php', 'active' => true],
    ['label' => 'Upload Images', 'href' => '/pest/public/staff/upload_images.php', 'active' => false],
    ['label' => 'Location Tracker', 'href' => '/pest/public/staff/location.php', 'active' => false],
    ['label' => 'Task History', 'href' => '/pest/public/staff/history.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">
    <?php
        $monthStart = $monthStart instanceof DateTimeImmutable ? $monthStart : new DateTimeImmutable(date('Y-m-01'));
        $monthEnd = $monthEnd instanceof DateTimeImmutable ? $monthEnd : $monthStart->modify('last day of this month');
        $monthTitle = $monthTitle !== '' ? $monthTitle : $monthStart->format('F Y');

        $prevMonth = $monthStart->modify('-1 month')->format('Y-m');
        $nextMonth = $monthStart->modify('+1 month')->format('Y-m');
        $firstDow = (int)$monthStart->format('N');
        $daysInMonth = (int)$monthEnd->format('j');
        $startOffset = $firstDow - 1;
        $totalCells = $startOffset + $daysInMonth;
        $weeks = (int)ceil($totalCells / 7);
        $weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
    ?>

    <div class="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
            <h1 class="text-xl font-semibold">My Tasks Calendar</h1>
            <p class="mt-1 text-sm text-slate-600">Viewing tasks scheduled in <span class="font-medium"><?= e($monthTitle) ?></span>.</p>
        </div>
        <div class="flex flex-wrap gap-2">
            <a class="rounded-lg border px-4 py-2 text-sm hover:bg-slate-50" href="/pest/public/staff/index.php?month=<?= e($prevMonth) ?>">Prev</a>
            <a class="rounded-lg border px-4 py-2 text-sm hover:bg-slate-50" href="/pest/public/staff/index.php?month=<?= e(date('Y-m')) ?>">This Month</a>
            <a class="rounded-lg border px-4 py-2 text-sm hover:bg-slate-50" href="/pest/public/staff/index.php?month=<?= e($nextMonth) ?>">Next</a>
        </div>
    </div>

    <div class="mt-5 overflow-x-auto">
        <div class="min-w-[900px]">
            <div class="grid grid-cols-7 gap-2">
                <?php foreach ($weekdays as $wd): ?>
                    <div class="text-xs font-semibold text-slate-600 px-2 py-1"><?= e($wd) ?></div>
                <?php endforeach; ?>
            </div>

            <div class="mt-2 grid grid-cols-7 gap-2">
                <?php
                    $cell = 0;
                    for ($w = 0; $w < $weeks; $w++):
                        for ($d = 0; $d < 7; $d++):
                            $dayNum = $cell - $startOffset + 1;
                            $inMonth = ($dayNum >= 1 && $dayNum <= $daysInMonth);
                            $dateKey = $inMonth ? $monthStart->format('Y-m-') . str_pad((string)$dayNum, 2, '0', STR_PAD_LEFT) : '';
                            $items = ($inMonth && isset($tasksByDay[$dateKey])) ? $tasksByDay[$dateKey] : [];
                            $isToday = $inMonth && ($dateKey === date('Y-m-d'));
                ?>
                    <div class="rounded-xl border bg-white p-2 min-h-[120px] <?= $isToday ? 'ring-2 ring-slate-900' : '' ?>">
                        <div class="flex items-center justify-between">
                            <div class="text-xs font-semibold text-slate-700"><?= $inMonth ? e((string)$dayNum) : '' ?></div>
                            <?php if ($inMonth && $items): ?>
                                <div class="text-[11px] text-slate-500"><?= e((string)count($items)) ?></div>
                            <?php endif; ?>
                        </div>

                        <div class="mt-2 space-y-2">
                            <?php if ($inMonth && $items): ?>
                                <?php foreach ($items as $t): ?>
                                    <?php
                                        $status = (string)($t['status'] ?? '');
                                        $badge = 'bg-slate-50 text-slate-700 border-slate-200';
                                        if ($status === 'completed') {
                                            $badge = 'bg-green-50 text-green-700 border-green-200';
                                        } elseif (in_array($status, ['assigned','accepted','started','rescheduled'], true)) {
                                            $badge = 'bg-indigo-50 text-indigo-700 border-indigo-200';
                                        }
                                    ?>
                                    <a class="block rounded-lg border px-2 py-1.5 hover:bg-slate-50" href="/pest/public/staff/task_details.php?id=<?= e((string)$t['task_id']) ?>">
                                        <div class="flex items-center justify-between gap-2">
                                            <div class="text-[11px] font-medium text-slate-900 truncate"><?= e((string)$t['service_name']) ?></div>
                                            <span class="inline-flex items-center rounded-full border px-2 py-0.5 text-[10px] font-medium <?= e($badge) ?>"><?= e($status) ?></span>
                                        </div>
                                        <div class="mt-1 text-[11px] text-slate-600">
                                            #<?= e((string)$t['task_id']) ?>
                                            <?php if (!empty($t['scheduled_time'])): ?>
                                                · <?= e((string)$t['scheduled_time']) ?>
                                            <?php endif; ?>
                                        </div>
                                        <?php if (!empty($t['customer_name'])): ?>
                                            <div class="mt-1 text-[11px] text-slate-500 truncate"><?= e((string)$t['customer_name']) ?></div>
                                        <?php endif; ?>
                                    </a>
                                <?php endforeach; ?>
                            <?php elseif ($inMonth): ?>
                                <div class="text-[11px] text-slate-400">No tasks</div>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php
                            $cell++;
                        endfor;
                    endfor;
                ?>
            </div>
        </div>
    </div>
</div>
<?php
$content = ob_get_clean();

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