<?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();
$adminId = (int)($user['user_id'] ?? 0);
$title = 'Assign Task';

$nav = [
    ['label' => 'Overview', 'href' => '/pest/public/admin/index.php', 'active' => false],
    ['label' => 'Customers', 'href' => '/pest/public/admin/customers.php', 'active' => false],
    ['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' => true],
    ['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],
];

$error = '';
$requests = [];
$staffList = [];
$customers = [];
$services = [];
$customerHistory = [];
$customerInfo = null;
$calendarMonthParam = trim((string)($_GET['calendar_month'] ?? date('Y-m')));
$calendarMonth = DateTimeImmutable::createFromFormat('Y-m', $calendarMonthParam) ?: new DateTimeImmutable('first day of this month');

$values = [
    'customer_id' => (string)($_GET['customer_id'] ?? ''),
    'request_id' => (string)($_GET['request_id'] ?? ''),
    'property_address' => '',
    'glue_box_count' => '0',
    'bait_box_count' => '0',
    'efk_count' => '0',
    'staff_id' => '',
    'scheduled_date' => date('Y-m-d'),
    'scheduled_time' => '09:00',
    'selected_dates' => [],
];

function generate_task_box_nos(int $glueCount, int $baitCount, int $efkCount): array
{
    $glueCount = max(0, $glueCount);
    $baitCount = max(0, $baitCount);
    $efkCount = max(0, $efkCount);

    $out = [];
    for ($i = 1; $i <= $glueCount; $i++) {
        $out[] = 'GLUE' . str_pad((string)$i, 3, '0', STR_PAD_LEFT);
    }
    for ($i = 1; $i <= $baitCount; $i++) {
        $out[] = 'BAIT' . str_pad((string)$i, 3, '0', STR_PAD_LEFT);
    }
    for ($i = 1; $i <= $efkCount; $i++) {
        $out[] = 'E.F.K' . str_pad((string)$i, 3, '0', STR_PAD_LEFT);
    }
    return $out;
}

function table_columns(PDO $pdo, string $table): array
{
    $stmt = $pdo->prepare(
        'SELECT column_name
         FROM information_schema.columns
         WHERE table_schema = DATABASE() AND table_name = :t'
    );
    $stmt->execute(['t' => $table]);
    return $stmt->fetchAll(PDO::FETCH_COLUMN);
}

function create_service_request_for_schedule(PDO $pdo, array $requestCols, array $data): int
{
    $insert = [];

    $map = [
        'customer_id' => $data['customer_id'] ?? null,
        'service_id' => $data['service_id'] ?? null,
        'property_address' => $data['property_address'] ?? null,
        'preferred_date' => $data['preferred_date'] ?? null,
        'preferred_time' => $data['preferred_time'] ?? null,
        'status' => $data['status'] ?? 'approved',
        'property_type' => $data['property_type'] ?? null,
        'pest_type' => $data['pest_type'] ?? null,
        'severity_level' => $data['severity_level'] ?? null,
        'special_instructions' => $data['special_instructions'] ?? null,
        'service_name' => $data['service_name'] ?? null,
        'created_at' => date('Y-m-d H:i:s'),
        'updated_at' => date('Y-m-d H:i:s'),
    ];

    foreach ($map as $col => $value) {
        if (in_array($col, $requestCols, true)) {
            $insert[$col] = $value;
        }
    }

    $columns = array_keys($insert);
    $placeholders = array_map(static fn (string $col): string => ':' . $col, $columns);
    $sql = 'INSERT INTO service_requests (' . implode(', ', $columns) . ') VALUES (' . implode(', ', $placeholders) . ')';
    $stmt = $pdo->prepare($sql);
    $stmt->execute($insert);

    return (int)$pdo->lastInsertId();
}

function normalize_selected_dates(array $dates, DateTimeImmutable $calendarMonth): array
{
    $normalized = [];
    $monthKey = $calendarMonth->format('Y-m');
    foreach ($dates as $date) {
        $date = trim((string)$date);
        if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
            continue;
        }
        if (substr($date, 0, 7) !== $monthKey) {
            continue;
        }
        $normalized[] = $date;
    }
    $normalized = array_values(array_unique($normalized));
    sort($normalized);
    return $normalized;
}

try {
    $pdo = Database::pdo();
    $requestCols = table_columns($pdo, 'service_requests');

    $customers = $pdo->query(
        "SELECT user_id, full_name, email
         FROM users
         WHERE user_type = 'customer' AND is_active = 1
         ORDER BY full_name ASC"
    )->fetchAll();

    $services = $pdo->query(
        "SELECT service_id, service_name, category
         FROM services
         WHERE is_active = 1
         ORDER BY service_name ASC"
    )->fetchAll();

    $customerId = (int)$values['customer_id'];

    $serviceLabelSql = in_array('service_name', $requestCols, true)
        ? 'COALESCE(s.service_name, sr.service_name, CONCAT("Request #", sr.request_id))'
        : 'COALESCE(s.service_name, CONCAT("Request #", sr.request_id))';
    $statusLabelSql = in_array('status', $requestCols, true)
        ? "COALESCE(sr.status, 'requested')"
        : "'requested'";

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

        $sqlReq = 'SELECT sr.request_id, u.full_name AS customer_name, ' . $serviceLabelSql . ' AS service_name, sr.preferred_date, sr.preferred_time, ' . $statusLabelSql . ' AS status
             FROM service_requests sr
             JOIN users u ON sr.customer_id = u.user_id
             LEFT JOIN services s ON sr.service_id = s.service_id
             WHERE sr.customer_id = :customer_id
               AND NOT EXISTS (
                   SELECT 1
                   FROM tasks t
                   WHERE t.request_id = sr.request_id
                     AND t.status <> "cancelled"
               )
             ORDER BY sr.created_at DESC';
        $stmtReq = $pdo->prepare($sqlReq);
        $stmtReq->execute(['customer_id' => $customerId]);
        $requests = $stmtReq->fetchAll();

        $stmtHist = $pdo->prepare(
            'SELECT
                sr.service_id AS service_id,
                ' . $serviceLabelSql . ' AS service_name,
                COUNT(*) AS times_taken,
                MAX(COALESCE(t.scheduled_date, sr.preferred_date, sr.created_at)) AS last_date
             FROM service_requests sr
             LEFT JOIN services s ON sr.service_id = s.service_id
             LEFT JOIN tasks t ON t.request_id = sr.request_id AND t.status <> "cancelled"
             WHERE sr.customer_id = :customer_id
             GROUP BY sr.service_id, service_name
             ORDER BY last_date DESC
             LIMIT 10'
        );
        $stmtHist->execute(['customer_id' => $customerId]);
        $customerHistory = $stmtHist->fetchAll();
    } else {
        $sqlReq = 'SELECT sr.request_id, u.full_name AS customer_name, ' . $serviceLabelSql . ' AS service_name, sr.preferred_date, sr.preferred_time, ' . $statusLabelSql . ' AS status
             FROM service_requests sr
             JOIN users u ON sr.customer_id = u.user_id
             LEFT JOIN services s ON sr.service_id = s.service_id
             WHERE NOT EXISTS (
                   SELECT 1
                   FROM tasks t
                   WHERE t.request_id = sr.request_id
                     AND t.status <> "cancelled"
               )
             ORDER BY sr.created_at DESC';
        $requests = $pdo->query($sqlReq)->fetchAll();
    }

    $staffList = $pdo->query(
        "SELECT u.user_id, u.full_name, sd.employee_code, sd.is_available
         FROM users u
         JOIN staff_details sd ON sd.user_id = u.user_id
         WHERE u.user_type = 'staff' AND u.is_active = 1
         ORDER BY sd.is_available DESC, u.full_name ASC"
    )->fetchAll();
} catch (Throwable $e) {
    $error = $e->getMessage();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $values['customer_id'] = trim((string)($_POST['customer_id'] ?? $values['customer_id']));
    $values['request_id'] = trim((string)($_POST['request_id'] ?? ''));
    $values['property_address'] = trim((string)($_POST['property_address'] ?? ''));
    $values['glue_box_count'] = trim((string)($_POST['glue_box_count'] ?? '0'));
    $values['bait_box_count'] = trim((string)($_POST['bait_box_count'] ?? '0'));
    $values['efk_count'] = trim((string)($_POST['efk_count'] ?? '0'));
    $values['staff_id'] = trim((string)($_POST['staff_id'] ?? ''));
    $values['scheduled_date'] = trim((string)($_POST['scheduled_date'] ?? ''));
    $values['scheduled_time'] = trim((string)($_POST['scheduled_time'] ?? ''));
    $values['selected_dates'] = normalize_selected_dates((array)($_POST['selected_dates'] ?? []), $calendarMonth);

    $customerId = (int)$values['customer_id'];
    $requestIdRaw = $values['request_id'];
    $requestId = 0;
    $serviceId = 0;
    if (strpos($requestIdRaw, 'service_') === 0) {
        $serviceId = (int)substr($requestIdRaw, 8);
    } else {
        $requestId = (int)$requestIdRaw;
    }
    $staffId = (int)$values['staff_id'];
    $scheduleDates = $values['selected_dates'];
    if (!$scheduleDates && $values['scheduled_date'] !== '') {
        $scheduleDates = [$values['scheduled_date']];
    }
    $glueCount = (int)$values['glue_box_count'];
    $baitCount = (int)$values['bait_box_count'];
    $efkCount = (int)$values['efk_count'];

    $generatedBoxes = generate_task_box_nos($glueCount, $baitCount, $efkCount);

    if ($customerId <= 0 || $staffId <= 0 || $values['scheduled_date'] === '' || $values['scheduled_time'] === '') {
        $error = 'All fields are required.';
    } elseif ($requestId <= 0 && ($serviceId <= 0 || $values['property_address'] === '')) {
        $error = 'Select a service request / service and enter property address.';
    } elseif (!$generatedBoxes) {
        $error = 'Enter box counts (Glue/Bait/E.F.K).';
    } elseif (!$scheduleDates) {
        $error = 'Select at least one date from the calendar or choose a scheduled date.';
    } else {
        try {
            $pdo = Database::pdo();
            $requestSeed = null;
            if ($requestId > 0) {
                $stmtSeed = $pdo->prepare('SELECT * FROM service_requests WHERE request_id = :id LIMIT 1');
                $stmtSeed->execute(['id' => $requestId]);
                $requestSeed = $stmtSeed->fetch();
                if (!$requestSeed) {
                    throw new RuntimeException('Selected service request was not found.');
                }
            }

            foreach ($scheduleDates as $index => $date) {
                $requestIdForTask = $requestId;

                if ($requestSeed) {
                    if ($index === 0) {
                        $requestIdForTask = (int)$requestSeed['request_id'];
                    } else {
                        $requestData = $requestSeed;
                        $requestData['preferred_date'] = $date;
                        $requestData['preferred_time'] = $values['scheduled_time'];
                        $requestData['status'] = 'approved';
                        $requestIdForTask = create_service_request_for_schedule($pdo, $requestCols, $requestData);
                    }
                } else {
                    $requestData = [
                        'customer_id' => $customerId,
                        'service_id' => $serviceId,
                        'property_address' => $values['property_address'],
                        'preferred_date' => $date,
                        'preferred_time' => $values['scheduled_time'],
                        'status' => 'approved',
                    ];
                    $requestIdForTask = create_service_request_for_schedule($pdo, $requestCols, $requestData);
                }

                $yearMonth = date('Y-m', strtotime($date));
                $stmtMaxNum = $pdo->prepare(
                    "SELECT COALESCE(MAX(CAST(SUBSTRING_INDEX(custom_task_id, '-', -1) AS UNSIGNED)), 0) AS max_num
                     FROM tasks
                     WHERE DATE_FORMAT(scheduled_date, '%Y-%m') = :ym
                       AND custom_task_id LIKE CONCAT(:ym, '-%')"
                );
                $stmtMaxNum->execute(['ym' => $yearMonth]);
                $maxNum = (int)($stmtMaxNum->fetchColumn() ?: 0);
                $nextNum = $maxNum + 1;
                $customTaskId = $yearMonth . '-' . $nextNum;

                $stmt = $pdo->prepare('CALL AssignTask(:request_id, :staff_id, :admin_id, :scheduled_date, :scheduled_time)');
                $stmt->execute([
                    'request_id' => $requestIdForTask,
                    'staff_id' => $staffId,
                    'admin_id' => $adminId,
                    'scheduled_date' => $date,
                    'scheduled_time' => $values['scheduled_time'],
                ]);
                $stmt->closeCursor();

                $stmtTid = $pdo->prepare(
                    'SELECT task_id
                     FROM tasks
                     WHERE request_id = :rid
                       AND assigned_staff_id = :sid
                       AND scheduled_date = :d
                       AND scheduled_time = :t
                     ORDER BY task_id DESC
                     LIMIT 1'
                );
                $stmtTid->execute([
                    'rid' => $requestIdForTask,
                    'sid' => $staffId,
                    'd' => $date,
                    't' => $values['scheduled_time'],
                ]);
                $taskId = (int)($stmtTid->fetchColumn() ?: 0);
                if ($taskId > 0) {
                    $stmtUpdateCustomId = $pdo->prepare('UPDATE tasks SET custom_task_id = :custom_id WHERE task_id = :tid');
                    $stmtUpdateCustomId->execute(['custom_id' => $customTaskId, 'tid' => $taskId]);
                    
                    TaskBoxService::setBoxNos($pdo, $taskId, $generatedBoxes, $adminId);
                    TaskBoxTypeService::setCounts($pdo, $taskId, $glueCount, $baitCount, $efkCount, $adminId);
                }
            }

            header('Location: /pest/public/admin/task_assignment.php');
            exit;
        } catch (Throwable $e) {
            if (isset($pdo) && $pdo instanceof PDO && $pdo->inTransaction()) {
                $pdo->rollBack();
            }
            $error = $e->getMessage();
        }
    }
}

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-center justify-between">
        <div>
            <h1 class="text-xl font-semibold">Assign Task</h1>
            <p class="mt-1 text-sm text-slate-600">Assign a service request to a staff member.</p>
        </div>
        <a class="rounded-lg border px-4 py-2 text-sm hover:bg-slate-50" href="/pest/public/admin/task_assignment.php">Back</a>
    </div>

    <form class="mt-6 grid grid-cols-1 gap-6 lg:grid-cols-3" method="post" action="">
        <div class="lg:col-span-2">
            <div class="grid grid-cols-1 gap-4 md:grid-cols-2">
                <div class="md:col-span-2">
                    <label class="block text-sm font-medium">Customer</label>
                    <select id="customerSelect" class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" name="customer_id">
                        <option value="">Select customer</option>
                        <?php foreach ($customers as $c): ?>
                            <option value="<?= e((string)$c['user_id']) ?>" <?= ($values['customer_id'] === (string)$c['user_id']) ? 'selected' : '' ?>>
                                <?= e((string)$c['full_name']) ?> (<?= e((string)$c['email']) ?>)
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <div class="mt-1 text-xs text-slate-500">Select a customer to view their requests and service history.</div>
                </div>

                <div class="md:col-span-2">
                    <label class="block text-sm font-medium">Service Request (recommended)</label>
                    <select class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" name="request_id">
                        <option value="">Select request</option>
                        <?php if ($services): ?>
                            <optgroup label="Services (Direct Assignment)">
                                <?php foreach ($services as $svc): ?>
                                    <option value="service_<?= e((string)$svc['service_id']) ?>" <?= ($values['request_id'] === 'service_' . (string)$svc['service_id']) ? 'selected' : '' ?>>
                                        <?= e((string)$svc['service_name']) ?><?= !empty($svc['category']) ? ' (' . e((string)$svc['category']) . ')' : '' ?>
                                    </option>
                                <?php endforeach; ?>
                            </optgroup>
                        <?php endif; ?>
                    </select>
                    <div class="mt-1 text-xs text-slate-500">Choose a service to assign directly.</div>
                </div>

                <div>
                    <label class="block text-sm font-medium">Property address</label>
                    <input class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" name="property_address" value="<?= e($values['property_address']) ?>" placeholder="Required for direct service">
                </div>

                <div class="md:col-span-2">
                    <label class="block text-sm font-medium">Box Types</label>
                    <div class="mt-1 grid grid-cols-1 gap-3 sm:grid-cols-3">
                        <div>
                            <label class="block text-xs text-slate-500">Glue Box</label>
                            <input class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" type="number" min="0" name="glue_box_count" value="<?= e((string)$values['glue_box_count']) ?>">
                        </div>
                        <div>
                            <label class="block text-xs text-slate-500">Bait Box</label>
                            <input class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" type="number" min="0" name="bait_box_count" value="<?= e((string)$values['bait_box_count']) ?>">
                        </div>
                        <div>
                            <label class="block text-xs text-slate-500">E.F.K - Electric Fly Killer</label>
                            <input class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" type="number" min="0" name="efk_count" value="<?= e((string)$values['efk_count']) ?>">
                        </div>
                    </div>
                    <div class="mt-1 text-xs text-slate-500">These counts will be saved for this task and used for staff uploads (E.F.K numbers).</div>
                </div>

                <div class="md:col-span-2">
                    <label class="block text-sm font-medium">Assign Staff</label>
                    <select class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" name="staff_id" required>
                        <option value="">Select staff</option>
                        <?php foreach ($staffList as $s): ?>
                            <option value="<?= e((string)$s['user_id']) ?>" <?= ($values['staff_id'] === (string)$s['user_id']) ? 'selected' : '' ?>>
                                <?= e((string)$s['full_name']) ?> (<?= e((string)$s['employee_code']) ?>) - <?= ((int)$s['is_available'] === 1) ? 'Available' : 'Busy' ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

        <div>
            <label class="block text-sm font-medium">Scheduled date</label>
            <input class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" type="date" name="scheduled_date" value="<?= e($values['scheduled_date']) ?>" required>
        </div>
        <div>
            <label class="block text-sm font-medium">Scheduled time</label>
            <input class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" type="time" name="scheduled_time" value="<?= e($values['scheduled_time']) ?>" required>
        </div>

        <?php
            $calendarMonthStart = $calendarMonth->modify('first day of this month');
            $calendarMonthEnd = $calendarMonth->modify('last day of this month');
            $gridStart = $calendarMonthStart->modify('-' . ((int)$calendarMonthStart->format('N') - 1) . ' days');
            $gridEnd = $calendarMonthEnd->modify('+' . (7 - (int)$calendarMonthEnd->format('N')) . ' days');
            $prevCalendarMonth = $calendarMonthStart->modify('-1 month')->format('Y-m');
            $nextCalendarMonth = $calendarMonthStart->modify('+1 month')->format('Y-m');
            $selectedDatesMap = array_fill_keys($values['selected_dates'], true);
        ?>

            </div>

            <div class="mt-6 rounded-2xl border border-slate-200 bg-white 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">Whole month calendar</div>
                    <div class="text-xs text-slate-500">Choose any dates you want for this assignment. If you leave all dates unselected, the scheduled date field above will be used.</div>
                </div>
                <div class="flex gap-2">
                    <button type="button" id="btnSelectAllDates" class="rounded-lg border border-blue-200 bg-blue-50 px-4 py-2 text-sm font-medium text-blue-700 hover:bg-blue-100">Select All Dates</button>
                    <a class="rounded-lg border px-4 py-2 text-sm hover:bg-slate-50" href="?customer_id=<?= e($values['customer_id']) ?>&calendar_month=<?= e($prevCalendarMonth) ?>">Previous</a>
                    <div class="rounded-lg border bg-slate-50 px-4 py-2 text-sm font-medium"><?= e($calendarMonthStart->format('F Y')) ?></div>
                    <a class="rounded-lg border px-4 py-2 text-sm hover:bg-slate-50" href="?customer_id=<?= e($values['customer_id']) ?>&calendar_month=<?= e($nextCalendarMonth) ?>">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
                        $dayValue = $day->format('Y-m-d');
                        $isCurrentMonth = ($day->format('Y-m') === $calendarMonthStart->format('Y-m'));
                        $isSelected = isset($selectedDatesMap[$dayValue]);
                    ?>
                    <label class="block cursor-pointer rounded-xl border p-3 <?= $isSelected ? 'border-slate-900 bg-slate-900 text-white' : ($isCurrentMonth ? 'border-slate-200 bg-white text-slate-900' : 'border-slate-100 bg-slate-100 text-slate-400') ?>">
                        <input class="hidden js-calendar-date" type="checkbox" name="selected_dates[]" value="<?= e($dayValue) ?>" <?= $isSelected ? 'checked' : '' ?> <?= $isCurrentMonth ? '' : 'disabled' ?>>
                        <div class="flex items-center justify-between">
                            <span class="text-sm font-semibold"><?= e($day->format('d')) ?></span>
                            <span class="text-[11px] <?= $isSelected ? 'text-slate-200' : 'text-slate-400' ?>"><?= e($day->format('D')) ?></span>
                        </div>
                        <div class="mt-4 text-[11px] <?= $isSelected ? 'text-slate-200' : 'text-slate-500' ?>">
                            <?= $isCurrentMonth ? ($isSelected ? 'Selected' : 'Click to select') : 'Outside month' ?>
                        </div>
                    </label>
                <?php endfor; ?>
            </div>
        </div>

            <div class="mt-6">
                <button class="w-full rounded-lg bg-slate-900 px-4 py-2 text-sm font-medium text-white hover:bg-slate-800" type="submit">Assign</button>
            </div>
        </div>

        <div class="lg:col-span-1">
            <div class="rounded-2xl border bg-slate-50 p-4">
                <div class="text-sm font-semibold">Customer service history</div>
                <div class="mt-1 text-xs text-slate-500">Already taken services (latest first).</div>

                <?php if (!$customerInfo): ?>
                    <div class="mt-4 text-sm text-slate-500">Select a customer to view their history.</div>
                <?php else: ?>
                    <div class="mt-4 rounded-xl border bg-white p-3">
                        <div class="text-sm font-medium"><?= e((string)($customerInfo['full_name'] ?? '')) ?></div>
                        <div class="text-xs text-slate-500"><?= e((string)($customerInfo['email'] ?? '')) ?></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-3">Service</th>
                                    <th class="py-2 pr-3">Times</th>
                                    <th class="py-2">Last</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (!$customerHistory): ?>
                                    <tr class="border-b"><td class="py-3 text-slate-500" colspan="3">No previous services found.</td></tr>
                                <?php else: ?>
                                    <?php foreach ($customerHistory as $h): ?>
                                        <?php
                                            $sid = (int)($h['service_id'] ?? 0);
                                            $svcHref = $sid > 0 ? ('/pest/public/admin/service_details.php?id=' . $sid) : '';
                                        ?>
                                        <tr class="border-b last:border-0">
                                            <td class="py-3 pr-3">
                                                <?php if ($svcHref !== ''): ?>
                                                    <a class="font-semibold text-slate-900 hover:underline" href="<?= e($svcHref) ?>"><?= e((string)($h['service_name'] ?? '')) ?></a>
                                                <?php else: ?>
                                                    <span class="font-semibold"><?= e((string)($h['service_name'] ?? '')) ?></span>
                                                <?php endif; ?>
                                            </td>
                                            <td class="py-3 pr-3"><?= e((string)($h['times_taken'] ?? '')) ?></td>
                                            <td class="py-3"><?= e((string)($h['last_date'] ?? '')) ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </form>
</div>

<script>
(function () {
    var sel = document.getElementById('customerSelect');
    if (!sel) return;
    sel.addEventListener('change', function () {
        var cid = sel.value || '';
        var url = new URL(window.location.href);
        if (cid) {
            url.searchParams.set('customer_id', cid);
        } else {
            url.searchParams.delete('customer_id');
        }
        url.searchParams.delete('request_id');
        window.location.href = url.toString();
    });
})();

(function () {
    var boxes = document.querySelectorAll('.js-calendar-date');
    for (var i = 0; i < boxes.length; i++) {
        boxes[i].addEventListener('change', function () {
            var label = this.closest('label');
            if (!label) return;
            if (this.checked) {
                label.classList.remove('border-slate-200', 'bg-white', 'text-slate-900');
                label.classList.add('border-slate-900', 'bg-slate-900', 'text-white');
            } else {
                label.classList.remove('border-slate-900', 'bg-slate-900', 'text-white');
                label.classList.add('border-slate-200', 'bg-white', 'text-slate-900');
            }
        });
    }
})();

(function () {
    var btnSelectAll = document.getElementById('btnSelectAllDates');
    if (!btnSelectAll) return;
    
    btnSelectAll.addEventListener('click', function () {
        var boxes = document.querySelectorAll('.js-calendar-date');
        for (var i = 0; i < boxes.length; i++) {
            if (!boxes[i].disabled && !boxes[i].checked) {
                boxes[i].checked = true;
                var label = boxes[i].closest('label');
                if (label) {
                    label.classList.remove('border-slate-200', 'bg-white', 'text-slate-900');
                    label.classList.add('border-slate-900', 'bg-slate-900', 'text-white');
                }
            }
        }
    });
})();
</script>
<?php
$content = ob_get_clean();
require __DIR__ . '/../../includes/dashboard_layout.php';
