<?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 = 'Task Assignment';

$rows = [];
$error = '';
$q = trim((string)($_GET['q'] ?? ''));
$view = trim((string)($_GET['view'] ?? 'calendar'));
$monthParam = trim((string)($_GET['month'] ?? date('Y-m')));
$detailStaff = trim((string)($_GET['detail_staff'] ?? ''));
$detailCustomer = trim((string)($_GET['detail_customer'] ?? ''));
$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');
$calendarRows = [];
$calendarMap = [];
$completedRows = [];
$completedSummaryRows = [];
$summaryRows = [];
$detailRows = [];
$notice = '';

$toPublic = function (string $p): string {
    $p = trim($p);
    if ($p === '') {
        return '';
    }
    if (preg_match('~^https?://~i', $p)) {
        return $p;
    }
    if (str_starts_with($p, Constants::APP_ROOT . '/')) {
        return $p;
    }
    if (str_starts_with($p, '/uploads/')) {
        return Constants::APP_ROOT . $p;
    }
    if (str_starts_with($p, 'uploads/')) {
        return Constants::APP_ROOT . '/' . $p;
    }
    return $p;
};

function checklist_label_from_image_path(string $path): string
{
    $p = str_replace('\\', '/', trim($path));
    if ($p === '') {
        return '';
    }
    if (preg_match('~/check_([^/]+)/~', $p, $m)) {
        $raw = (string)($m[1] ?? '');
        $raw = str_replace('_', ' ', $raw);
        $raw = preg_replace('/\s+/', ' ', $raw);
        return trim($raw);
    }
    return '';
}

function task_status_badge_class(string $status): string
{
    switch ($status) {
        case 'completed':
            return 'bg-green-50 text-green-700 border-green-200';
        case 'accepted':
        case 'started':
            return 'bg-blue-50 text-blue-700 border-blue-200';
        case 'cancelled':
            return 'bg-red-50 text-red-700 border-red-200';
        case 'rescheduled':
            return 'bg-amber-50 text-amber-700 border-amber-200';
        default:
            return 'bg-slate-50 text-slate-700 border-slate-200';
    }
}

function table_exists(PDO $pdo, string $table): bool
{
    $stmt = $pdo->prepare(
        'SELECT COUNT(*)
         FROM information_schema.tables
         WHERE table_schema = DATABASE() AND table_name = :t'
    );
    $stmt->execute(['t' => $table]);
    return (int)$stmt->fetchColumn() > 0;
}

function load_task_images_from_dir(int $taskId): array
{
    $uploadsRoot = realpath(__DIR__ . '/../') ?: (__DIR__ . '/../');
    $relDir = 'uploads/tasks/' . $taskId;
    $absDir = $uploadsRoot . '/' . $relDir;
    $out = [];
    if (is_dir($absDir)) {
        $allowedExt = ['jpg', 'jpeg', 'png', 'webp', 'gif'];
        $stack = [[$absDir, '/' . $relDir]];

        while ($stack) {
            [$curAbs, $curRel] = array_pop($stack);
            $list = scandir($curAbs);
            if (!is_array($list)) {
                continue;
            }
            foreach ($list as $f) {
                if ($f === '.' || $f === '..') {
                    continue;
                }
                $pAbs = $curAbs . '/' . $f;
                $pRel = $curRel . '/' . $f;
                if (is_dir($pAbs)) {
                    $stack[] = [$pAbs, $pRel];
                    continue;
                }
                if (!is_file($pAbs)) {
                    continue;
                }
                $ext = strtolower(pathinfo($f, PATHINFO_EXTENSION));
                if ($ext !== '' && in_array($ext, $allowedExt, true)) {
                    $out[] = $pRel;
                }
            }
        }
    }
    rsort($out);
    return $out;
}

function summarize_task_groups(array $rows): array
{
    $groups = [];
    foreach ($rows as $row) {
        $staffName = trim((string)($row['staff_name'] ?? 'Unassigned'));
        $customerName = trim((string)($row['customer_name'] ?? 'Unknown Customer'));
        $key = mb_strtolower($staffName . '|' . $customerName);

        if (!isset($groups[$key])) {
            $groups[$key] = [
                'staff_name' => $staffName,
                'customer_name' => $customerName,
                'task_count' => 0,
                'pending_count' => 0,
                'completed_count' => 0,
                'in_progress_count' => 0,
                'latest_schedule' => '',
                'services' => [],
            ];
        }

        $status = strtolower(trim((string)($row['task_status'] ?? '')));
        $schedule = trim((string)($row['scheduled_date'] ?? '') . ' ' . (string)($row['scheduled_time'] ?? ''));
        $serviceName = trim((string)($row['service_name'] ?? ''));

        $groups[$key]['task_count']++;
        if (in_array($status, ['pending', 'assigned'], true)) {
            $groups[$key]['pending_count']++;
        }
        if (in_array($status, ['accepted', 'started'], true)) {
            $groups[$key]['in_progress_count']++;
        }
        if ($status === 'completed') {
            $groups[$key]['completed_count']++;
        }
        if ($schedule !== '' && ($groups[$key]['latest_schedule'] === '' || strcmp($schedule, $groups[$key]['latest_schedule']) > 0)) {
            $groups[$key]['latest_schedule'] = $schedule;
        }
        if ($serviceName !== '') {
            $groups[$key]['services'][$serviceName] = true;
        }
    }

    foreach ($groups as &$group) {
        $group['service_summary'] = implode(', ', array_keys($group['services']));
        unset($group['services']);
    }
    unset($group);

    usort($groups, static function (array $a, array $b): int {
        if ($a['pending_count'] !== $b['pending_count']) {
            return $b['pending_count'] <=> $a['pending_count'];
        }
        if ($a['task_count'] !== $b['task_count']) {
            return $b['task_count'] <=> $a['task_count'];
        }
        return strcmp($a['customer_name'], $b['customer_name']);
    });

    return $groups;
}

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

    if ($q !== '') {
        try {
            $qLike = '%' . $q . '%';
            $qId = ctype_digit($q) ? (int)$q : 0;

            if ($qId > 0) {
                $stmt = $pdo->prepare(
                    "SELECT task_id, custom_task_id, scheduled_date, scheduled_time, task_status, staff_name, customer_name, service_name, property_address, pest_type, severity_level, payment_status
                     FROM admin_all_tasks
                     WHERE task_status <> 'deleted'
                       AND task_id = :task_id
                     ORDER BY scheduled_date DESC, scheduled_time DESC"
                );
                $stmt->execute([
                    'task_id' => $qId,
                ]);
            } else {
                $stmt = $pdo->prepare(
                    "SELECT task_id, custom_task_id, scheduled_date, scheduled_time, task_status, staff_name, customer_name, service_name, property_address, pest_type, severity_level, payment_status
                     FROM admin_all_tasks
                     WHERE task_status <> 'deleted'
                       AND (staff_name LIKE :staff_like OR customer_name LIKE :customer_like OR service_name LIKE :service_like)
                     ORDER BY scheduled_date DESC, scheduled_time DESC"
                );
                $stmt->execute([
                    'staff_like' => $qLike,
                    'customer_like' => $qLike,
                    'service_like' => $qLike,
                ]);
            }

            $rows = $stmt->fetchAll();
        } catch (Throwable $e) {
            throw $e;
        }
    } else {
        $rows = $pdo->query(
            "SELECT task_id, custom_task_id, scheduled_date, scheduled_time, task_status, staff_name, customer_name, service_name, property_address, pest_type, severity_level, payment_status
             FROM admin_all_tasks
             WHERE task_status <> 'deleted'
             ORDER BY scheduled_date DESC, scheduled_time DESC"
        )->fetchAll();
    }

    $summaryRows = summarize_task_groups($rows);
    if ($detailStaff !== '' && $detailCustomer !== '') {
        foreach ($rows as $row) {
            $staffName = trim((string)($row['staff_name'] ?? ''));
            $customerName = trim((string)($row['customer_name'] ?? ''));
            if ($staffName === $detailStaff && $customerName === $detailCustomer) {
                $detailRows[] = $row;
            }
        }
    }

    if ($q !== '' && ctype_digit($q) && (int)$q > 0) {
        $stmtCalendar = $pdo->prepare(
            "SELECT task_id, custom_task_id, scheduled_date, scheduled_time, task_status, staff_name, customer_name, service_name
             FROM admin_all_tasks
             WHERE scheduled_date BETWEEN :from AND :to
               AND task_status <> 'deleted'
               AND task_id = :task_id
             ORDER BY scheduled_date ASC, scheduled_time ASC, task_id ASC"
        );
        $stmtCalendar->execute([
            'from' => $monthStart->format('Y-m-d'),
            'to' => $monthEnd->format('Y-m-d'),
            'task_id' => (int)$q,
        ]);
    } elseif ($q !== '') {
        $stmtCalendar = $pdo->prepare(
            "SELECT task_id, custom_task_id, scheduled_date, scheduled_time, task_status, staff_name, customer_name, service_name
             FROM admin_all_tasks
             WHERE scheduled_date BETWEEN :from AND :to
               AND task_status <> 'deleted'
               AND (staff_name LIKE :staff_like OR customer_name LIKE :customer_like OR service_name LIKE :service_like)
             ORDER BY scheduled_date ASC, scheduled_time ASC, task_id ASC"
        );
        $stmtCalendar->execute([
            'from' => $monthStart->format('Y-m-d'),
            'to' => $monthEnd->format('Y-m-d'),
            'staff_like' => '%' . $q . '%',
            'customer_like' => '%' . $q . '%',
            'service_like' => '%' . $q . '%',
        ]);
    } else {
        $stmtCalendar = $pdo->prepare(
            "SELECT task_id, custom_task_id, scheduled_date, scheduled_time, task_status, staff_name, customer_name, service_name
             FROM admin_all_tasks
             WHERE scheduled_date BETWEEN :from AND :to
               AND task_status <> 'deleted'
             ORDER BY scheduled_date ASC, scheduled_time ASC, task_id ASC"
        );
        $stmtCalendar->execute([
            'from' => $monthStart->format('Y-m-d'),
            'to' => $monthEnd->format('Y-m-d'),
        ]);
    }
    $calendarRows = $stmtCalendar->fetchAll();

    if ($detailStaff !== '' && $detailCustomer !== '' && $view === 'calendar') {
        $calendarRows = array_values(array_filter($calendarRows, static function (array $row) use ($detailStaff, $detailCustomer): bool {
            $staffName = trim((string)($row['staff_name'] ?? ''));
            $customerName = trim((string)($row['customer_name'] ?? ''));
            return $staffName === $detailStaff && $customerName === $detailCustomer;
        }));
    }

    foreach ($calendarRows as $row) {
        $key = (string)($row['scheduled_date'] ?? '');
        if ($key === '') {
            continue;
        }
        if (!isset($calendarMap[$key])) {
            $calendarMap[$key] = [];
        }
        $calendarMap[$key][] = $row;
    }

    try {
        if ($q === '') {
            $stmtCompleted = $pdo->prepare(
                "SELECT custom_task_id, task_id, scheduled_date, scheduled_time, task_status, staff_name, customer_name, service_name, property_address
                 FROM admin_all_tasks
                 WHERE task_status = 'completed'
                   AND scheduled_date BETWEEN :from AND :to
                 ORDER BY scheduled_date DESC, scheduled_time DESC, task_id DESC"
            );
            $stmtCompleted->execute([
                'from' => $monthStart->format('Y-m-d'),
                'to' => $monthEnd->format('Y-m-d'),
            ]);
        } else {
            $qLikeCompleted = '%' . $q . '%';
            $qIdCompleted = ctype_digit($q) ? (int)$q : 0;

            if ($qIdCompleted > 0) {
                $stmtCompleted = $pdo->prepare(
                    "SELECT task_id, custom_task_id, scheduled_date, scheduled_time, task_status, staff_name, customer_name, service_name, property_address
                     FROM admin_all_tasks
                     WHERE task_status = 'completed'
                       AND scheduled_date BETWEEN :from AND :to
                       AND task_id = :task_id
                     ORDER BY scheduled_date DESC, scheduled_time DESC, task_id DESC"
                );
                $stmtCompleted->execute([
                    'from' => $monthStart->format('Y-m-d'),
                    'to' => $monthEnd->format('Y-m-d'),
                    'task_id' => $qIdCompleted,
                ]);
            } else {
                $stmtCompleted = $pdo->prepare(
                    "SELECT task_id, custom_task_id, scheduled_date, scheduled_time, task_status, staff_name, customer_name, service_name, property_address
                     FROM admin_all_tasks
                     WHERE task_status = 'completed'
                       AND scheduled_date BETWEEN :from AND :to
                       AND (staff_name LIKE :staff_like OR customer_name LIKE :customer_like OR service_name LIKE :service_like)
                     ORDER BY scheduled_date DESC, scheduled_time DESC, task_id DESC"
                );
                $stmtCompleted->execute([
                    'from' => $monthStart->format('Y-m-d'),
                    'to' => $monthEnd->format('Y-m-d'),
                    'staff_like' => $qLikeCompleted,
                    'customer_like' => $qLikeCompleted,
                    'service_like' => $qLikeCompleted,
                ]);
            }
        }
        $completedRows = $stmtCompleted->fetchAll();
    } catch (Throwable $e) {
        throw $e;
    }

    if ($completedRows) {
        $hasTaskImagesTable = table_exists($pdo, 'task_images');
        foreach ($completedRows as &$completedRow) {
            $taskId = (int)($completedRow['task_id'] ?? 0);
            $images = $taskId > 0 ? load_task_images_from_dir($taskId) : [];

            if (!$images && $taskId > 0 && $hasTaskImagesTable) {
                try {
                    $stmtImgs = $pdo->prepare(
                        "SELECT COALESCE(image_path, file_path, path) AS p
                         FROM task_images
                         WHERE task_id = :task_id
                         ORDER BY 1 DESC"
                    );
                    $stmtImgs->execute(['task_id' => $taskId]);
                    $dbImages = $stmtImgs->fetchAll(PDO::FETCH_COLUMN);
                    foreach ($dbImages as $img) {
                        if ($img) {
                            $images[] = (string)$img;
                        }
                    }
                } catch (Throwable $e) {
                }
            }

            $completedRow['images'] = $images;

            $checkGroups = [];
            foreach ($images as $imgPath) {
                $lbl = checklist_label_from_image_path((string)$imgPath);
                if ($lbl === '') {
                    continue;
                }
                if (!isset($checkGroups[$lbl])) {
                    $checkGroups[$lbl] = [];
                }
                $checkGroups[$lbl][] = (string)$imgPath;
            }
            $completedRow['check_images'] = $checkGroups;
        }
        unset($completedRow);
    }

    $completedSummaryRows = summarize_task_groups($completedRows);

    if ($view === 'completed' && $detailStaff !== '' && $detailCustomer !== '') {
        $completedRows = array_values(array_filter($completedRows, static function (array $row) use ($detailStaff, $detailCustomer): bool {
            $staffName = trim((string)($row['staff_name'] ?? ''));
            $customerName = trim((string)($row['customer_name'] ?? ''));
            return $staffName === $detailStaff && $customerName === $detailCustomer;
        }));
    }

    if ($q !== '' && ctype_digit($q) && (int)$q > 0 && !$rows && !$calendarRows && !$completedRows) {
        $notice = 'Task Id not Found';
    }
} catch (Throwable $e) {
    $error = $e->getMessage();
}

$nav = [
    ['label' => 'Overview', 'href' => Constants::APP_ROOT . '/admin/index.php', 'active' => false],
    ['label' => 'Customers', 'href' => Constants::APP_ROOT . '/admin/customers.php', 'active' => false],
    ['label' => 'Staff', 'href' => Constants::APP_ROOT . '/admin/staff.php', 'active' => false],
    ['label' => 'Staff Locations', 'href' => Constants::APP_ROOT . '/admin/staff_locations.php', 'active' => false],
    ['label' => 'Services', 'href' => Constants::APP_ROOT . '/admin/services.php', 'active' => false],
    ['label' => 'Task Assignment', 'href' => Constants::APP_ROOT . '/admin/task_assignment.php', 'active' => true],
    ['label' => 'Payments', 'href' => Constants::APP_ROOT . '/admin/payments.php', 'active' => false],
    ['label' => 'Complaints', 'href' => Constants::APP_ROOT . '/admin/complaints.php', 'active' => false],
    ['label' => 'Reports', 'href' => Constants::APP_ROOT . '/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; ?>

<?php if ($notice !== ''): ?>
    <div class="mt-4 rounded-xl border border-amber-200 bg-amber-50 p-4 text-sm text-amber-800">
        <?= e($notice) ?>
    </div>
<?php endif; ?>

<div class="rounded-xl border bg-white p-6">
    <div class="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
            <h1 class="text-xl font-semibold">Task Assignment</h1>
            <p class="mt-1 text-sm text-slate-600">Assign customer requests to staff, update schedules, and manage the monthly archive professionally.</p>
        </div>
        <div class="flex flex-wrap gap-2">
            <a class="inline-flex items-center justify-center rounded-lg border px-4 py-2 text-sm hover:bg-slate-50" href="<?= e(Constants::APP_ROOT) ?>/admin/task_assignment.php?view=list&month=<?= e($monthStart->format('Y-m')) ?>">List View</a>
            <a class="inline-flex items-center justify-center rounded-lg border px-4 py-2 text-sm hover:bg-slate-50" href="<?= e(Constants::APP_ROOT) ?>/admin/task_assignment.php?view=calendar&month=<?= e($monthStart->format('Y-m')) ?>">Calendar View</a>
            <a class="inline-flex items-center justify-center rounded-lg border px-4 py-2 text-sm hover:bg-slate-50" href="<?= e(Constants::APP_ROOT) ?>/admin/task_assignment.php?view=completed&month=<?= e($monthStart->format('Y-m')) ?>">Completed Tasks</a>
            <a class="inline-flex items-center justify-center rounded-lg bg-slate-900 px-4 py-2 text-sm font-medium text-white hover:bg-slate-800" href="<?= e(Constants::APP_ROOT) ?>/admin/task_add.php">Assign Task</a>
        </div>
    </div>

    <form class="mt-5 flex flex-col gap-3 lg:flex-row" method="get" action="">
        <input type="hidden" name="view" value="<?= e($view) ?>">
        <input class="w-full rounded-lg border px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-slate-900" type="text" name="q" value="<?= e($q) ?>" placeholder="Search by staff, customer, service">
        <input class="rounded-lg border px-3 py-2 text-sm" type="month" name="month" value="<?= e($monthStart->format('Y-m')) ?>">
        <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) ?>/admin/task_assignment.php">Reset</a>
    </form>

    <?php if ($view === 'list'): ?>
        <?php
            $prevMonth = $monthStart->modify('-1 month')->format('Y-m');
            $nextMonth = $monthStart->modify('+1 month')->format('Y-m');

            $tasksByCustomer = [];
            foreach ($calendarRows as $r) {
                $cust = trim((string)($r['customer_name'] ?? ''));
                if ($cust === '') {
                    $cust = 'Unknown Customer';
                }
                if (!isset($tasksByCustomer[$cust])) {
                    $tasksByCustomer[$cust] = [];
                }
                $tasksByCustomer[$cust][] = $r;
            }
            ksort($tasksByCustomer, SORT_NATURAL | SORT_FLAG_CASE);

            $customerSummaries = [];
            foreach ($tasksByCustomer as $custName => $custTasks) {
                $pending = 0;
                $inProgress = 0;
                $completed = 0;
                $latestSchedule = '';
                $services = [];
                $staff = [];

                foreach ($custTasks as $t) {
                    $status = strtolower(trim((string)($t['task_status'] ?? '')));
                    if (in_array($status, ['pending', 'assigned'], true)) {
                        $pending++;
                    } elseif (in_array($status, ['accepted', 'started'], true)) {
                        $inProgress++;
                    } elseif ($status === 'completed') {
                        $completed++;
                    }

                    $schedule = trim((string)($t['scheduled_date'] ?? '') . ' ' . (string)($t['scheduled_time'] ?? ''));
                    if ($schedule !== '' && ($latestSchedule === '' || strcmp($schedule, $latestSchedule) > 0)) {
                        $latestSchedule = $schedule;
                    }

                    $svc = trim((string)($t['service_name'] ?? ''));
                    if ($svc !== '') {
                        $services[$svc] = true;
                    }

                    $st = trim((string)($t['staff_name'] ?? ''));
                    if ($st !== '') {
                        $staff[$st] = true;
                    }
                }

                $customerSummaries[] = [
                    'customer_name' => $custName,
                    'task_count' => count($custTasks),
                    'pending_count' => $pending,
                    'in_progress_count' => $inProgress,
                    'completed_count' => $completed,
                    'latest_schedule' => $latestSchedule,
                    'service_summary' => implode(', ', array_keys($services)),
                    'staff_summary' => implode(', ', array_keys($staff)),
                ];
            }

            usort($customerSummaries, static function (array $a, array $b): int {
                if (($a['task_count'] ?? 0) !== ($b['task_count'] ?? 0)) {
                    return ($b['task_count'] ?? 0) <=> ($a['task_count'] ?? 0);
                }
                return strcmp((string)($a['customer_name'] ?? ''), (string)($b['customer_name'] ?? ''));
            });

            $detailCustomerMonthRows = [];
            if ($detailCustomer !== '' && isset($tasksByCustomer[$detailCustomer])) {
                $detailCustomerMonthRows = $tasksByCustomer[$detailCustomer];
            }
        ?>
        <div class="mt-6 rounded-2xl border border-slate-200 bg-slate-50 p-4">
            <div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                <div>
                    <div class="text-sm font-semibold text-slate-900">Month List View</div>
                    <div class="text-xs text-slate-500">Showing tasks scheduled in <?= e($monthStart->format('F Y')) ?>.</div>
                </div>
                <div class="flex gap-2">
                    <a class="rounded-lg border bg-white px-4 py-2 text-sm hover:bg-slate-50" href="<?= e(Constants::APP_ROOT) ?>/admin/task_assignment.php?view=list&month=<?= e($prevMonth) ?>&q=<?= urlencode($q) ?>&detail_staff=<?= urlencode($detailStaff) ?>&detail_customer=<?= urlencode($detailCustomer) ?>">Previous</a>
                    <a class="rounded-lg border bg-white px-4 py-2 text-sm hover:bg-slate-50" href="<?= e(Constants::APP_ROOT) ?>/admin/task_assignment.php?view=list&month=<?= e($nextMonth) ?>&q=<?= urlencode($q) ?>&detail_staff=<?= urlencode($detailStaff) ?>&detail_customer=<?= urlencode($detailCustomer) ?>">Next</a>
                </div>
            </div>

            <div class="mt-4 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">Customer</th>
                            <th class="py-2 pr-4">Staff</th>
                            <th class="py-2 pr-4">Services</th>
                            <th class="py-2 pr-4">Pending</th>
                            <th class="py-2 pr-4">In Progress</th>
                            <th class="py-2 pr-4">Completed</th>
                            <th class="py-2 pr-4">Total</th>
                            <th class="py-2 pr-4">Latest Schedule</th>
                            <th class="py-2">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!$calendarRows): ?>
                            <tr class="border-b"><td class="py-3 text-slate-500" colspan="9">No scheduled tasks for this month.</td></tr>
                        <?php else: ?>
                            <?php foreach ($customerSummaries as $s): ?>
                                <tr class="border-b last:border-0">
                                    <td class="py-3 pr-4 font-semibold text-slate-900"><?= e((string)($s['customer_name'] ?? '')) ?></td>
                                    <td class="py-3 pr-4 text-slate-600"><?= e((string)($s['staff_summary'] ?? '')) ?></td>
                                    <td class="py-3 pr-4 text-slate-600"><?= e((string)(($s['service_summary'] ?? '') !== '' ? $s['service_summary'] : '-')) ?></td>
                                    <td class="py-3 pr-4"><span class="inline-flex min-w-[2rem] items-center justify-center rounded-full bg-amber-50 px-2 py-1 text-xs font-semibold text-amber-700"><?= e((string)($s['pending_count'] ?? 0)) ?></span></td>
                                    <td class="py-3 pr-4"><span class="inline-flex min-w-[2rem] items-center justify-center rounded-full bg-blue-50 px-2 py-1 text-xs font-semibold text-blue-700"><?= e((string)($s['in_progress_count'] ?? 0)) ?></span></td>
                                    <td class="py-3 pr-4"><span class="inline-flex min-w-[2rem] items-center justify-center rounded-full bg-green-50 px-2 py-1 text-xs font-semibold text-green-700"><?= e((string)($s['completed_count'] ?? 0)) ?></span></td>
                                    <td class="py-3 pr-4 font-medium text-slate-900"><?= e((string)($s['task_count'] ?? 0)) ?></td>
                                    <td class="py-3 pr-4 text-slate-600"><?= e((string)(($s['latest_schedule'] ?? '') !== '' ? $s['latest_schedule'] : '-')) ?></td>
                                    <td class="py-3">
                                        <a class="inline-flex items-center justify-center rounded-lg bg-slate-900 px-3 py-1.5 text-xs font-medium text-white hover:bg-slate-800" href="<?= e(Constants::APP_ROOT) ?>/admin/task_assignment.php?view=list&month=<?= e($monthStart->format('Y-m')) ?>&q=<?= urlencode($q) ?>&detail_customer=<?= urlencode((string)($s['customer_name'] ?? '')) ?>#customer-details">Details</a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <?php if ($detailCustomer !== ''): ?>
            <div id="customer-details" class="mt-6 rounded-2xl border border-slate-200 bg-white p-5">
                <div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                    <div>
                        <div class="text-sm font-semibold text-slate-900">Customer Task Details</div>
                        <div class="text-xs text-slate-500">Showing tasks for <?= e($detailCustomer) ?> in <?= e($monthStart->format('F Y')) ?>.</div>
                    </div>
                    <div class="flex gap-2">
                        <a class="rounded-lg border px-4 py-2 text-sm hover:bg-slate-50" href="<?= e(Constants::APP_ROOT) ?>/admin/task_assignment.php?view=list&month=<?= e($monthStart->format('Y-m')) ?>&q=<?= urlencode($q) ?>">Close</a>
                    </div>
                </div>

                <div class="mt-4 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">Task</th>
                                <th class="py-2 pr-4">Schedule</th>
                                <th class="py-2 pr-4">Staff</th>
                                <th class="py-2 pr-4">Service</th>
                                <th class="py-2 pr-4">Status</th>
                                <th class="py-2">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!$detailCustomerMonthRows): ?>
                                <tr class="border-b"><td class="py-3 text-slate-500" colspan="6">No tasks found for this customer in this month.</td></tr>
                            <?php else: ?>
                                <?php foreach ($detailCustomerMonthRows as $r): ?>
                                    <?php $badge = task_status_badge_class((string)($r['task_status'] ?? '')); ?>
                                    <tr class="border-b last:border-0">
                                        <td class="py-3 pr-4 font-medium">#<?= e((string)($r['custom_task_id'] ?? $r['task_id'])) ?></td>
                                        <td class="py-3 pr-4"><?= e((string)$r['scheduled_date']) ?> <?= e((string)$r['scheduled_time']) ?></td>
                                        <td class="py-3 pr-4"><?= e((string)($r['staff_name'] ?? '')) ?></td>
                                        <td class="py-3 pr-4"><?= e((string)($r['service_name'] ?? '')) ?></td>
                                        <td class="py-3 pr-4"><span class="inline-flex items-center rounded-full border px-2.5 py-1 text-xs font-medium <?= e($badge) ?>"><?= e((string)($r['task_status'] ?? '')) ?></span></td>
                                        <td class="py-3">
                                            <div class="flex flex-nowrap gap-2">
                                                <a class="inline-flex items-center justify-center rounded-lg bg-blue-600 px-3 py-1.5 text-xs font-medium text-white hover:bg-blue-700" href="<?= e(Constants::APP_ROOT) ?>/admin/task_details.php?id=<?= e((string)$r['task_id']) ?>">View</a>
                                                <a class="inline-flex items-center justify-center rounded-lg bg-amber-500 px-3 py-1.5 text-xs font-medium text-white hover:bg-amber-600" href="<?= e(Constants::APP_ROOT) ?>/admin/task_edit.php?id=<?= e((string)$r['task_id']) ?>">Edit</a>
                                                <form method="post" action="<?= e(Constants::APP_ROOT) ?>/admin/task_delete.php" onsubmit="return confirm('Delete this task?');">
                                                    <input type="hidden" name="id" value="<?= e((string)$r['task_id']) ?>">
                                                    <input type="hidden" name="return_view" value="list">
                                                    <input type="hidden" name="return_month" value="<?= e($monthStart->format('Y-m')) ?>">
                                                    <input type="hidden" name="return_detail_staff" value="">
                                                    <input type="hidden" name="return_detail_customer" value="<?= e($detailCustomer) ?>">
                                                    <button class="inline-flex items-center justify-center rounded-lg bg-red-600 px-3 py-1.5 text-xs font-medium text-white hover:bg-red-700" type="submit">Delete</button>
                                                </form>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        <?php endif; ?>

    <?php elseif ($view === 'calendar'): ?>
        <?php
            $gridStart = $monthStart->modify('-' . ((int)$monthStart->format('N') - 1) . ' days');
            $gridEnd = $monthEnd->modify('+' . (7 - (int)$monthEnd->format('N')) . ' days');
            $prevMonth = $monthStart->modify('-1 month')->format('Y-m');
            $nextMonth = $monthStart->modify('+1 month')->format('Y-m');
        ?>
        <div class="mt-6 rounded-2xl border border-slate-200 bg-slate-50 p-4">
            <div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                <div>
                    <div class="text-sm font-semibold text-slate-900">Monthly Schedule Archive</div>
                    <div class="text-xs text-slate-500">
                        Browse assigned work for <?= e($monthStart->format('F Y')) ?>
                        <?php if ($detailStaff !== '' && $detailCustomer !== ''): ?>
                            for <?= e($detailStaff) ?> and <?= e($detailCustomer) ?>
                        <?php endif; ?>.
                    </div>
                </div>
                <div class="flex gap-2">
                    <a class="rounded-lg border bg-white px-4 py-2 text-sm hover:bg-slate-50" href="/pest/public/admin/task_assignment.php?view=calendar&month=<?= e($prevMonth) ?>&detail_staff=<?= urlencode($detailStaff) ?>&detail_customer=<?= urlencode($detailCustomer) ?>">Previous</a>
                    <a class="rounded-lg border bg-white px-4 py-2 text-sm hover:bg-slate-50" href="/pest/public/admin/task_assignment.php?view=calendar&month=<?= e($nextMonth) ?>&detail_staff=<?= urlencode($detailStaff) ?>&detail_customer=<?= urlencode($detailCustomer) ?>">Next</a>
                </div>
            </div>

            <div class="mt-4 grid grid-cols-7 gap-2 text-center text-xs font-semibold uppercase tracking-wide text-slate-500">
                <div>Mon</div>
                <div>Tue</div>
                <div>Wed</div>
                <div>Thu</div>
                <div>Fri</div>
                <div>Sat</div>
                <div>Sun</div>
            </div>

            <div class="mt-2 grid grid-cols-1 gap-3 md:grid-cols-7">
                <?php for ($day = $gridStart; $day <= $gridEnd; $day = $day->modify('+1 day')): ?>
                    <?php
                        $dayKey = $day->format('Y-m-d');
                        $dayTasks = $calendarMap[$dayKey] ?? [];
                        $isCurrentMonth = ($day->format('Y-m') === $monthStart->format('Y-m'));
                    ?>
                    <div class="min-h-[170px] rounded-xl border <?= $isCurrentMonth ? 'border-slate-200 bg-white' : 'border-slate-100 bg-slate-100/70' ?> p-3">
                        <div class="flex items-center justify-between">
                            <div class="text-sm font-semibold <?= $isCurrentMonth ? 'text-slate-900' : 'text-slate-400' ?>"><?= e($day->format('d')) ?></div>
                            <div class="text-[11px] text-slate-400"><?= e($day->format('D')) ?></div>
                        </div>
                        <div class="mt-3 space-y-2">
                            <?php if (!$dayTasks): ?>
                                <div class="rounded-lg border border-dashed border-slate-200 px-2 py-3 text-center text-[11px] text-slate-400">No tasks</div>
                            <?php else: ?>
                                <?php foreach ($dayTasks as $task): ?>
                                    <?php $badge = task_status_badge_class((string)($task['task_status'] ?? '')); ?>
                                    <div class="rounded-lg border border-slate-200 bg-slate-50 p-2">
                                        <div class="flex items-center justify-between gap-2">
                                            <div class="text-xs font-semibold text-slate-900">#<?= e((string)($task['custom_task_id'] ?? $task['task_id'])) ?></div>
                                            <span class="inline-flex items-center rounded-full border px-2 py-0.5 text-[10px] font-medium <?= e($badge) ?>"><?= e((string)$task['task_status']) ?></span>
                                        </div>
                                        <div class="mt-1 text-[11px] text-slate-600"><?= e((string)($task['scheduled_time'] ?? '')) ?> - <?= e((string)($task['service_name'] ?? '')) ?></div>
                                        <div class="mt-1 text-[11px] text-slate-500"><?= e((string)($task['customer_name'] ?? '')) ?></div>
                                        <div class="text-[11px] text-slate-500"><?= e((string)($task['staff_name'] ?? '')) ?></div>
                                        <div class="mt-2">
                                            <a class="flex w-full items-center justify-center rounded-lg border bg-white px-2.5 py-1.5 text-[11px] font-medium hover:bg-slate-50" href="/pest/public/admin/task_details.php?id=<?= e((string)$task['task_id']) ?>">View</a>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endfor; ?>
            </div>
        </div>

        <div class="mt-6 rounded-xl border bg-white p-5">
            <div class="text-sm font-semibold text-slate-900">Month archive list</div>
            <div class="mt-3 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">Task</th>
                            <th class="py-2 pr-4">Schedule</th>
                            <th class="py-2 pr-4">Staff</th>
                            <th class="py-2 pr-4">Customer</th>
                            <th class="py-2 pr-4">Service</th>
                            <th class="py-2 pr-4">Status</th>
                            <th class="py-2">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!$calendarRows): ?>
                            <tr class="border-b"><td class="py-3 text-slate-500" colspan="7">No scheduled tasks for this month.</td></tr>
                        <?php else: ?>
                            <?php foreach ($calendarRows as $r): ?>
                                <tr class="border-b last:border-0">
                                    <td class="py-3 pr-4 font-medium">#<?= e((string)($r['custom_task_id'] ?? $r['task_id'])) ?></td>
                                    <td class="py-3 pr-4"><?= e((string)$r['scheduled_date']) ?> <?= e((string)$r['scheduled_time']) ?></td>
                                    <td class="py-3 pr-4"><?= e((string)($r['staff_name'] ?? '')) ?></td>
                                    <td class="py-3 pr-4"><?= e((string)$r['customer_name']) ?></td>
                                    <td class="py-3 pr-4"><?= e((string)$r['service_name']) ?></td>
                                    <td class="py-3 pr-4"><?= e((string)$r['task_status']) ?></td>
                                    <td class="py-3">
                                        <form method="post" action="/pest/public/admin/task_delete.php" onsubmit="return confirm('Delete this task?');">
                                            <input type="hidden" name="id" value="<?= e((string)$r['task_id']) ?>">
                                            <input type="hidden" name="return_view" value="calendar">
                                            <input type="hidden" name="return_month" value="<?= e($monthStart->format('Y-m')) ?>">
                                            <input type="hidden" name="return_detail_staff" value="<?= e($detailStaff) ?>">
                                            <input type="hidden" name="return_detail_customer" value="<?= e($detailCustomer) ?>">
                                            <button class="rounded-lg border border-red-200 bg-red-50 px-3 py-1.5 text-xs text-red-700 hover:bg-red-100" type="submit">Delete</button>
                                        </form>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    <?php elseif ($view === 'completed'): ?>
        <div class="mt-5 rounded-2xl border border-slate-200 bg-slate-50 p-4">
            <div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                <div>
                    <div class="text-sm font-semibold text-slate-900">Completed Task Summary</div>
                    <div class="text-xs text-slate-500">Grouped by same staff and customer (month filter applied).</div>
                </div>
                <div class="rounded-lg border bg-white px-4 py-2 text-sm font-medium text-slate-700">
                    <?= e((string)count($completedSummaryRows)) ?> group(s)
                </div>
            </div>
        </div>

        <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">Staff</th>
                        <th class="py-2 pr-4">Customer</th>
                        <th class="py-2 pr-4">Services</th>
                        <th class="py-2 pr-4">Completed</th>
                        <th class="py-2 pr-4">Total Tasks</th>
                        <th class="py-2 pr-4">Latest Schedule</th>
                        <th class="py-2">Actions</th>
                    </tr>
                </thead>
                <tbody>
                <?php if (!$completedSummaryRows): ?>
                    <tr class="border-b"><td class="py-3 text-slate-500" colspan="7">No completed tasks found for this month.</td></tr>
                <?php else: ?>
                    <?php foreach ($completedSummaryRows as $r): ?>
                        <tr class="border-b last:border-0">
                            <td class="py-3 pr-4"><?= e((string)($r['staff_name'] ?? '')) ?></td>
                            <td class="py-3 pr-4"><?= e((string)$r['customer_name']) ?></td>
                            <td class="py-3 pr-4 text-slate-600"><?= e((string)($r['service_summary'] ?: '-')) ?></td>
                            <td class="py-3 pr-4"><span class="inline-flex min-w-[2rem] items-center justify-center rounded-full bg-green-50 px-2 py-1 text-xs font-semibold text-green-700"><?= e((string)$r['completed_count']) ?></span></td>
                            <td class="py-3 pr-4 font-medium text-slate-900"><?= e((string)$r['task_count']) ?></td>
                            <td class="py-3 pr-4 text-slate-600"><?= e((string)($r['latest_schedule'] ?: '-')) ?></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) ?>/admin/task_assignment.php?view=completed&month=<?= e($monthStart->format('Y-m')) ?>&q=<?= urlencode($q) ?>&detail_staff=<?= urlencode((string)$r['staff_name']) ?>&detail_customer=<?= urlencode((string)$r['customer_name']) ?>#completed-details">Details</a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
                </tbody>
            </table>
        </div>

        <?php if ($detailStaff !== '' && $detailCustomer !== ''): ?>
            <div id="completed-details" class="mt-6 rounded-2xl border border-slate-200 bg-white p-5">
                <div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                    <div>
                        <div class="text-sm font-semibold text-slate-900">Completed Task Details</div>
                        <div class="text-xs text-slate-500">Showing completed tasks for <?= e($detailStaff) ?> and <?= e($detailCustomer) ?>.</div>
                    </div>
                    <div class="flex gap-2">
                        <a class="rounded-lg border px-4 py-2 text-sm hover:bg-slate-50" href="<?= e(Constants::APP_ROOT) ?>/admin/task_assignment.php?view=completed&month=<?= e($monthStart->format('Y-m')) ?>&q=<?= urlencode($q) ?>">Close</a>
                    </div>
                </div>

                <div class="mt-5 space-y-4">
                    <?php if (!$completedRows): ?>
                        <div class="rounded-xl border bg-white p-5 text-sm text-slate-500">No completed tasks found for this group.</div>
                    <?php else: ?>
                        <?php foreach ($completedRows as $r): ?>
                            <div class="rounded-2xl border bg-white p-5 shadow-sm">
                                <div class="flex flex-col gap-4 xl:flex-row xl:items-start xl:justify-between">
                                    <div class="grid flex-1 grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-4">
                                        <div>
                                            <div class="text-xs text-slate-500">Task</div>
                                            <div class="mt-1 font-semibold text-slate-900">#<?= e((string)($r['custom_task_id'] ?? $r['task_id'])) ?></div>
                                        </div>
                                        <div>
                                            <div class="text-xs text-slate-500">Schedule</div>
                                            <div class="mt-1 font-medium text-slate-900"><?= e((string)$r['scheduled_date']) ?> <?= e((string)$r['scheduled_time']) ?></div>
                                        </div>
                                        <div>
                                            <div class="text-xs text-slate-500">Service</div>
                                            <div class="mt-1 font-medium text-slate-900"><?= e((string)($r['service_name'] ?? '')) ?></div>
                                        </div>
                                        <div>
                                            <div class="text-xs text-slate-500">Status</div>
                                            <div class="mt-1 font-medium text-slate-900"><?= e((string)($r['task_status'] ?? '')) ?></div>
                                        </div>
                                    </div>
                                    <div class="flex flex-wrap items-center gap-2">
                                        <a class="rounded-lg border px-3 py-1.5 text-xs hover:bg-slate-50" href="<?= e(Constants::APP_ROOT) ?>/admin/task_details.php?id=<?= e((string)$r['task_id']) ?>">View</a>
                                    </div>
                                </div>

                                <div class="mt-4 grid grid-cols-1 gap-4 lg:grid-cols-[minmax(0,1fr)_minmax(320px,420px)]">
                                    <div>
                                        <div class="text-xs text-slate-500">Property Address</div>
                                        <div class="mt-1 text-sm text-slate-700"><?= e((string)($r['property_address'] ?? '')) ?></div>
                                    </div>
                                    <div>
                                        <div class="rounded-xl border bg-slate-50 p-4">
                                            <div class="text-xs font-medium text-slate-600">Pictures</div>
                                            <div class="mt-2 text-sm text-slate-700">Hidden in this view. Click <span class="font-medium">View</span> above to open full task details with pictures and checklist images.</div>
                                            <div class="mt-3 text-xs text-slate-500">
                                                Total images: <?= e((string)count((array)($r['images'] ?? []))) ?>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
        <?php endif; ?>
    <?php else: ?>
        <div class="mt-5 rounded-2xl border border-slate-200 bg-slate-50 p-4">
            <div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                <div>
                    <div class="text-sm font-semibold text-slate-900">Task Summary</div>
                    <div class="text-xs text-slate-500">Grouped by same staff and customer to summarize workload quickly.</div>
                </div>
                <div class="rounded-lg border bg-white px-4 py-2 text-sm font-medium text-slate-700">
                    <?= e((string)count($summaryRows)) ?> group(s)
                </div>
            </div>
        </div>

        <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">Staff</th>
                        <th class="py-2 pr-4">Customer</th>
                        <th class="py-2 pr-4">Services</th>
                        <th class="py-2 pr-4">Pending</th>
                        <th class="py-2 pr-4">In Progress</th>
                        <th class="py-2 pr-4">Completed</th>
                        <th class="py-2 pr-4">Total Tasks</th>
                        <th class="py-2 pr-4">Latest Schedule</th>
                        <th class="py-2">Actions</th>
                    </tr>
                </thead>
                <tbody>
                <?php if (!$summaryRows): ?>
                    <tr class="border-b"><td class="py-3 text-slate-500" colspan="9">No tasks found.</td></tr>
                <?php else: ?>
                    <?php foreach ($summaryRows as $r): ?>
                        <tr class="border-b last:border-0">
                            <td class="py-3 pr-4"><?= e((string)($r['staff_name'] ?? '')) ?></td>
                            <td class="py-3 pr-4"><?= e((string)$r['customer_name']) ?></td>
                            <td class="py-3 pr-4 text-slate-600"><?= e((string)($r['service_summary'] ?: '-')) ?></td>
                            <td class="py-3 pr-4"><span class="inline-flex min-w-[2rem] items-center justify-center rounded-full bg-amber-50 px-2 py-1 text-xs font-semibold text-amber-700"><?= e((string)$r['pending_count']) ?></span></td>
                            <td class="py-3 pr-4"><span class="inline-flex min-w-[2rem] items-center justify-center rounded-full bg-blue-50 px-2 py-1 text-xs font-semibold text-blue-700"><?= e((string)$r['in_progress_count']) ?></span></td>
                            <td class="py-3 pr-4"><span class="inline-flex min-w-[2rem] items-center justify-center rounded-full bg-green-50 px-2 py-1 text-xs font-semibold text-green-700"><?= e((string)$r['completed_count']) ?></span></td>
                            <td class="py-3 pr-4 font-medium text-slate-900"><?= e((string)$r['task_count']) ?></td>
                            <td class="py-3 pr-4 text-slate-600"><?= e((string)($r['latest_schedule'] ?: '-')) ?></td>
                            <td class="py-3">
                                <div class="flex flex-wrap gap-2">
                                    <a class="rounded-lg border px-3 py-1.5 text-xs hover:bg-slate-50" href="/pest/public/admin/task_assignment.php?view=list&month=<?= e($monthStart->format('Y-m')) ?>&q=<?= urlencode($q) ?>&detail_staff=<?= urlencode((string)$r['staff_name']) ?>&detail_customer=<?= urlencode((string)$r['customer_name']) ?>">Details</a>
                                    <a class="rounded-lg border px-3 py-1.5 text-xs hover:bg-slate-50" href="/pest/public/admin/task_assignment.php?view=list&month=<?= e($monthStart->format('Y-m')) ?>&q=<?= urlencode($q) ?>&detail_staff=<?= urlencode((string)$r['staff_name']) ?>&detail_customer=<?= urlencode((string)$r['customer_name']) ?>#task-details">Edit</a>
                                    <a class="rounded-lg border px-3 py-1.5 text-xs hover:bg-slate-50" href="/pest/public/admin/task_assignment.php?view=calendar&month=<?= e($monthStart->format('Y-m')) ?>&detail_staff=<?= urlencode((string)$r['staff_name']) ?>&detail_customer=<?= urlencode((string)$r['customer_name']) ?>">Calendar</a>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
                </tbody>
            </table>
        </div>

        <?php if ($detailStaff !== '' && $detailCustomer !== ''): ?>
            <div id="task-details" class="mt-6 rounded-2xl border border-slate-200 bg-white p-5">
                <div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                    <div>
                        <div class="text-sm font-semibold text-slate-900">Task Details</div>
                        <div class="text-xs text-slate-500">Showing all tasks for <?= e($detailStaff) ?> and <?= e($detailCustomer) ?>.</div>
                    </div>
                    <div class="flex gap-2">
                        <a class="rounded-lg border px-4 py-2 text-sm hover:bg-slate-50" href="/pest/public/admin/task_assignment.php?view=calendar&month=<?= e($monthStart->format('Y-m')) ?>&detail_staff=<?= urlencode($detailStaff) ?>&detail_customer=<?= urlencode($detailCustomer) ?>">Calendar View</a>
                        <a class="rounded-lg border px-4 py-2 text-sm hover:bg-slate-50" href="/pest/public/admin/task_assignment.php?view=list&month=<?= e($monthStart->format('Y-m')) ?>&q=<?= urlencode($q) ?>">Close</a>
                    </div>
                </div>

                <div class="mt-4 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">Task</th>
                                <th class="py-2 pr-4">Schedule</th>
                                <th class="py-2 pr-4">Service</th>
                                <th class="py-2 pr-4">Status</th>
                                <th class="py-2">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!$detailRows): ?>
                                <tr class="border-b"><td class="py-3 text-slate-500" colspan="5">No tasks found for this summary group.</td></tr>
                            <?php else: ?>
                                <?php foreach ($detailRows as $task): ?>
                                    <tr class="border-b last:border-0">
                                        <td class="py-3 pr-4 font-medium">#<?= e((string)($task['custom_task_id'] ?? $task['task_id'])) ?></td>
                                        <td class="py-3 pr-4"><?= e((string)$task['scheduled_date']) ?> <?= e((string)$task['scheduled_time']) ?></td>
                                        <td class="py-3 pr-4"><?= e((string)$task['service_name']) ?></td>
                                        <td class="py-3 pr-4"><?= e((string)$task['task_status']) ?></td>
                                        <td class="py-3">
                                            <div class="flex flex-wrap gap-2">
                                                <a class="rounded-lg border px-3 py-1.5 text-xs hover:bg-slate-50" href="/pest/public/admin/task_details.php?id=<?= e((string)$task['task_id']) ?>">View</a>
                                                <a class="rounded-lg border px-3 py-1.5 text-xs hover:bg-slate-50" href="/pest/public/admin/task_edit.php?id=<?= e((string)$task['task_id']) ?>">Edit</a>
                                                <form method="post" action="/pest/public/admin/task_delete.php" onsubmit="return confirm('Delete this task?');">
                                                    <input type="hidden" name="id" value="<?= e((string)$task['task_id']) ?>">
                                                    <input type="hidden" name="return_view" value="list">
                                                    <input type="hidden" name="return_month" value="<?= e($monthStart->format('Y-m')) ?>">
                                                    <input type="hidden" name="return_detail_staff" value="<?= e($detailStaff) ?>">
                                                    <input type="hidden" name="return_detail_customer" value="<?= e($detailCustomer) ?>">
                                                    <button class="rounded-lg border border-red-200 bg-red-50 px-3 py-1.5 text-xs text-red-700 hover:bg-red-100" type="submit">Delete</button>
                                                </form>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        <?php endif; ?>
    <?php endif; ?>
</div>
<?php
$content = ob_get_clean();

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