<?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 = 'Upload Images';

$staffId = (int)($user['user_id'] ?? 0);
$tasks = [];
$error = '';
$success = '';

$taskId = (int)($_GET['task_id'] ?? ($_POST['task_id'] ?? 0));
$boxNo = trim((string)($_POST['box_no'] ?? ($_GET['box_no'] ?? '')));
$uploadFor = trim((string)($_POST['upload_for'] ?? ($_GET['upload_for'] ?? 'box')));
$efkNo = (int)($_POST['efk_no'] ?? ($_GET['efk_no'] ?? 0));
$latRaw = (string)($_POST['lat'] ?? '');
$lngRaw = (string)($_POST['lng'] ?? '');
$accRaw = (string)($_POST['acc'] ?? '');
$taskBoxNos = [];
$boxTypeCounts = ['glue_box_count' => 0, 'bait_box_count' => 0, 'efk_count' => 0];
$selectedTaskStatus = '';

$autoOpenUploadFor = '';
$autoOpenBoxNo = '';
$autoOpenEfkNo = 0;

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

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

try {
    $pdo = Database::pdo();
    $stmt = $pdo->prepare('CALL GetStaffTasks(:staff_id)');
    $stmt->execute(['staff_id' => $staffId]);
    $tasks = $stmt->fetchAll();
    $stmt->closeCursor();

    if ($taskId > 0) {
        foreach ($tasks as $t) {
            if ((int)($t['task_id'] ?? 0) === $taskId) {
                $selectedTaskStatus = strtolower(trim((string)($t['status'] ?? '')));
                break;
            }
        }
    }

    if ($taskId > 0) {
        try {
            $taskBoxNos = TaskBoxService::getBoxNos($pdo, $taskId);
        } catch (Throwable $e) {
            $taskBoxNos = [];
        }

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

        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            $uploadForGet = trim((string)($_GET['upload_for'] ?? ''));
            $boxNoGet = trim((string)($_GET['box_no'] ?? ''));
            $efkNoGet = (int)($_GET['efk_no'] ?? 0);

            if ($uploadForGet === 'box') {
                $boxNoGet = urldecode($boxNoGet);
                if ($boxNoGet !== '' && (!$taskBoxNos || in_array($boxNoGet, $taskBoxNos, true))) {
                    $autoOpenUploadFor = 'box';
                    $autoOpenBoxNo = $boxNoGet;
                    $boxNo = $boxNoGet;
                    $uploadFor = 'box';
                    $efkNo = 0;
                }
            }
            if ($uploadForGet === 'efk') {
                $efkCount = (int)($boxTypeCounts['efk_count'] ?? 0);
                if ($efkCount > 0 && $efkNoGet > 0 && $efkNoGet <= $efkCount) {
                    $autoOpenUploadFor = 'efk';
                    $autoOpenEfkNo = $efkNoGet;
                    $uploadFor = 'efk';
                    $boxNo = '';
                    $efkNo = $efkNoGet;
                }
            }
        }
    }
} catch (Throwable $e) {
    $error = $e->getMessage();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $error === '' && $taskId > 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' => $taskId]);
        $t = $stmtOwn->fetch(PDO::FETCH_ASSOC);
        $assignedStaff = (int)($t['assigned_staff_id'] ?? 0);
        $currentStatus = strtolower(trim((string)($t['status'] ?? '')));

        if ($assignedStaff !== $staffId) {
            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' => $taskId]);
        }

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($taskId <= 0) {
        $error = 'Please select a task.';
    } elseif ($uploadFor !== 'box' && $uploadFor !== 'efk') {
        $error = 'Invalid upload selection.';
    } elseif ($uploadFor === 'box' && $boxNo === '' && $taskBoxNos) {
        $error = 'Please select a Box No.';
    } elseif ($uploadFor === 'box' && $boxNo !== '' && $taskBoxNos && !in_array($boxNo, $taskBoxNos, true)) {
        $error = 'Invalid Box No selection.';
    } elseif ($uploadFor === 'efk' && (int)($boxTypeCounts['efk_count'] ?? 0) <= 0) {
        $error = 'No E.F.K items set for this task.';
    } elseif ($uploadFor === 'efk' && ($efkNo <= 0 || $efkNo > (int)($boxTypeCounts['efk_count'] ?? 0))) {
        $error = 'Please select a valid E.F.K number.';
    } elseif (!isset($_FILES['images'])) {
        $error = 'Please select images to upload.';
    } else {
        $isOwnTask = false;
        foreach ($tasks as $t) {
            if ((int)($t['task_id'] ?? 0) === $taskId) {
                $isOwnTask = true;
                break;
            }
        }

        if (!$isOwnTask) {
            $error = 'Invalid task selection.';
        } else {
            $uploadsRoot = realpath(__DIR__ . '/../') ?: (__DIR__ . '/../');
            $relDir = 'uploads/tasks/' . $taskId;

            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)) {
                    $error = 'Failed to create upload directory.';
                }
            }

            if ($error === '') {
                $allowedMimes = [
                    'image/jpeg' => 'jpg',
                    'image/png' => 'png',
                    'image/webp' => 'webp',
                    'image/gif' => 'gif',
                ];

                $maxBytes = 5 * 1024 * 1024;
                $files = normalize_files_array($_FILES['images']);
                $saved = 0;

                $pdo = Database::pdo();
                $hasTaskImagesTable = table_exists($pdo, 'task_images');
                $cols = $hasTaskImagesTable ? table_columns($pdo, 'task_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) {
                        $error = 'One of the files failed to upload.';
                        break;
                    }
                    if ((int)$f['size'] <= 0 || (int)$f['size'] > $maxBytes) {
                        $error = 'Each image must be less than 5MB.';
                        break;
                    }

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

                    $ext = $allowedMimes[$mime];
                    $safeName = bin2hex(random_bytes(16)) . '.' . $ext;
                    $absPath = $absDir . '/' . $safeName;
                    $relPath = '/' . $relDir . '/' . $safeName;

                    if (!move_uploaded_file((string)$f['tmp_name'], $absPath)) {
                        $error = 'Failed to save uploaded file.';
                        break;
                    }

                    $saved++;

                    if ($hasTaskImagesTable && $cols) {
                        try {
                            $data = [];
                            if (in_array('task_id', $cols, true)) {
                                $data['task_id'] = $taskId;
                            }
                            if (in_array('uploaded_by', $cols, true)) {
                                $data['uploaded_by'] = $staffId;
                            } elseif (in_array('staff_id', $cols, true)) {
                                $data['staff_id'] = $staffId;
                            }
                            if (in_array('image_path', $cols, true)) {
                                $data['image_path'] = $relPath;
                            } elseif (in_array('file_path', $cols, true)) {
                                $data['file_path'] = $relPath;
                            } elseif (in_array('path', $cols, true)) {
                                $data['path'] = $relPath;
                            }
                            if (in_array('uploaded_at', $cols, true)) {
                                $data['uploaded_at'] = date('Y-m-d H:i:s');
                            }

                            if ($data) {
                                $colNames = array_keys($data);
                                $placeholders = [];
                                foreach ($colNames as $c) {
                                    $placeholders[] = ':' . $c;
                                }
                                $sql = 'INSERT INTO task_images (' . implode(',', $colNames) . ') VALUES (' . implode(',', $placeholders) . ')';
                                $stmtIns = $pdo->prepare($sql);
                                $stmtIns->execute($data);
                            }
                        } catch (Throwable $e) {
                            // Ignore DB insert errors; file is already saved.
                        }
                    }
                }

                if ($error === '') {
                    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 {
                                $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.
                            }
                        }
                    }
                    $success = $saved > 0 ? ($saved . ' image(s) uploaded successfully.') : 'No files uploaded.';
                    header('Location: ' . Constants::APP_ROOT . '/staff/upload_images.php?task_id=' . $taskId);
                    exit;
                }
            }
        }
    }
}

$uploadedFiles = [];
$uploadedByBox = [];
$uploadedByEfk = [];
$boxHasUploads = [];
$efkHasUploads = [];
if ($taskId > 0) {
    $uploadsRoot = realpath(__DIR__ . '/../') ?: (__DIR__ . '/../');
    $relDir = 'uploads/tasks/' . $taskId;
    $absDir = $uploadsRoot . '/' . $relDir;
    if (is_dir($absDir)) {
        $list = scandir($absDir);
        if (is_array($list)) {
            foreach ($list as $f) {
                if ($f === '.' || $f === '..') {
                    continue;
                }
                $p = $absDir . '/' . $f;
                if (is_file($p)) {
                    $relPath = '/' . $relDir . '/' . $f;
                    $uploadedFiles[] = $relPath;
                    $uploadedByBox['Unassigned'][] = $relPath;
                    continue;
                }
                if (is_dir($p)) {
                    $sub = scandir($p);
                    if (!is_array($sub)) {
                        continue;
                    }
                    $isBox = (strpos($f, 'box_') === 0);
                    $isEfk = (strpos($f, 'efk_') === 0);
                    $label = '';
                    if ($isBox) {
                        $label = substr($f, 4);
                    } elseif ($isEfk) {
                        $label = substr($f, 4);
                    }
                    foreach ($sub as $sf) {
                        if ($sf === '.' || $sf === '..') {
                            continue;
                        }
                        $sp = $p . '/' . $sf;
                        if (is_file($sp)) {
                            $relPath = '/' . $relDir . '/' . $f . '/' . $sf;
                            $uploadedFiles[] = $relPath;
                            if ($isBox) {
                                $uploadedByBox[$label][] = $relPath;
                                $boxHasUploads[$label] = true;
                            }
                            if ($isEfk) {
                                $uploadedByEfk[$label][] = $relPath;
                                $efkHasUploads[$label] = true;
                            }
                        }
                    }
                }
            }
            rsort($uploadedFiles);
            foreach ($uploadedByBox as $k => $v) {
                if (is_array($v)) {
                    rsort($uploadedByBox[$k]);
                }
            }
            foreach ($uploadedByEfk as $k => $v) {
                if (is_array($v)) {
                    rsort($uploadedByEfk[$k]);
                }
            }
        }
    }
}

$nav = [
    ['label' => 'Overview', 'href' => Constants::APP_ROOT . '/staff/overview.php', 'active' => false],
    ['label' => 'My Tasks', 'href' => Constants::APP_ROOT . '/staff/index.php', 'active' => false],
    ['label' => 'Upload Images', 'href' => Constants::APP_ROOT . '/staff/upload_images.php', 'active' => true],
    ['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; ?>

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

<div id="autoOpenConfig"
     data-upload-for="<?= e($autoOpenUploadFor) ?>"
     data-box-no="<?= e($autoOpenBoxNo) ?>"
     data-efk-no="<?= e((string)$autoOpenEfkNo) ?>"
     class="hidden"></div>

<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">Upload Task Images</h1>
            <p class="mt-1 text-sm text-slate-600">Upload images for your assigned tasks.</p>
        </div>
    </div>

    <style>
        .btn-3d {
            background: linear-gradient(180deg, #ffffff 0%, #f1f5f9 100%);
            border: 1px solid rgba(15, 23, 42, 0.14);
            border-bottom-color: rgba(15, 23, 42, 0.28);
            box-shadow: 0 2px 0 rgba(15, 23, 42, 0.12), 0 10px 18px rgba(15, 23, 42, 0.08);
            transition: transform 0.08s ease, box-shadow 0.08s ease;
        }
        .btn-3d.has-upload {
            background: linear-gradient(180deg, #ecfdf5 0%, #d1fae5 100%);
            border-color: rgba(16, 185, 129, 0.45);
            border-bottom-color: rgba(16, 185, 129, 0.65);
            box-shadow: 0 2px 0 rgba(16, 185, 129, 0.22), 0 10px 18px rgba(15, 23, 42, 0.08);
        }
        .btn-3d:active {
            transform: translateY(1px);
            box-shadow: 0 1px 0 rgba(15, 23, 42, 0.10), 0 8px 14px rgba(15, 23, 42, 0.06);
        }
        .modal-backdrop {
            background: rgba(15, 23, 42, 0.55);
        }
    </style>

    <form class="mt-6 grid grid-cols-1 gap-4 md:grid-cols-2" method="get" action="">
        <div class="md:col-span-2">
            <label class="block text-sm font-medium">Select Task</label>
            <select class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" name="task_id" id="taskSelect" required>
                <option value="">Choose a task</option>
                <?php foreach ($tasks as $t): ?>
                    <option value="<?= e((string)$t['task_id']) ?>" <?= ((int)$taskId === (int)$t['task_id']) ? 'selected' : '' ?>>
                        #<?= e((string)$t['task_id']) ?> - <?= e((string)$t['customer_name']) ?> - <?= e((string)$t['service_name']) ?> (<?= e((string)$t['status']) ?>)
                    </option>
                <?php endforeach; ?>
            </select>
            <div class="mt-1 text-xs text-slate-500">After selecting a task, the boxes for that task will appear as buttons.</div>
        </div>
    </form>

    <div class="mt-6 grid grid-cols-1 gap-5">
        <div class="rounded-xl border bg-slate-50 p-4">
            <div class="flex items-center justify-between gap-3">
                <div class="text-sm font-semibold">Box No</div>
                <div class="text-xs text-slate-500">Tap a box to upload images</div>
            </div>
            <div class="mt-3">
                <?php
                    $taskBoxNosUi = [];
                    foreach ($taskBoxNos as $bn) {
                        $bnStr = (string)$bn;
                        if ($bnStr === '') {
                            continue;
                        }
                        if (str_starts_with($bnStr, 'E.F.K')) {
                            continue;
                        }
                        $taskBoxNosUi[] = $bnStr;
                    }

                    $boxGroupsUi = [
                        'Glue Boxes' => [],
                        'Bait Boxes' => [],
                        'Other' => [],
                    ];
                    foreach ($taskBoxNosUi as $bnu) {
                        if (str_starts_with($bnu, 'GLUE')) {
                            $boxGroupsUi['Glue Boxes'][] = $bnu;
                        } elseif (str_starts_with($bnu, 'BAIT')) {
                            $boxGroupsUi['Bait Boxes'][] = $bnu;
                        } else {
                            $boxGroupsUi['Other'][] = $bnu;
                        }
                    }
                ?>
                <?php if ($taskId <= 0): ?>
                    <div class="text-sm text-slate-500">Select a task first.</div>
                <?php elseif (!$taskBoxNosUi): ?>
                    <div class="text-sm text-slate-500">No box numbers set for this task.</div>
                <?php else: ?>
                    <div class="space-y-4">
                        <?php foreach ($boxGroupsUi as $gt => $items): ?>
                            <?php if (!$items) continue; ?>
                            <div>
                                <div class="text-xs font-semibold text-slate-600"><?= e((string)$gt) ?></div>
                                <div class="mt-2 grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4">
                                    <?php foreach ($items as $b): ?>
                                        <a
                                            href="#"
                                            class="btn-3d block rounded-xl px-4 py-3 text-left <?= !empty($boxHasUploads[(string)$b]) ? 'has-upload' : '' ?>"
                                            data-open-uploader="1"
                                            data-upload-for="box"
                                            data-box-no="<?= e((string)$b) ?>"
                                        >
                                            <div class="text-sm font-semibold text-slate-900"><?= e((string)$b) ?></div>
                                            <div class="mt-1 text-xs text-slate-500">Upload images</div>
                                        </a>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <div class="rounded-xl border bg-slate-50 p-4">
            <div class="flex items-center justify-between gap-3">
                <div class="text-sm font-semibold">E.F.K - Electric Fly Killer</div>
                <div class="text-xs text-slate-500">Tap a number to upload images</div>
            </div>
            <div class="mt-3">
                <?php $efkCountUi = (int)($boxTypeCounts['efk_count'] ?? 0); ?>
                <?php if ($taskId <= 0): ?>
                    <div class="text-sm text-slate-500">Select a task first.</div>
                <?php elseif ($efkCountUi <= 0): ?>
                    <div class="text-sm text-slate-500">No E.F.K items set for this task.</div>
                <?php else: ?>
                    <div class="grid grid-cols-3 gap-3 sm:grid-cols-4 md:grid-cols-6">
                        <?php for ($i = 1; $i <= $efkCountUi; $i++): ?>
                            <a
                                href="#"
                                class="btn-3d block rounded-xl px-4 py-3 text-left <?= !empty($efkHasUploads[(string)$i]) ? 'has-upload' : '' ?>"
                                data-open-uploader="1"
                                data-upload-for="efk"
                                data-efk-no="<?= e((string)$i) ?>"
                            >
                                <div class="text-sm font-semibold text-slate-900">E.F.K <?= e((string)$i) ?></div>
                                <div class="mt-1 text-xs text-slate-500">Upload images</div>
                            </a>
                        <?php endfor; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <div id="uploadModal" class="fixed inset-0 z-50 hidden">
        <div class="modal-backdrop absolute inset-0" data-close-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="modalTitle">Upload images</div>
                        <div class="mt-1 text-xs text-slate-500" id="modalSubtitle">Allowed: JPG, PNG, WEBP, GIF. Max 5MB each.</div>
                    </div>
                    <button type="button" class="rounded-lg border px-3 py-1.5 text-sm" data-close-modal="1">Close</button>
                </div>

                <form class="p-5" method="post" action="" enctype="multipart/form-data" id="modalUploadForm">
                    <input type="hidden" name="lat" id="uplLat" value="">
                    <input type="hidden" name="lng" id="uplLng" value="">
                    <input type="hidden" name="acc" id="uplAcc" value="">

                    <input type="hidden" name="task_id" value="<?= e((string)$taskId) ?>">
                    <input type="hidden" name="upload_for" id="modalUploadFor" value="box">
                    <input type="hidden" name="box_no" id="modalBoxNo" value="">
                    <input type="hidden" name="efk_no" id="modalEfkNo" value="0">

                    <div class="rounded-xl border bg-slate-50 p-4 text-sm" id="modalSelectionBox"></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">You can select multiple images at once.</div>
                    </div>

                    <div class="mt-5">
                        <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</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <?php if ($taskId > 0): ?>
        <div class="mt-8">
            <?php
                $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;
                };
            ?>

            <div class="text-sm font-semibold">All Uploaded Images (Grid)</div>
            <div class="mt-3 grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6">
                <?php if (!$uploadedFiles): ?>
                    <div class="col-span-full text-sm text-slate-500">No images uploaded for this task.</div>
                <?php else: ?>
                    <?php foreach ($uploadedFiles as $p): ?>
                        <?php $pub = $toPublic((string)$p); ?>
                        <a class="block overflow-hidden rounded-lg border bg-white" href="<?= e($pub) ?>" target="_blank" rel="noopener">
                            <img class="h-28 w-full object-cover" src="<?= e($pub) ?>" alt="Task image">
                        </a>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>

            <div class="text-sm font-semibold">Uploaded Images (Box No)</div>
            <div class="mt-3 space-y-4">
                <?php if (!$uploadedByBox): ?>
                    <div class="text-sm text-slate-500">No box images uploaded for this task.</div>
                <?php else: ?>
                    <?php foreach ($uploadedByBox as $label => $paths): ?>
                        <?php if (!$paths) continue; ?>
                        <div>
                            <div class="text-xs font-medium text-slate-600"><?= e((string)$label) ?></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($pub) ?>" target="_blank" rel="noopener">
                                        <img class="h-32 w-full object-cover" src="<?= e($pub) ?>" alt="Task image">
                                    </a>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>

            <div class="mt-6 text-sm font-semibold">Uploaded Images (E.F.K)</div>
            <div class="mt-3 space-y-4">
                <?php if (!$uploadedByEfk): ?>
                    <div class="text-sm text-slate-500">No E.F.K images uploaded for this task.</div>
                <?php else: ?>
                    <?php foreach ($uploadedByEfk as $label => $paths): ?>
                        <?php if (!$paths) continue; ?>
                        <div>
                            <div class="text-xs font-medium text-slate-600">E.F.K #<?= e((string)$label) ?></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($pub) ?>" target="_blank" rel="noopener">
                                        <img class="h-32 w-full object-cover" src="<?= e($pub) ?>" alt="EFK image">
                                    </a>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>

            <div class="mt-8">
                <?php if (!in_array(strtolower(trim((string)$selectedTaskStatus)), ['completed', 'cancelled'], true)): ?>
                    <form method="post" action="" onsubmit="return confirm('Mark this task as completed?');">
                        <input type="hidden" name="task_id" value="<?= e((string)$taskId) ?>">
                        <input type="hidden" name="complete_task" value="1">
                        <button class="w-full rounded-xl bg-gradient-to-b from-emerald-600 to-emerald-700 px-4 py-3 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 else: ?>
                    <div class="rounded-xl border bg-slate-50 p-4 text-sm text-slate-700">Task status: <span class="font-semibold"><?= e((string)$selectedTaskStatus) ?></span></div>
                <?php endif; ?>
            </div>
        </div>
    <?php endif; ?>
</div>
<script>
    (function () {
        var taskSelect = document.getElementById('taskSelect');
        if (taskSelect) {
            taskSelect.addEventListener('change', function () {
                var v = String(taskSelect.value || '');
                var url = new URL(window.location.href);
                if (v) {
                    url.searchParams.set('task_id', v);
                } else {
                    url.searchParams.delete('task_id');
                }
                window.location.href = url.toString();
            });
        }

        var form = document.getElementById('modalUploadForm');
        var latEl = document.getElementById('uplLat');
        var lngEl = document.getElementById('uplLng');
        var accEl = document.getElementById('uplAcc');

        var modal = document.getElementById('uploadModal');
        var modalTitle = document.getElementById('modalTitle');
        var modalSelectionBox = document.getElementById('modalSelectionBox');
        var modalUploadFor = document.getElementById('modalUploadFor');
        var modalBoxNo = document.getElementById('modalBoxNo');
        var modalEfkNo = document.getElementById('modalEfkNo');

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

        function openModalForBox(boxNo) {
            if (!modal || !modalUploadFor || !modalBoxNo || !modalEfkNo || !modalTitle || !modalSelectionBox) return;
            modalUploadFor.value = 'box';
            modalBoxNo.value = String(boxNo || '');
            modalEfkNo.value = '0';
            modalTitle.textContent = 'Upload images for ' + String(boxNo || 'Box');
            modalSelectionBox.textContent = 'Box No: ' + String(boxNo || '');
            modal.classList.remove('hidden');
        }

        function openModalForEfk(n) {
            if (!modal || !modalUploadFor || !modalBoxNo || !modalEfkNo || !modalTitle || !modalSelectionBox) return;
            modalUploadFor.value = 'efk';
            modalBoxNo.value = '';
            modalEfkNo.value = String(n || '0');
            modalTitle.textContent = 'Upload images for E.F.K ' + String(n || '');
            modalSelectionBox.textContent = 'E.F.K No: ' + String(n || '');
            modal.classList.remove('hidden');
        }

        var autoCfg = document.getElementById('autoOpenConfig');
        if (autoCfg) {
            var af = autoCfg.getAttribute('data-upload-for') || '';
            var ab = autoCfg.getAttribute('data-box-no') || '';
            var ae = parseInt(autoCfg.getAttribute('data-efk-no') || '0', 10) || 0;
            if (af === 'box' && ab) {
                openModalForBox(ab);
            }
            if (af === 'efk' && ae > 0) {
                openModalForEfk(ae);
            }
        }

        function asElement(node) {
            if (!node) return null;
            if (node.nodeType === 1) return node;
            if (node.nodeType === 3 && node.parentElement) return node.parentElement;
            return null;
        }

        document.addEventListener('click', function (e) {
            var t = asElement(e.target);
            if (!t) return;

            var openBtn = t.closest ? t.closest('[data-open-uploader="1"]') : null;
            if (openBtn) {
                e.preventDefault();
                var uploadFor = openBtn.getAttribute('data-upload-for') || 'box';
                if (uploadFor === 'efk') {
                    var en = openBtn.getAttribute('data-efk-no') || '0';
                    openModalForEfk(parseInt(en, 10) || 0);
                } else {
                    var bn = openBtn.getAttribute('data-box-no') || '';
                    openModalForBox(bn);
                }
                return;
            }

            var closeBtn = t.closest ? t.closest('[data-close-modal="1"]') : null;
            if (closeBtn) {
                closeModal();
            }
        });

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

        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
            });
        });
    })();
</script>
<?php
$content = ob_get_clean();

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