<?php

declare(strict_types=1);

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

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

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

$user = auth_user();
$title = 'Task Details';

$customerId = (int)($user['user_id'] ?? 0);
$id = (int)($_GET['id'] ?? 0);

$row = null;
$checklist = null;
$imagesByBox = [];
$imagesByEfk = [];
$boxNos = [];
$boxTypeCounts = ['glue_box_count' => 0, 'bait_box_count' => 0, 'efk_count' => 0];
$error = '';
$imageUploaders = [];

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

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

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

function load_task_images_grouped_customer(int $taskId): array
{
    $uploadsRoot = realpath(__DIR__ . '/../') ?: (__DIR__ . '/../');
    $relBase = 'uploads/tasks/' . $taskId;
    $absBase = $uploadsRoot . '/' . $relBase;
    $out = [];
    if (!is_dir($absBase)) {
        return $out;
    }
    $allowedExt = ['jpg', 'jpeg', 'png', 'webp', 'gif'];
    $list = scandir($absBase);
    if (!is_array($list)) {
        return $out;
    }
    foreach ($list as $f) {
        if ($f === '.' || $f === '..') {
            continue;
        }
        $p = $absBase . '/' . $f;
        if (is_file($p)) {
            $ext = strtolower(pathinfo($f, PATHINFO_EXTENSION));
            if ($ext !== '' && in_array($ext, $allowedExt, true)) {
                $out['Unassigned'][] = '/' . $relBase . '/' . $f;
            }
            continue;
        }
        if (is_dir($p) && strpos($f, 'box_') === 0) {
            $boxLabel = substr($f, 4);
            $stack = [[$p, '/' . $relBase . '/' . $f]];
            while ($stack) {
                [$curAbs, $curRel] = array_pop($stack);
                $sub = scandir($curAbs);
                if (!is_array($sub)) {
                    continue;
                }
                foreach ($sub as $sf) {
                    if ($sf === '.' || $sf === '..') {
                        continue;
                    }
                    $spAbs = $curAbs . '/' . $sf;
                    $spRel = $curRel . '/' . $sf;
                    if (is_dir($spAbs)) {
                        $stack[] = [$spAbs, $spRel];
                        continue;
                    }
                    if (is_file($spAbs)) {
                        $ext = strtolower(pathinfo($sf, PATHINFO_EXTENSION));
                        if ($ext !== '' && in_array($ext, $allowedExt, true)) {
                            $out[$boxLabel][] = $spRel;
                        }
                    }
                }
            }
        }
    }
    return $out;
}

function load_task_efk_images_grouped_customer(int $taskId): array
{
    $uploadsRoot = realpath(__DIR__ . '/../') ?: (__DIR__ . '/../');
    $relBase = 'uploads/tasks/' . $taskId;
    $absBase = $uploadsRoot . '/' . $relBase;
    $out = [];
    if (!is_dir($absBase)) {
        return $out;
    }
    $allowedExt = ['jpg', 'jpeg', 'png', 'webp', 'gif'];
    $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, 'efk_') === 0) {
            $efkLabel = substr($f, 4);
            $stack = [[$p, '/' . $relBase . '/' . $f]];
            while ($stack) {
                [$curAbs, $curRel] = array_pop($stack);
                $sub = scandir($curAbs);
                if (!is_array($sub)) {
                    continue;
                }
                foreach ($sub as $sf) {
                    if ($sf === '.' || $sf === '..') {
                        continue;
                    }
                    $spAbs = $curAbs . '/' . $sf;
                    $spRel = $curRel . '/' . $sf;
                    if (is_dir($spAbs)) {
                        $stack[] = [$spAbs, $spRel];
                        continue;
                    }
                    if (is_file($spAbs)) {
                        $ext = strtolower(pathinfo($sf, PATHINFO_EXTENSION));
                        if ($ext !== '' && in_array($ext, $allowedExt, true)) {
                            $out[$efkLabel][] = $spRel;
                        }
                    }
                }
            }
        }
    }
    return $out;
}

function load_task_check_images_grouped_customer(int $taskId): array
{
    $uploadsRoot = realpath(__DIR__ . '/../') ?: (__DIR__ . '/../');
    $relBase = 'uploads/tasks/' . $taskId;
    $absBase = $uploadsRoot . '/' . $relBase;
    $out = [];
    if (!is_dir($absBase)) {
        return $out;
    }
    $allowedExt = ['jpg', 'jpeg', 'png', 'webp', 'gif'];
    $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) {
            $label = substr($f, 6);
            $stack = [[$p, '/' . $relBase . '/' . $f]];
            while ($stack) {
                [$curAbs, $curRel] = array_pop($stack);
                $sub = scandir($curAbs);
                if (!is_array($sub)) {
                    continue;
                }
                foreach ($sub as $sf) {
                    if ($sf === '.' || $sf === '..') {
                        continue;
                    }
                    $spAbs = $curAbs . '/' . $sf;
                    $spRel = $curRel . '/' . $sf;
                    if (is_dir($spAbs)) {
                        $stack[] = [$spAbs, $spRel];
                        continue;
                    }
                    if (is_file($spAbs)) {
                        $ext = strtolower(pathinfo($sf, PATHINFO_EXTENSION));
                        if ($ext !== '' && in_array($ext, $allowedExt, true)) {
                            $out[$label][] = $spRel;
                        }
                    }
                }
            }
        }
    }
    return $out;
}

try {
    if ($id <= 0) {
        throw new RuntimeException('Invalid task.');
    }

    $pdo = Database::pdo();
    $stmt = $pdo->prepare(
        "SELECT
            t.task_id,
            t.scheduled_date,
            t.scheduled_time,
            t.status AS task_status,
            s.service_name,
            u.full_name AS staff_name,
            p.payment_status,
            sr.property_address,
            sr.pest_type,
            sr.severity_level,
            sr.preferred_date,
            sr.preferred_time
         FROM tasks t
         JOIN service_requests sr ON t.request_id = sr.request_id
         JOIN services s ON sr.service_id = s.service_id
         LEFT JOIN users u ON t.assigned_staff_id = u.user_id
         LEFT JOIN payments p ON p.request_id = sr.request_id
         WHERE t.task_id = :task_id
           AND sr.customer_id = :customer_id
         LIMIT 1"
    );
    $stmt->execute(['task_id' => $id, 'customer_id' => $customerId]);
    $row = $stmt->fetch();

    if (!$row) {
        $error = 'Task not found.';
    } else {
        $imagesByBox = load_task_images_grouped_customer($id);
        $imagesByEfk = load_task_efk_images_grouped_customer($id);
        $imagesByCheck = load_task_check_images_grouped_customer($id);

        try {
            if (table_exists($pdo, 'task_images')) {
                $stmtUp = $pdo->prepare(
                    "SELECT
                        COALESCE(ti.image_path, ti.file_path, ti.path) AS p,
                        COALESCE(ti.uploaded_by, ti.staff_id) AS uid,
                        u.full_name AS uploader_name
                     FROM task_images ti
                     LEFT JOIN users u ON u.user_id = COALESCE(ti.uploaded_by, ti.staff_id)
                     WHERE ti.task_id = :tid"
                );
                $stmtUp->execute(['tid' => $id]);
                $rowsUp = $stmtUp->fetchAll();
                foreach ($rowsUp as $ur) {
                    $p = trim((string)($ur['p'] ?? ''));
                    if ($p === '') {
                        continue;
                    }
                    $pub = $toPublic($p);
                    $uid = (int)($ur['uid'] ?? 0);
                    $nm = trim((string)($ur['uploader_name'] ?? ''));
                    $imageUploaders[$pub] = [
                        'id' => $uid,
                        'name' => $nm,
                    ];
                }
            }
        } catch (Throwable $e) {
        }

        $allImages = [];
        foreach ($imagesByBox as $grp => $paths) {
            foreach (($paths ?: []) as $p) {
                $allImages[] = (string)$p;
            }
        }
        foreach ($imagesByEfk as $grp => $paths) {
            foreach (($paths ?: []) as $p) {
                $allImages[] = (string)$p;
            }
        }
        foreach ($imagesByCheck as $grp => $paths) {
            foreach (($paths ?: []) as $p) {
                $allImages[] = (string)$p;
            }
        }
        $allImages = array_values(array_unique($allImages));
        rsort($allImages);

        try {
            $boxNos = TaskBoxService::getBoxNos($pdo, $id);
        } catch (Throwable $e) {
            $boxNos = [];
        }

        try {
            $boxTypeCounts = TaskBoxTypeService::getCounts($pdo, $id);
        } catch (Throwable $e) {
            $boxTypeCounts = ['glue_box_count' => 0, 'bait_box_count' => 0, 'efk_count' => 0];
        }

        try {
            $checklist = TaskChecklistService::get($pdo, $id);
        } catch (Throwable $e) {
            $checklist = null;
        }
    }
} catch (Throwable $e) {
    $error = $e->getMessage();
}

$nav = [
    ['label' => 'Overview', 'href' => Constants::APP_ROOT . '/customer/overview.php', 'active' => false],
    ['label' => 'My Requests', 'href' => Constants::APP_ROOT . '/customer/index.php', 'active' => false],
    ['label' => 'Request Service', 'href' => Constants::APP_ROOT . '/customer/request_service.php', 'active' => false],
    ['label' => 'My Services', 'href' => Constants::APP_ROOT . '/customer/my_services.php', 'active' => true],
    ['label' => 'Service Reports', 'href' => Constants::APP_ROOT . '/customer/reports.php', 'active' => false],
    ['label' => 'IPM Map', 'href' => Constants::APP_ROOT . '/customer/ipm_map.php', 'active' => false],
    ['label' => 'Gap Analysis Report', 'href' => Constants::APP_ROOT . '/customer/gap_analysis_report.php', 'active' => false],
    ['label' => 'Trend Analysis Report', 'href' => Constants::APP_ROOT . '/customer/trend_analysis_report.php', 'active' => false],
    ['label' => 'Complaints', 'href' => Constants::APP_ROOT . '/customer/complaints.php', 'active' => false],
    ['label' => 'Payments', 'href' => Constants::APP_ROOT . '/customer/payments.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 your scheduled service.</p>
        </div>
        <a class="rounded-lg border px-4 py-2 text-sm hover:bg-slate-50" href="<?= e(Constants::APP_ROOT) ?>/customer/my_services.php">Back</a>
    </div>

    <?php if ($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>
                </div>
            </div>

            <div class="rounded-xl border bg-slate-50 p-4">
                <div class="text-xs font-medium text-slate-600">Service</div>
                <div class="mt-2 text-sm">
                    <div><span class="text-slate-500">Service:</span> <span class="font-medium"><?= e((string)($row['service_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>
                    <?php if (!empty($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">Checklist Images</div>
            <div class="mt-3 space-y-4">
                <?php if (empty($imagesByCheck)): ?>
                    <div class="text-sm text-slate-500">No checklist images uploaded for this task.</div>
                <?php else: ?>
                    <?php foreach ($imagesByCheck as $checkLabel => $paths): ?>
                        <?php if (!$paths) continue; ?>
                        <div>
                            <div class="text-xs font-medium text-slate-600"><?= e((string)$checkLabel) ?></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="js-img block overflow-hidden rounded-lg border bg-white" href="<?= e((string)$pub) ?>" data-src="<?= e((string)$pub) ?>" data-title="Checklist" data-subtitle="<?= e((string)$checkLabel) ?>">
                                        <img class="h-32 w-full object-cover" src="<?= e((string)$pub) ?>" alt="Checklist 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">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="js-img block overflow-hidden rounded-lg border bg-white" href="<?= e((string)$pub) ?>" data-src="<?= e((string)$pub) ?>" data-title="E.F.K" data-subtitle="#<?= e((string)$efkLabel) ?>">
                                        <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 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-semibold text-slate-600"><?= e((string)$groupTitle) ?></div>
                                <div class="mt-2 flex flex-wrap gap-2">
                                    <?php foreach ($items as $bn): ?>
                                        <?php $hasBoxImages = !empty($imagesByBox[(string)$bn]); ?>
                                        <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) ?>"
                                            <?= $hasBoxImages ? '' : 'disabled' ?>
                                            title="<?= $hasBoxImages ? 'View uploaded images' : 'No images uploaded' ?>"
                                        ><?= e((string)$bn) ?></button>
                                    <?php endforeach; ?>
                                </div>
                                <div class="mt-1 text-xs text-slate-500"><?= e((string)count(array_filter($items, static fn($x) => !empty($imagesByBox[(string)$x])))) ?> with images</div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </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="js-img block overflow-hidden rounded-lg border bg-white" href="<?= e((string)$pub) ?>" data-src="<?= e((string)$pub) ?>" data-title="Box" data-subtitle="<?= e((string)$boxLabel) ?>">
                                        <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>

<div id="imgModal" class="fixed inset-0 z-50 hidden">
    <div id="imgModalOverlay" 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="imgModalTitle" class="text-sm font-semibold text-slate-900">Image</div>
                    <div id="imgModalSubtitle" class="mt-0.5 text-xs text-slate-500"></div>
                </div>
                <button id="imgModalClose" 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="imgModalImg" 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">Type:</span> <span id="imgModalType" class="font-medium">-</span></div>
                        <div class="mt-1"><span class="text-slate-500">Group:</span> <span id="imgModalGroup" class="font-medium">-</span></div>
                        <div class="mt-1"><span class="text-slate-500">Uploaded by:</span> <span id="imgModalUploader" class="font-medium">-</span></div>
                        <div class="mt-1"><span class="text-slate-500">Link:</span> <a id="imgModalLink" class="font-medium text-blue-700 hover:underline" href="#" target="_blank" rel="noopener">Open Original</a></div>
                    </div>

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

<script>
    (function () {
        var imageUploaders = <?php echo json_encode($imageUploaders, JSON_UNESCAPED_SLASHES); ?>;
        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('imgModal');
        var overlay = document.getElementById('imgModalOverlay');
        var btnClose = document.getElementById('imgModalClose');
        var img = document.getElementById('imgModalImg');
        var title = document.getElementById('imgModalTitle');
        var subtitle = document.getElementById('imgModalSubtitle');
        var typeEl = document.getElementById('imgModalType');
        var groupEl = document.getElementById('imgModalGroup');
        var uploaderEl = document.getElementById('imgModalUploader');
        var linkEl = document.getElementById('imgModalLink');
        var thumbWrap = document.getElementById('imgModalThumbWrap');
        var thumbs = document.getElementById('imgModalThumbs');

        function setUploader(src) {
            if (!uploaderEl) return;
            var meta = imageUploaders ? imageUploaders[src] : null;
            if (!meta) {
                uploaderEl.textContent = '-';
                return;
            }
            var label = '';
            if (meta.name && meta.id) {
                label = meta.name + ' (ID: ' + meta.id + ')';
            } else if (meta.name) {
                label = meta.name;
            } else if (meta.id) {
                label = 'ID: ' + meta.id;
            }
            uploaderEl.textContent = label || '-';
        }

        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.dataset.src = u;
                a.addEventListener('click', function (ev) {
                    ev.preventDefault();
                    openModal(u, typeEl ? typeEl.textContent : 'Image', groupEl ? groupEl.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, t, sub, images) {
            if (!modal || !img) return;
            img.src = src;
            if (title) title.textContent = t || 'Image';
            if (subtitle) subtitle.textContent = sub || '';
            if (typeEl) typeEl.textContent = t || '-';
            if (groupEl) groupEl.textContent = sub || '-';
            if (linkEl) linkEl.href = src;
            setUploader(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 = '';
            if (uploaderEl) uploaderEl.textContent = '-';
            document.body.style.overflow = '';
        }

        document.addEventListener('click', function (e) {
            var a = e.target && e.target.closest ? e.target.closest('a.js-img') : null;
            if (!a) return;
            e.preventDefault();
            openModal(a.getAttribute('data-src') || a.href, a.getAttribute('data-title') || 'Image', a.getAttribute('data-subtitle') || '', [a.getAttribute('data-src') || a.href]);
        });

        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 box = btn.getAttribute('data-box') || '';
            var imgs = (boxImages && boxImages[box]) ? boxImages[box] : [];
            if (!imgs || !imgs.length) return;
            openModal(imgs[0], 'Box', box, imgs);
        });

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

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

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