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

$id = (int)($_GET['id'] ?? 0);
$row = null;
$checklist = null;
$boxNos = [];
$boxNo = '';
$uploadFor = trim((string)($_POST['upload_for'] ?? 'box'));
$efkNo = (int)($_POST['efk_no'] ?? 0);
$latRaw = (string)($_POST['lat'] ?? '');
$lngRaw = (string)($_POST['lng'] ?? '');
$accRaw = (string)($_POST['acc'] ?? '');
$imagesByBox = [];
$imagesByEfk = [];
$imagesByChecklist = [];
$boxTypeCounts = ['glue_box_count' => 0, 'bait_box_count' => 0, 'efk_count' => 0];
$error = '';
$success = '';

$checkFields = [
    'fumigation_completed' => 'Fumigation Completed',
    'bait_box_checked' => 'Bait Box Checked',
    'glue_box_checked' => 'Glue Box Checked',
    'efk_checked' => "E.F.K's Checked",
    'ilt_checked' => "I.L.T 's Checked",
    'others_checked' => "Other's",
];

function normalize_files_array(array $files): array
{
    $out = [];
    if (!isset($files['name']) || !is_array($files['name'])) {
        return $out;
    }
    $count = count($files['name']);
    for ($i = 0; $i < $count; $i++) {
        $out[] = [
            'name' => $files['name'][$i] ?? '',
            'type' => $files['type'][$i] ?? '',
            'tmp_name' => $files['tmp_name'][$i] ?? '',
            'error' => $files['error'][$i] ?? UPLOAD_ERR_NO_FILE,
            'size' => $files['size'][$i] ?? 0,
        ];
    }
    return $out;
}

function load_task_checklist_images_grouped_staff(int $taskId): array
{
    $uploadsRoot = realpath(__DIR__ . '/../') ?: (__DIR__ . '/../');
    $relBase = 'uploads/tasks/' . $taskId;
    $absBase = $uploadsRoot . '/' . $relBase;
    $out = [];
    if (!is_dir($absBase)) {
        return $out;
    }
    $list = scandir($absBase);
    if (!is_array($list)) {
        return $out;
    }
    foreach ($list as $f) {
        if ($f === '.' || $f === '..') {
            continue;
        }
        $p = $absBase . '/' . $f;
        if (is_dir($p) && strpos($f, 'check_') === 0) {
            $key = substr($f, 6);
            $sub = scandir($p);
            if (!is_array($sub)) {
                continue;
            }
            foreach ($sub as $sf) {
                if ($sf === '.' || $sf === '..') {
                    continue;
                }
                $sp = $p . '/' . $sf;
                if (is_file($sp)) {
                    $out[$key][] = '/' . $relBase . '/' . $f . '/' . $sf;
                }
            }
            if (!empty($out[$key])) {
                rsort($out[$key]);
            }
        }
    }
    return $out;
}

$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;
};

if ($id > 0) {
    try {
        $pdo = Database::pdo();
        $stmt = $pdo->prepare(
            "SELECT a.*
             FROM admin_all_tasks a
             JOIN tasks t ON t.task_id = a.task_id
             WHERE a.task_id = :id
               AND t.assigned_staff_id = :staff_id
             LIMIT 1"
        );
        $stmt->execute([
            'id' => $id,
            'staff_id' => (int)($user['user_id'] ?? 0),
        ]);
        $row = $stmt->fetch();
        if (!$row) {
            $error = 'Task not found or not assigned to you.';
        } else {
            $checklist = TaskChecklistService::get($pdo, $id);
            $boxNos = TaskBoxService::getBoxNos($pdo, $id);
            $boxTypeCounts = TaskBoxTypeService::getCounts($pdo, $id);
            $imagesByChecklist = load_task_checklist_images_grouped_staff($id);

            $uploadsRoot = realpath(__DIR__ . '/../') ?: (__DIR__ . '/../');
            $relBase = 'uploads/tasks/' . $id;
            $absBase = $uploadsRoot . '/' . $relBase;
            if (is_dir($absBase)) {
                $list = scandir($absBase);
                if (is_array($list)) {
                    foreach ($list as $f) {
                        if ($f === '.' || $f === '..') {
                            continue;
                        }
                        $p = $absBase . '/' . $f;
                        if (is_file($p)) {
                            $imagesByBox['Unassigned'][] = '/' . $relBase . '/' . $f;
                            continue;
                        }
                        if (is_dir($p) && strpos($f, 'box_') === 0) {
                            $boxLabel = substr($f, 4);
                            $sub = scandir($p);
                            if (!is_array($sub)) {
                                continue;
                            }
                            foreach ($sub as $sf) {
                                if ($sf === '.' || $sf === '..') {
                                    continue;
                                }
                                $sp = $p . '/' . $sf;
                                if (is_file($sp)) {
                                    $imagesByBox[$boxLabel][] = '/' . $relBase . '/' . $f . '/' . $sf;
                                }
                            }
                        }

                        if (is_dir($p) && strpos($f, 'efk_') === 0) {
                            $efkLabel = substr($f, 4);
                            $sub = scandir($p);
                            if (!is_array($sub)) {
                                continue;
                            }
                            foreach ($sub as $sf) {
                                if ($sf === '.' || $sf === '..') {
                                    continue;
                                }
                                $sp = $p . '/' . $sf;
                                if (is_file($sp)) {
                                    $imagesByEfk[$efkLabel][] = '/' . $relBase . '/' . $f . '/' . $sf;
                                }
                            }
                        }
                    }
                }
            }
        }
    } catch (Throwable $e) {
        $error = $e->getMessage();
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $error === '' && $id > 0 && isset($_POST['upload_check_images'])) {
    try {
        $checkKeyRaw = trim((string)($_POST['check_key'] ?? ''));
        $checkKey = preg_replace('/[^a-z0-9_]+/i', '', $checkKeyRaw) ?: '';
        if ($checkKey === '' || !isset($checkFields[$checkKey])) {
            throw new RuntimeException('Invalid checklist item.');
        }
        if (!isset($_FILES['images'])) {
            throw new RuntimeException('Please select images to upload.');
        }

        $files = normalize_files_array($_FILES['images']);
        $files = array_values(array_filter($files, static function (array $f): bool {
            return (int)($f['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_NO_FILE;
        }));

        if (count($files) < 1) {
            throw new RuntimeException('Please select at least 1 image.');
        }
        if (count($files) > 5) {
            throw new RuntimeException('You can upload maximum 5 images.');
        }

        $pdo = Database::pdo();
        $stmtOwn = $pdo->prepare('SELECT assigned_staff_id, status FROM tasks WHERE task_id = :id LIMIT 1');
        $stmtOwn->execute(['id' => $id]);
        $t = $stmtOwn->fetch(PDO::FETCH_ASSOC);
        $assignedStaff = (int)($t['assigned_staff_id'] ?? 0);
        if ($assignedStaff !== (int)($user['user_id'] ?? 0)) {
            throw new RuntimeException('Invalid task selection.');
        }

        $uploadsRoot = realpath(__DIR__ . '/../') ?: (__DIR__ . '/../');
        $relDir = 'uploads/tasks/' . $id . '/check_' . $checkKey;
        $absDir = $uploadsRoot . '/' . $relDir;
        if (!is_dir($absDir)) {
            if (!mkdir($absDir, 0775, true) && !is_dir($absDir)) {
                throw new RuntimeException('Failed to create upload directory.');
            }
        }

        $allowedMimes = [
            'image/jpeg' => 'jpg',
            'image/png' => 'png',
            'image/webp' => 'webp',
            'image/gif' => 'gif',
        ];
        $maxBytes = 5 * 1024 * 1024;
        $finfo = new finfo(FILEINFO_MIME_TYPE);

        foreach ($files as $f) {
            if ((int)$f['error'] !== UPLOAD_ERR_OK) {
                throw new RuntimeException('One of the files failed to upload.');
            }
            if ((int)$f['size'] <= 0 || (int)$f['size'] > $maxBytes) {
                throw new RuntimeException('Each image must be less than 5MB.');
            }
            $mime = $finfo->file((string)$f['tmp_name']);
            if (!isset($allowedMimes[$mime])) {
                throw new RuntimeException('Only JPG, PNG, WEBP, GIF images are allowed.');
            }
            $ext = $allowedMimes[$mime];
            $safeName = bin2hex(random_bytes(16)) . '.' . $ext;
            $absPath = $absDir . '/' . $safeName;
            if (!move_uploaded_file((string)$f['tmp_name'], $absPath)) {
                throw new RuntimeException('Failed to save uploaded file.');
            }
        }

        header('Location: ' . Constants::APP_ROOT . '/staff/task_details.php?id=' . $id);
        exit;
    } catch (Throwable $e) {
        $error = $e->getMessage();
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $error === '' && $id > 0 && isset($_POST['complete_task'])) {
    try {
        $pdo = Database::pdo();
        $stmtOwn = $pdo->prepare('SELECT assigned_staff_id, status FROM tasks WHERE task_id = :id LIMIT 1');
        $stmtOwn->execute(['id' => $id]);
        $t = $stmtOwn->fetch(PDO::FETCH_ASSOC);
        $assignedStaff = (int)($t['assigned_staff_id'] ?? 0);
        $currentStatus = strtolower(trim((string)($t['status'] ?? '')));

        if ($assignedStaff !== (int)($user['user_id'] ?? 0)) {
            throw new RuntimeException('Invalid task selection.');
        }
        if (in_array($currentStatus, ['cancelled'], true)) {
            throw new RuntimeException('Cancelled tasks cannot be completed.');
        }
        if ($currentStatus !== 'completed') {
            $stmtUp = $pdo->prepare('UPDATE tasks SET status = :s WHERE task_id = :id');
            $stmtUp->execute(['s' => 'completed', 'id' => $id]);
        }

        header('Location: ' . Constants::APP_ROOT . '/staff/task_details.php?id=' . $id);
        exit;
    } catch (Throwable $e) {
        $error = $e->getMessage();
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $error === '' && $id > 0 && isset($_POST['save_checklist'])) {
    try {
        $pdo = Database::pdo();
        $flags = [];
        foreach ($checkFields as $k => $label) {
            $flags[$k] = !empty($_POST[$k]);
        }
        $flags['others_text'] = (string)($_POST['others_text'] ?? '');
        TaskChecklistService::save($pdo, $id, $flags, (int)($user['user_id'] ?? 0));
        header('Location: ' . Constants::APP_ROOT . '/staff/task_details.php?id=' . $id);
        exit;
    } catch (Throwable $e) {
        $error = $e->getMessage();
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $error === '' && $id > 0 && isset($_POST['upload_images'])) {
    $boxNo = trim((string)($_POST['box_no'] ?? ''));
    $uploadFor = trim((string)($_POST['upload_for'] ?? 'box'));
    $efkNo = (int)($_POST['efk_no'] ?? 0);
    try {
        $pdo = Database::pdo();
        $boxNos = TaskBoxService::getBoxNos($pdo, $id);
        $boxTypeCounts = TaskBoxTypeService::getCounts($pdo, $id);

        if ($uploadFor !== 'box' && $uploadFor !== 'efk') {
            throw new RuntimeException('Invalid upload selection.');
        }

        if ($uploadFor === 'box' && $boxNos && $boxNo === '') {
            throw new RuntimeException('Please select a Box No.');
        }
        if ($uploadFor === 'box' && $boxNo !== '' && $boxNos && !in_array($boxNo, $boxNos, true)) {
            throw new RuntimeException('Invalid Box No selection.');
        }

        if ($uploadFor === 'efk') {
            $efkCount = (int)($boxTypeCounts['efk_count'] ?? 0);
            if ($efkCount <= 0) {
                throw new RuntimeException('No E.F.K items set for this task.');
            }
            if ($efkNo <= 0 || $efkNo > $efkCount) {
                throw new RuntimeException('Please select a valid E.F.K number.');
            }
        }
        if (!isset($_FILES['images'])) {
            throw new RuntimeException('Please select images to upload.');
        }

        $uploadsRoot = realpath(__DIR__ . '/../') ?: (__DIR__ . '/../');
        $relDir = 'uploads/tasks/' . $id;
        if ($uploadFor === 'efk') {
            $relDir .= '/efk_' . (int)$efkNo;
        } else {
            if ($boxNo !== '') {
                $safeBoxDir = preg_replace('/[^a-zA-Z0-9_-]+/', '_', $boxNo) ?: '';
                if ($safeBoxDir !== '') {
                    $relDir .= '/box_' . $safeBoxDir;
                }
            }
        }
        $absDir = $uploadsRoot . '/' . $relDir;

        if (!is_dir($absDir)) {
            if (!mkdir($absDir, 0775, true) && !is_dir($absDir)) {
                throw new RuntimeException('Failed to create upload directory.');
            }
        }

        $allowedMimes = [
            'image/jpeg' => 'jpg',
            'image/png' => 'png',
            'image/webp' => 'webp',
            'image/gif' => 'gif',
        ];
        $maxBytes = 5 * 1024 * 1024;
        $files = normalize_files_array($_FILES['images']);
        $finfo = new finfo(FILEINFO_MIME_TYPE);

        foreach ($files as $f) {
            if ((int)$f['error'] === UPLOAD_ERR_NO_FILE) {
                continue;
            }
            if ((int)$f['error'] !== UPLOAD_ERR_OK) {
                throw new RuntimeException('One of the files failed to upload.');
            }
            if ((int)$f['size'] <= 0 || (int)$f['size'] > $maxBytes) {
                throw new RuntimeException('Each image must be less than 5MB.');
            }

            $mime = $finfo->file((string)$f['tmp_name']);
            if (!isset($allowedMimes[$mime])) {
                throw new RuntimeException('Only JPG, PNG, WEBP, GIF images are allowed.');
            }

            $ext = $allowedMimes[$mime];
            $safeName = bin2hex(random_bytes(16)) . '.' . $ext;
            $absPath = $absDir . '/' . $safeName;
            if (!move_uploaded_file((string)$f['tmp_name'], $absPath)) {
                throw new RuntimeException('Failed to save uploaded file.');
            }
        }

        if ($latRaw !== '' && $lngRaw !== '') {
            $lat = (float)$latRaw;
            $lng = (float)$lngRaw;
            $acc = null;
            if ($accRaw !== '' && is_numeric($accRaw)) {
                $acc = (int)round((float)$accRaw);
            }
            if ($lat >= -90 && $lat <= 90 && $lng >= -180 && $lng <= 180) {
                try {
                    $staffId = (int)($user['user_id'] ?? 0);
                    if ($staffId > 0) {
                        $activeId = StaffLocationService::getActiveSessionId($pdo, $staffId);
                        if ($activeId !== null) {
                            StaffLocationService::logPoint($pdo, $activeId, $staffId, $lat, $lng, $acc);
                        }
                    }
                } catch (Throwable $e) {
                    // Ignore location history errors; images are already uploaded.
                }
            }
        }

        header('Location: ' . Constants::APP_ROOT . '/staff/task_details.php?id=' . $id);
        exit;
    } catch (Throwable $e) {
        $error = $e->getMessage();
    }
}

$nav = [
    ['label' => 'My Tasks', 'href' => Constants::APP_ROOT . '/staff/index.php', 'active' => false],
    ['label' => 'Task Details', 'href' => Constants::APP_ROOT . '/staff/task_details.php', 'active' => true],
    ['label' => 'Upload Images', 'href' => Constants::APP_ROOT . '/staff/upload_images.php', 'active' => false],
    ['label' => 'Location Tracker', 'href' => Constants::APP_ROOT . '/staff/location.php', 'active' => false],
    ['label' => 'Task History', 'href' => Constants::APP_ROOT . '/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">
    <div class="flex items-start justify-between gap-4">
        <div>
            <h1 class="text-xl font-semibold">Task Details</h1>
            <p class="mt-1 text-sm text-slate-600">Details for tasks assigned by admin.</p>
        </div>
        <div class="flex items-center gap-2">
            <?php if ($row): ?>
                <?php $statusUi = strtolower(trim((string)($row['task_status'] ?? ''))); ?>
                <span class="inline-flex items-center rounded-full border bg-slate-50 px-3 py-1 text-xs font-medium text-slate-700"><?= e((string)($row['task_status'] ?? '')) ?></span>
                <?php if (!in_array($statusUi, ['completed', 'cancelled'], true)): ?>
                    <form method="post" action="" onsubmit="return confirm('Mark this task as completed?');">
                        <input type="hidden" name="complete_task" value="1">
                        <button class="rounded-xl bg-gradient-to-b from-emerald-600 to-emerald-700 px-4 py-2 text-sm font-semibold text-white shadow hover:from-emerald-500 hover:to-emerald-700 active:translate-y-px" type="submit">Complete Task</button>
                    </form>
                <?php endif; ?>
            <?php endif; ?>
            <a class="rounded-lg border px-4 py-2 text-sm hover:bg-slate-50" href="<?= e(Constants::APP_ROOT) ?>/staff/index.php">Back</a>
        </div>
    </div>

    <?php if ($id <= 0): ?>
        <div class="mt-6 rounded-xl border bg-slate-50 p-4 text-sm text-slate-700">
            Select a task from <span class="font-medium">My Tasks</span> to view details.
        </div>
    <?php elseif ($row): ?>
        <div id="checkUploadModal" class="fixed inset-0 z-50 hidden">
            <div class="absolute inset-0 bg-slate-900/60" data-close-check-modal="1"></div>
            <div class="absolute inset-0 flex items-center justify-center p-4">
                <div class="w-full max-w-lg rounded-2xl bg-white shadow-xl">
                    <div class="flex items-start justify-between gap-4 border-b p-5">
                        <div>
                            <div class="text-base font-semibold" id="checkModalTitle">Upload images</div>
                            <div class="mt-1 text-xs text-slate-500">Minimum 1 image, maximum 5 images.</div>
                        </div>
                        <button type="button" class="rounded-lg border px-3 py-1.5 text-sm" data-close-check-modal="1">Close</button>
                    </div>
                    <form class="p-5" method="post" action="" enctype="multipart/form-data" id="checkModalForm">
                        <input type="hidden" name="upload_check_images" value="1">
                        <input type="hidden" name="check_key" id="checkModalKey" value="">
                        <div class="rounded-xl border bg-slate-50 p-4 text-sm" id="checkModalSelected"></div>
                        <div class="mt-4">
                            <label class="block text-sm font-medium">Images</label>
                            <input class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" type="file" name="images[]" accept="image/*" multiple required>
                            <div class="mt-1 text-xs text-slate-500">Allowed: JPG, PNG, WEBP, GIF. Max 5MB each.</div>
                        </div>
                        <div class="mt-5">
                            <button class="w-full rounded-xl bg-slate-900 px-4 py-3 text-sm font-semibold text-white hover:bg-slate-800" type="submit">Upload</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <div class="mt-6 grid grid-cols-1 gap-6 lg:grid-cols-2">
            <div class="rounded-xl border bg-slate-50 p-4">
                <div class="text-xs font-medium text-slate-600">Task</div>
                <div class="mt-2 text-sm">
                    <div><span class="text-slate-500">Task ID:</span> <span class="font-medium">#<?= e((string)$row['task_id']) ?></span></div>
                    <div class="mt-1"><span class="text-slate-500">Status:</span> <span class="font-medium"><?= e((string)($row['task_status'] ?? '')) ?></span></div>
                    <div class="mt-1"><span class="text-slate-500">Scheduled:</span> <span class="font-medium"><?= e((string)($row['scheduled_date'] ?? '')) ?> <?= e((string)($row['scheduled_time'] ?? '')) ?></span></div>
                </div>
            </div>

            <div class="rounded-xl border bg-slate-50 p-4">
                <div class="text-xs font-medium text-slate-600">Customer & Service</div>
                <div class="mt-2 text-sm">
                    <div><span class="text-slate-500">Customer:</span> <span class="font-medium"><?= e((string)($row['customer_name'] ?? '')) ?></span></div>
                    <div class="mt-1"><span class="text-slate-500">Service:</span> <span class="font-medium"><?= e((string)($row['service_name'] ?? '')) ?></span></div>
                    <?php if (isset($row['property_address'])): ?>
                        <div class="mt-1"><span class="text-slate-500">Address:</span> <span class="font-medium"><?= e((string)($row['property_address'] ?? '')) ?></span></div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <div class="mt-6 rounded-xl border bg-white p-4">
            <div class="text-sm font-semibold">E.F.K Images</div>
            <div class="mt-3 space-y-4">
                <?php if (!$imagesByEfk): ?>
                    <div class="text-sm text-slate-500">No E.F.K images uploaded for this task.</div>
                <?php else: ?>
                    <?php foreach ($imagesByEfk as $efkLabel => $paths): ?>
                        <?php if (!$paths) continue; ?>
                        <div>
                            <div class="text-xs font-medium text-slate-600">E.F.K #<?= e((string)$efkLabel) ?></div>
                            <div class="mt-2 grid grid-cols-2 gap-3 md:grid-cols-4">
                                <?php foreach ($paths as $p): ?>
                                    <?php $pub = $toPublic((string)$p); ?>
                                    <a class="block overflow-hidden rounded-lg border bg-white" href="<?= e((string)$pub) ?>" target="_blank" rel="noopener">
                                        <img class="h-32 w-full object-cover" src="<?= e((string)$pub) ?>" alt="EFK image">
                                    </a>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>

        <div class="mt-6 rounded-xl border bg-white p-4">
            <div class="text-xs font-medium text-slate-600">Additional</div>
            <div class="mt-3 grid grid-cols-1 gap-4 md:grid-cols-3 text-sm">
                <?php if (isset($row['pest_type'])): ?>
                    <div>
                        <div class="text-xs text-slate-500">Pest Type</div>
                        <div class="font-medium"><?= e((string)($row['pest_type'] ?? '')) ?></div>
                    </div>
                <?php endif; ?>
                <?php if (isset($row['severity_level'])): ?>
                    <div>
                        <div class="text-xs text-slate-500">Severity</div>
                        <div class="font-medium"><?= e((string)($row['severity_level'] ?? '')) ?></div>
                    </div>
                <?php endif; ?>
                <?php if (isset($row['payment_status'])): ?>
                    <div>
                        <div class="text-xs text-slate-500">Payment Status</div>
                        <div class="font-medium"><?= e((string)($row['payment_status'] ?? '')) ?></div>
                    </div>
                <?php endif; ?>
            </div>

            <form class="mt-6" method="post" action="">
                <input type="hidden" name="save_checklist" value="1">
                <?php
                    $checkGroups = [
                        'Fumigation' => ['fumigation_completed'],
                        'Boxes' => ['bait_box_checked', 'glue_box_checked'],
                        'Machines' => ['efk_checked', 'ilt_checked'],
                        'Others' => ['others_checked'],
                    ];
                ?>

                <div class="space-y-5">
                    <?php foreach ($checkGroups as $groupTitle => $keys): ?>
                        <div class="rounded-xl border bg-slate-50 p-4">
                            <div class="text-xs font-semibold text-slate-700"><?= e((string)$groupTitle) ?></div>
                            <div class="mt-3 grid grid-cols-1 gap-3 md:grid-cols-2">
                                <?php foreach ($keys as $k): ?>
                                    <?php $label = $checkFields[$k] ?? $k; ?>
                                    <?php $isChecked = !empty($checklist[$k]); ?>
                                    <label class="flex items-center gap-2 rounded-lg border bg-white px-3 py-2 text-sm">
                                        <input class="chk" type="checkbox" name="<?= e((string)$k) ?>" value="1" <?= $isChecked ? 'checked' : '' ?> data-check-key="<?= e((string)$k) ?>" <?= ($k === 'others_checked') ? 'data-others="1"' : '' ?>>
                                        <span><?= e((string)$label) ?></span>
                                    </label>

                                    <?php if (!empty($imagesByChecklist[$k])): ?>
                                        <div class="md:col-span-2">
                                            <div class="mt-2 grid grid-cols-2 gap-3 md:grid-cols-4">
                                                <?php foreach (($imagesByChecklist[$k] ?? []) as $p): ?>
                                                    <?php $pub = $toPublic((string)$p); ?>
                                                    <a class="block overflow-hidden rounded-lg border bg-white" href="<?= e((string)$pub) ?>" target="_blank" rel="noopener">
                                                        <img class="h-24 w-full object-cover" src="<?= e((string)$pub) ?>" alt="Checklist image">
                                                    </a>
                                                <?php endforeach; ?>
                                            </div>
                                        </div>
                                    <?php endif; ?>

                                    <?php if ($k === 'others_checked'): ?>
                                        <div id="othersTextWrap" class="md:col-span-2" style="display: none;">
                                            <label class="block text-sm font-medium">Other's (details)</label>
                                            <input class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" type="text" name="others_text" value="<?= e((string)($checklist['others_text'] ?? '')) ?>" placeholder="Enter details...">
                                        </div>
                                    <?php endif; ?>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>

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

        <div class="mt-6 rounded-xl border bg-white p-4">
            <div class="text-sm font-semibold">Box No(s)</div>
            <div class="mt-3">
                <?php if (!$boxNos): ?>
                    <div class="text-sm text-slate-500">No box numbers set for this task.</div>
                <?php else: ?>
                    <?php
                        $boxGroups = [
                            'Glue Boxes' => [],
                            'Bait Boxes' => [],
                            'E.F.K' => [],
                            'Other' => [],
                        ];
                        foreach ($boxNos as $b) {
                            $bn = trim((string)$b);
                            if ($bn === '') {
                                continue;
                            }
                            if (str_starts_with($bn, 'GLUE')) {
                                $boxGroups['Glue Boxes'][] = $bn;
                            } elseif (str_starts_with($bn, 'BAIT')) {
                                $boxGroups['Bait Boxes'][] = $bn;
                            } elseif (str_starts_with($bn, 'E.F.K')) {
                                $boxGroups['E.F.K'][] = $bn;
                            } else {
                                $boxGroups['Other'][] = $bn;
                            }
                        }
                    ?>

                    <div class="space-y-4">
                        <?php foreach ($boxGroups as $groupTitle => $items): ?>
                            <?php if (!$items) continue; ?>
                            <div>
                                <div class="text-xs font-semibold text-slate-600"><?= e((string)$groupTitle) ?></div>
                                <div class="mt-2 flex flex-wrap gap-2">
                                    <?php foreach ($items as $bn): ?>
                                        <?php if (str_starts_with($bn, 'E.F.K')): ?>
                                            <a
                                                class="inline-flex items-center rounded-full border bg-slate-50 px-3 py-1 text-sm hover:bg-white"
                                                href="<?= e(Constants::APP_ROOT) ?>/staff/upload_images.php?task_id=<?= e((string)$id) ?>&upload_for=efk&efk_no=<?= e((string)((int)preg_replace('/[^0-9]+/', '', $bn))) ?>"
                                            ><?= e((string)$bn) ?></a>
                                        <?php else: ?>
                                            <a
                                                class="inline-flex items-center rounded-full border bg-slate-50 px-3 py-1 text-sm hover:bg-white"
                                                href="<?= e(Constants::APP_ROOT) ?>/staff/upload_images.php?task_id=<?= e((string)$id) ?>&upload_for=box&box_no=<?= e(urlencode((string)$bn)) ?>"
                                            ><?= e((string)$bn) ?></a>
                                        <?php endif; ?>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>

            <div class="mt-5">
                <div class="text-sm font-semibold">Box Types</div>
                <div class="mt-3 grid grid-cols-1 gap-3 md:grid-cols-3 text-sm">
                    <div class="rounded-lg border bg-slate-50 px-3 py-2">
                        <div class="text-xs text-slate-500">Glue Box</div>
                        <div class="font-medium"><?= e((string)($boxTypeCounts['glue_box_count'] ?? 0)) ?></div>
                    </div>
                    <div class="rounded-lg border bg-slate-50 px-3 py-2">
                        <div class="text-xs text-slate-500">Bait Box</div>
                        <div class="font-medium"><?= e((string)($boxTypeCounts['bait_box_count'] ?? 0)) ?></div>
                    </div>
                    <div class="rounded-lg border bg-slate-50 px-3 py-2">
                        <div class="text-xs text-slate-500">E.F.K - Electric Fly Killer</div>
                        <div class="font-medium"><?= e((string)($boxTypeCounts['efk_count'] ?? 0)) ?></div>
                    </div>
                </div>
            </div>

            <form id="uploadImagesForm" class="mt-4 grid grid-cols-1 gap-4 md:grid-cols-2" method="post" action="" enctype="multipart/form-data">
                <input type="hidden" name="upload_images" value="1">
                <input type="hidden" name="lat" id="uplLat" value="">
                <input type="hidden" name="lng" id="uplLng" value="">
                <input type="hidden" name="acc" id="uplAcc" value="">

                <div class="md:col-span-2">
                    <label class="block text-sm font-medium">Upload For</label>
                    <select class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" name="upload_for">
                        <option value="box" <?= ($uploadFor === 'box') ? 'selected' : '' ?>>Box No</option>
                        <option value="efk" <?= ($uploadFor === 'efk') ? 'selected' : '' ?>>E.F.K - Electric Fly Killer</option>
                    </select>
                </div>

                <div class="md:col-span-2">
                    <label class="block text-sm font-medium">Box No</label>
                    <select class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" name="box_no" <?= ($boxNos && $uploadFor === 'box') ? 'required' : '' ?>>
                        <option value=""><?= $boxNos ? 'Select box no' : 'No box numbers set for this task' ?></option>
                        <?php foreach ($boxNos as $b): ?>
                            <option value="<?= e((string)$b) ?>" <?= ($boxNo === (string)$b) ? 'selected' : '' ?>><?= e((string)$b) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="md:col-span-2">
                    <label class="block text-sm font-medium">E.F.K No</label>
                    <?php $efkCountUi = (int)($boxTypeCounts['efk_count'] ?? 0); ?>
                    <select class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" name="efk_no" <?= ($efkCountUi > 0 && $uploadFor === 'efk') ? 'required' : '' ?>>
                        <option value=""><?= ($efkCountUi > 0) ? 'Select E.F.K no' : 'No E.F.K set for this task' ?></option>
                        <?php for ($i = 1; $i <= $efkCountUi; $i++): ?>
                            <option value="<?= e((string)$i) ?>" <?= ($efkNo === $i) ? 'selected' : '' ?>><?= e((string)$i) ?></option>
                        <?php endfor; ?>
                    </select>
                </div>

                <div class="md:col-span-2">
                    <input class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" type="file" name="images[]" accept="image/*" multiple required>
                    <div class="mt-1 text-xs text-slate-500">Allowed: JPG, PNG, WEBP, GIF. Max 5MB each.</div>
                </div>

                <div class="md:col-span-2">
                    <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">Upload Images</button>
                </div>
            </form>
        </div>

        <div class="mt-6 rounded-xl border bg-white p-4">
            <div class="text-sm font-semibold">Images (by Box No)</div>
            <div class="mt-3 space-y-4">
                <?php if (!$imagesByBox): ?>
                    <div class="text-sm text-slate-500">No images uploaded for this task.</div>
                <?php else: ?>
                    <?php foreach ($imagesByBox as $boxLabel => $paths): ?>
                        <?php if (!$paths) continue; ?>
                        <div>
                            <div class="text-xs font-medium text-slate-600"><?= e((string)$boxLabel) ?></div>
                            <div class="mt-2 grid grid-cols-2 gap-3 md:grid-cols-4">
                                <?php foreach ($paths as $p): ?>
                                    <?php $pub = $toPublic((string)$p); ?>
                                    <a class="block overflow-hidden rounded-lg border bg-white" href="<?= e((string)$pub) ?>" target="_blank" rel="noopener">
                                        <img class="h-32 w-full object-cover" src="<?= e((string)$pub) ?>" alt="Task image">
                                    </a>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
    <?php endif; ?>
</div>
<script>
    (function () {
        var wrap = document.getElementById('othersTextWrap');
        var cb = document.querySelector('input[data-others="1"]');
        function sync() {
            if (!wrap || !cb) return;
            wrap.style.display = cb.checked ? '' : 'none';
        }
        cb && cb.addEventListener('change', sync);
        sync();
    })();

    (function () {
        var form = document.getElementById('uploadImagesForm');
        var latEl = document.getElementById('uplLat');
        var lngEl = document.getElementById('uplLng');
        var accEl = document.getElementById('uplAcc');
        if (!form || !latEl || !lngEl) return;

        var submitting = false;

        form.addEventListener('submit', function (e) {
            if (submitting) return;
            if (!navigator.geolocation) return;

            e.preventDefault();
            navigator.geolocation.getCurrentPosition(function (pos) {
                try {
                    latEl.value = String(pos.coords.latitude);
                    lngEl.value = String(pos.coords.longitude);
                    if (accEl) accEl.value = String(pos.coords.accuracy);
                } catch (err) {}
                submitting = true;
                form.submit();
            }, function () {
                submitting = true;
                form.submit();
            }, {
                enableHighAccuracy: true,
                timeout: 10000,
                maximumAge: 0
            });
        });
    })();

    (function () {
        var modal = document.getElementById('checkUploadModal');
        var keyEl = document.getElementById('checkModalKey');
        var titleEl = document.getElementById('checkModalTitle');
        var selectedEl = document.getElementById('checkModalSelected');
        if (!modal || !keyEl || !titleEl || !selectedEl) return;

        function closeModal() {
            modal.classList.add('hidden');
        }

        function openModal(key, label) {
            keyEl.value = String(key || '');
            titleEl.textContent = 'Upload images';
            selectedEl.textContent = String(label || '');
            modal.classList.remove('hidden');
        }

        document.addEventListener('click', function (e) {
            var t = e.target;
            if (!t || !t.closest) return;
            if (t.closest('[data-close-check-modal="1"]')) {
                closeModal();
            }
        });

        document.addEventListener('keydown', function (e) {
            if (e.key === 'Escape') closeModal();
        });

        var checks = document.querySelectorAll('input[type="checkbox"][data-check-key]');
        if (!checks || !checks.length) return;

        checks.forEach(function (cb) {
            cb.addEventListener('change', function () {
                if (!cb.checked) return;
                var key = cb.getAttribute('data-check-key') || '';
                if (!key) return;
                var label = '';
                var lbl = cb.closest('label');
                if (lbl) {
                    var spans = lbl.getElementsByTagName('span');
                    if (spans && spans.length) {
                        label = spans[0].textContent || '';
                    }
                }
                openModal(key, label);
            });
        });
    })();
</script>
<?php
$content = ob_get_clean();

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