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

$id = (int)($_GET['id'] ?? 0);
$row = null;
$checklist = null;
$boxNos = [];
$imagesByBox = [];
$imagesByEfk = [];
$imagesByCheck = [];
$boxTypeCounts = ['glue_box_count' => 0, 'bait_box_count' => 0, 'efk_count' => 0];
$error = '';

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

$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",
];

if ($id > 0) {
    try {
        $pdo = Database::pdo();
        $stmt = $pdo->prepare(
            "SELECT a.*
             FROM admin_all_tasks a
             WHERE a.task_id = :id
             LIMIT 1"
        );
        $stmt->execute(['id' => $id]);
        $row = $stmt->fetch();

        if (!$row) {
            $error = 'Task not found.';
        } else {
            $checklist = TaskChecklistService::get($pdo, $id);
            $boxNos = TaskBoxService::getBoxNos($pdo, $id);
            $boxTypeCounts = TaskBoxTypeService::getCounts($pdo, $id);

            $uploadsRoot = realpath(__DIR__ . '/../') ?: (__DIR__ . '/../');
            $relBase = 'uploads/tasks/' . $id;
            $absBase = $uploadsRoot . '/' . $relBase;
            if (is_dir($absBase)) {
                $list = scandir($absBase);
                if (is_array($list)) {
                    $allowedExt = ['jpg', 'jpeg', 'png', 'webp', 'gif'];
                    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)) {
                                    $ext = strtolower(pathinfo($sf, PATHINFO_EXTENSION));
                                    if ($ext === '' || !in_array($ext, $allowedExt, true)) {
                                        continue;
                                    }
                                    $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)) {
                                    $ext = strtolower(pathinfo($sf, PATHINFO_EXTENSION));
                                    if ($ext === '' || !in_array($ext, $allowedExt, true)) {
                                        continue;
                                    }
                                    $imagesByEfk[$efkLabel][] = '/' . $relBase . '/' . $f . '/' . $sf;
                                }
                            }
                        }

                        if (is_dir($p) && strpos($f, 'check_') === 0) {
                            $checkKey = 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)) {
                                    $ext = strtolower(pathinfo($sf, PATHINFO_EXTENSION));
                                    if ($ext === '' || !in_array($ext, $allowedExt, true)) {
                                        continue;
                                    }
                                    $imagesByCheck[$checkKey][] = '/' . $relBase . '/' . $f . '/' . $sf;
                                }
                            }
                        }
                    }
                }
            }
        }
    } 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; ?>

<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">Read-only task view.</p>
        </div>
        <div class="flex gap-2">
            <?php if ($id > 0): ?>
                <a class="rounded-lg border px-4 py-2 text-sm hover:bg-slate-50" href="<?= e(Constants::APP_ROOT) ?>/admin/task_edit.php?id=<?= e((string)$id) ?>">Edit</a>
            <?php endif; ?>
            <a class="rounded-lg border px-4 py-2 text-sm hover:bg-slate-50" href="<?= e(Constants::APP_ROOT) ?>/admin/task_assignment.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 to view details.
        </div>
    <?php elseif ($row): ?>
        <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>
                    <?php if (isset($row['payment_status'])): ?>
                        <div class="mt-1"><span class="text-slate-500">Payment:</span> <span class="font-medium"><?= e((string)($row['payment_status'] ?? '')) ?></span></div>
                    <?php endif; ?>
                </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">Staff:</span> <span class="font-medium"><?= e((string)($row['staff_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']) && $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-sm font-semibold">Additional Checklist</div>
            <div class="mt-3 grid grid-cols-1 gap-2 md:grid-cols-2">
                <?php foreach ($checkFields as $k => $label): ?>
                    <?php $isChecked = $checklist ? !empty($checklist[$k]) : false; ?>
                    <div class="flex items-center justify-between rounded-lg border bg-slate-50 px-3 py-2 text-sm">
                        <div><?= e($label) ?></div>
                        <div class="font-medium <?= $isChecked ? 'text-green-700' : 'text-slate-500' ?>"><?= $isChecked ? 'Yes' : 'No' ?></div>
                    </div>

                    <?php if (!empty($imagesByCheck[$k])): ?>
                        <div class="-mt-1 rounded-lg border bg-white p-3">
                            <div class="grid grid-cols-2 gap-3 md:grid-cols-4">
                                <?php foreach ($imagesByCheck[$k] as $p): ?>
                                    <?php $pub = $toPublic((string)$p); ?>
                                    <a class="block overflow-hidden rounded-lg border bg-slate-50" 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 endforeach; ?>
            </div>

            <?php
                $othersText = $checklist ? trim((string)($checklist['others_text'] ?? '')) : '';
                $othersChecked = $checklist ? !empty($checklist['others_checked']) : false;
            ?>
            <?php if ($othersChecked && $othersText !== ''): ?>
                <div class="mt-3 rounded-lg border bg-white px-3 py-2 text-sm">
                    <div class="text-xs font-medium text-slate-600">Other's (details)</div>
                    <div class="mt-1 text-slate-800"><?= e($othersText) ?></div>
                </div>
            <?php endif; ?>
        </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-medium text-slate-600"><?= e((string)$groupTitle) ?></div>
                                <div class="mt-2 flex flex-wrap gap-2">
                                    <?php foreach ($items as $bn): ?>
                                        <?php
                                            $safeBoxDir = preg_replace('/[^a-zA-Z0-9_-]+/', '_', (string)$bn) ?: '';
                                            $hasBoxImages = ($safeBoxDir !== '') && !empty($imagesByBox[$safeBoxDir]);
                                        ?>
                                        <button
                                            type="button"
                                            class="js-box-pill inline-flex items-center rounded-full border px-3 py-1 text-sm transition hover:bg-white <?= $hasBoxImages ? 'border-green-200 bg-green-50 text-green-800' : 'border-slate-200 bg-slate-50 text-slate-800' ?>"
                                            data-box="<?= e((string)$bn) ?>"
                                            data-box-safe="<?= e((string)$safeBoxDir) ?>"
                                            <?= $hasBoxImages ? '' : 'disabled' ?>
                                            title="<?= $hasBoxImages ? 'View uploaded images' : 'No images uploaded' ?>"
                                        ><?= e((string)$bn) ?></button>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <div id="boxImgModal" class="fixed inset-0 z-50 hidden">
            <div id="boxImgModalOverlay" class="absolute inset-0 bg-slate-900/70"></div>
            <div class="relative mx-auto flex h-full max-w-5xl items-center justify-center p-4">
                <div class="w-full overflow-hidden rounded-2xl bg-white shadow-xl">
                    <div class="flex items-start justify-between gap-4 border-b p-4">
                        <div>
                            <div id="boxImgModalTitle" class="text-sm font-semibold text-slate-900">Box Images</div>
                            <div id="boxImgModalSubtitle" class="mt-0.5 text-xs text-slate-500"></div>
                        </div>
                        <button id="boxImgModalClose" class="rounded-lg border px-3 py-2 text-sm hover:bg-slate-50" type="button">Close</button>
                    </div>
                    <div class="grid grid-cols-1 gap-4 p-4 lg:grid-cols-[minmax(0,1fr)_320px]">
                        <div class="overflow-hidden rounded-xl border bg-slate-50">
                            <img id="boxImgModalImg" class="h-[60vh] w-full object-contain bg-white" src="" alt="Preview">
                        </div>
                        <div class="rounded-xl border bg-white p-4">
                            <div class="text-xs font-medium text-slate-500">Details</div>
                            <div class="mt-2 text-sm text-slate-800">
                                <div><span class="text-slate-500">Task ID:</span> <span class="font-medium">#<?= e((string)$id) ?></span></div>
                                <div class="mt-1"><span class="text-slate-500">Box No:</span> <span id="boxImgModalBox" class="font-medium">-</span></div>
                                <div class="mt-1"><span class="text-slate-500">Images:</span> <span id="boxImgModalCount" class="font-medium">0</span></div>
                                <div class="mt-1"><span class="text-slate-500">Link:</span> <a id="boxImgModalLink" class="font-medium text-blue-700 hover:underline" href="#" target="_blank" rel="noopener">Open Original</a></div>
                            </div>

                            <div id="boxImgModalThumbWrap" class="mt-4 hidden">
                                <div class="text-xs font-medium text-slate-500">More images</div>
                                <div id="boxImgModalThumbs" class="mt-2 grid grid-cols-4 gap-2"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="mt-6 rounded-xl border bg-white p-4">
            <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>

        <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="Box image">
                                    </a>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>

        <script>
            (function () {
                var boxImages = <?php
                    $boxImagesPublic = [];
                    foreach (($imagesByBox ?? []) as $k => $paths) {
                        $kk = (string)$k;
                        if ($kk === '' || $kk === 'Unassigned') {
                            continue;
                        }
                        $boxImagesPublic[$kk] = array_values(array_filter(array_map($toPublic, array_map('strval', (array)$paths))));
                    }
                    echo json_encode($boxImagesPublic, JSON_UNESCAPED_SLASHES);
                ?>;

                var modal = document.getElementById('boxImgModal');
                var overlay = document.getElementById('boxImgModalOverlay');
                var btnClose = document.getElementById('boxImgModalClose');
                var img = document.getElementById('boxImgModalImg');
                var subtitle = document.getElementById('boxImgModalSubtitle');
                var boxEl = document.getElementById('boxImgModalBox');
                var countEl = document.getElementById('boxImgModalCount');
                var linkEl = document.getElementById('boxImgModalLink');
                var thumbWrap = document.getElementById('boxImgModalThumbWrap');
                var thumbs = document.getElementById('boxImgModalThumbs');

                function setThumbs(images, activeSrc) {
                    if (!thumbWrap || !thumbs) return;
                    thumbs.innerHTML = '';
                    if (!images || images.length <= 1) {
                        thumbWrap.classList.add('hidden');
                        return;
                    }
                    thumbWrap.classList.remove('hidden');
                    images.forEach(function (u) {
                        var a = document.createElement('a');
                        a.href = u;
                        a.className = 'block overflow-hidden rounded-lg border ' + (u === activeSrc ? 'border-blue-300 ring-2 ring-blue-200' : 'border-slate-200');
                        a.addEventListener('click', function (ev) {
                            ev.preventDefault();
                            openModal(u, boxEl ? boxEl.textContent : '-', images);
                        });

                        var im = document.createElement('img');
                        im.src = u;
                        im.alt = 'Thumbnail';
                        im.className = 'h-16 w-full object-cover';
                        a.appendChild(im);
                        thumbs.appendChild(a);
                    });
                }

                function openModal(src, boxNo, images) {
                    if (!modal || !img) return;
                    img.src = src;
                    if (subtitle) subtitle.textContent = boxNo ? ('Box ' + boxNo) : '';
                    if (boxEl) boxEl.textContent = boxNo || '-';
                    if (countEl) countEl.textContent = (images && images.length) ? String(images.length) : '0';
                    if (linkEl) linkEl.href = src;
                    setThumbs(images || [], src);
                    modal.classList.remove('hidden');
                    document.body.style.overflow = 'hidden';
                }

                function closeModal() {
                    if (!modal) return;
                    modal.classList.add('hidden');
                    if (img) img.src = '';
                    document.body.style.overflow = '';
                }

                document.addEventListener('click', function (e) {
                    var btn = e.target && e.target.closest ? e.target.closest('button.js-box-pill') : null;
                    if (!btn) return;
                    e.preventDefault();
                    var boxNo = btn.getAttribute('data-box') || '';
                    var safe = btn.getAttribute('data-box-safe') || '';
                    var imgs = (boxImages && boxImages[safe]) ? boxImages[safe] : [];
                    if (!imgs || !imgs.length) return;
                    openModal(imgs[0], boxNo, imgs);
                });

                overlay && overlay.addEventListener('click', closeModal);
                btnClose && btnClose.addEventListener('click', closeModal);

                window.addEventListener('keydown', function (e) {
                    if (e.key === 'Escape') closeModal();
                });
            })();
        </script>
    <?php endif; ?>
</div>
<?php
$content = ob_get_clean();

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