<?php
declare(strict_types=1);
ini_set('display_errors', '0');

require_once __DIR__ . '/../includes/console_shell.php';
require_login();

$pageLink = 'masters/designations.php';
$acl = require_acl('can_view', $pageLink);

$errors = [];
$flash = $_SESSION['flash_designations'] ?? null;
unset($_SESSION['flash_designations']);

$mode = (string)($_GET['mode'] ?? '');
$editId = max(0, (int)($_GET['edit'] ?? 0));
$isFormView = $mode === 'add' || $editId > 0;
$search = trim((string)($_GET['q'] ?? ''));
$editItem = null;

function designation_selected_locations(mysqli $con, int $designationId): array
{
    if ($designationId <= 0) {
        return [];
    }

    $ids = [];
    $stmt = $con->prepare('SELECT orglocation FROM jos_app_designation_locationlog WHERE designationid=? ORDER BY id ASC');
    $stmt->bind_param('i', $designationId);
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $ids[] = (int)$row['orglocation'];
    }
    $stmt->close();
    return $ids;
}

function designation_location_summary(mysqli $con, int $designationId): array
{
    if ($designationId <= 0) {
        return [];
    }

    $items = [];
    $stmt = $con->prepare('SELECT l.orglocation, l.status, o.name FROM jos_app_designation_locationlog l LEFT JOIN jos_app_orglocation o ON o.id=l.orglocation WHERE l.designationid=? ORDER BY l.id ASC');
    $stmt->bind_param('i', $designationId);
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $items[] = $row;
    }
    $stmt->close();
    return $items;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = (string)($_POST['action'] ?? '');

    if (!verify_csrf($_POST['_csrf'] ?? null)) {
        $errors[] = 'Security token expired. Please refresh and try again.';
    } elseif ($action === 'save') {
        $id = max(0, (int)($_POST['id'] ?? 0));
        $designation = trim((string)($_POST['designation'] ?? ''));
        $locationIds = array_values(array_unique(array_filter(array_map('intval', (array)($_POST['orglocation'] ?? [])), fn($value) => $value > 0)));

        if ($id > 0 && empty($acl['can_edit'])) {
            $errors[] = 'You do not have permission to edit designations.';
        }
        if ($id === 0 && empty($acl['can_add'])) {
            $errors[] = 'You do not have permission to add designations.';
        }
        if ($designation === '') {
            $errors[] = 'Designation is required.';
        } elseif (strlen($designation) > 255) {
            $errors[] = 'Designation must be 255 characters or fewer.';
        }

        if (!$errors && $locationIds) {
            $validLocationCount = 0;
            $stmt = $con->prepare('SELECT id FROM jos_app_orglocation WHERE id=? LIMIT 1');
            foreach ($locationIds as $locationId) {
                $stmt->bind_param('i', $locationId);
                $stmt->execute();
                if ($stmt->get_result()->fetch_assoc()) {
                    $validLocationCount++;
                }
            }
            $stmt->close();
            if ($validLocationCount !== count($locationIds)) {
                $errors[] = 'One or more selected locations are invalid.';
            }
        }

        if (!$errors) {
            $con->begin_transaction();
            try {
                if ($id > 0) {
                    $stmt = $con->prepare('UPDATE jos_app_designation SET designation=? WHERE id=?');
                    $stmt->bind_param('si', $designation, $id);
                    $stmt->execute();
                    $stmt->close();
                    $designationId = $id;
                    audit_log('designation.update', 'jos_app_designation', (string)$designationId, $designation);
                } else {
                    $stmt = $con->prepare('INSERT INTO jos_app_designation (designation) VALUES (?)');
                    $stmt->bind_param('s', $designation);
                    $stmt->execute();
                    $designationId = (int)$con->insert_id;
                    $stmt->close();
                    audit_log('designation.create', 'jos_app_designation', (string)$designationId, $designation);
                }

                $stmt = $con->prepare('DELETE FROM jos_app_designation_locationlog WHERE designationid=?');
                $stmt->bind_param('i', $designationId);
                $stmt->execute();
                $stmt->close();

                if ($locationIds) {
                    $locationStatus = 0;
                    $stmt = $con->prepare('INSERT INTO jos_app_designation_locationlog (designationid, orglocation, status) VALUES (?, ?, ?)');
                    foreach ($locationIds as $locationId) {
                        $stmt->bind_param('iii', $designationId, $locationId, $locationStatus);
                        $stmt->execute();
                    }
                    $stmt->close();
                }

                if ($con->query("SHOW TABLES LIKE 'jos_app_editdesignation'")->num_rows > 0) {
                    $userId = (int)(current_user()['id'] ?? 0);
                    $orgLocationCsv = implode(',', $locationIds);
                    $empty = '';
                    $stmt = $con->prepare('INSERT INTO jos_app_editdesignation (designation, designame, modify_by, orglocation, update_status, date, time) VALUES (?, ?, ?, ?, ?, NOW(), NOW())');
                    if ($stmt) {
                        $stmt->bind_param('isiss', $designationId, $designation, $userId, $orgLocationCsv, $empty);
                        $stmt->execute();
                        $stmt->close();
                    }
                }

                $con->commit();
                $_SESSION['flash_designations'] = $id > 0 ? 'Designation updated successfully.' : 'Designation saved successfully.';
                redirect('/masters/designations.php');
            } catch (Throwable $e) {
                $con->rollback();
                $errors[] = 'Unable to save designation. Please try again.';
            }
        }

        $isFormView = true;
        $editId = $id;
    } elseif ($action === 'delete') {
        if (empty($acl['can_delete'])) {
            $errors[] = 'You do not have permission to delete designations.';
        }

        $id = max(0, (int)($_POST['id'] ?? 0));
        if ($id <= 0) {
            $errors[] = 'Invalid designation selected.';
        }

        if (!$errors) {
            $stmt = $con->prepare('SELECT designation FROM jos_app_designation WHERE id=? LIMIT 1');
            $stmt->bind_param('i', $id);
            $stmt->execute();
            $row = $stmt->get_result()->fetch_assoc();
            $stmt->close();
            $designationName = (string)($row['designation'] ?? '');

            $con->begin_transaction();
            try {
                $stmt = $con->prepare('DELETE FROM jos_app_designation_locationlog WHERE designationid=?');
                $stmt->bind_param('i', $id);
                $stmt->execute();
                $stmt->close();

                $stmt = $con->prepare('DELETE FROM jos_app_designation WHERE id=?');
                $stmt->bind_param('i', $id);
                $stmt->execute();
                $stmt->close();

                $con->commit();
                audit_log('designation.delete', 'jos_app_designation', (string)$id, $designationName);
                $_SESSION['flash_designations'] = 'Designation deleted successfully.';
                redirect('/masters/designations.php');
            } catch (Throwable $e) {
                $con->rollback();
                $errors[] = 'Unable to delete designation. Please try again.';
            }
        }
    }
}

if ($editId > 0) {
    $stmt = $con->prepare('SELECT id, designation FROM jos_app_designation WHERE id=? LIMIT 1');
    $stmt->bind_param('i', $editId);
    $stmt->execute();
    $editItem = $stmt->get_result()->fetch_assoc() ?: null;
    $stmt->close();

    if (!$editItem && !$errors) {
        $_SESSION['flash_designations'] = 'Designation record was not found.';
        redirect('/masters/designations.php');
    }
}

$locationOptions = [];
$result = $con->query('SELECT id, name FROM jos_app_orglocation ORDER BY name ASC, id ASC');
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $locationOptions[] = $row;
    }
    $result->free();
}

$designations = [];
if (!$isFormView) {
    if ($search !== '') {
        $like = '%' . $search . '%';
        $stmt = $con->prepare('SELECT id, designation FROM jos_app_designation WHERE designation LIKE ? ORDER BY id ASC');
        $stmt->bind_param('s', $like);
        $stmt->execute();
        $result = $stmt->get_result();
        while ($row = $result->fetch_assoc()) {
            $row['locations'] = designation_location_summary($con, (int)$row['id']);
            $designations[] = $row;
        }
        $stmt->close();
    } else {
        $result = $con->query('SELECT id, designation FROM jos_app_designation ORDER BY id ASC');
        if ($result) {
            while ($row = $result->fetch_assoc()) {
                $row['locations'] = designation_location_summary($con, (int)$row['id']);
                $designations[] = $row;
            }
            $result->free();
        }
    }
}

$formId = (int)($editItem['id'] ?? 0);
$formDesignation = $errors ? trim((string)($_POST['designation'] ?? '')) : (string)($editItem['designation'] ?? '');
$formLocations = $errors ? array_values(array_unique(array_filter(array_map('intval', (array)($_POST['orglocation'] ?? [])), fn($value) => $value > 0))) : designation_selected_locations($con, $formId);
$locationPickerOptions = array_map(static fn(array $location): array => [
    'id' => (int)$location['id'],
    'name' => (string)$location['name'],
], $locationOptions);

console_header('Add Designation', $pageLink);
?>
<div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-6 gap-4">
    <div>
        <div class="flex items-center gap-2 text-[12px] font-semibold text-slate-500 mb-2">
            <a href="/dashboard.php" class="hover:text-brand-600 transition-colors">Dashboard</a>
            <i class="fa-solid fa-chevron-right text-[9px] text-slate-300"></i>
            <span>Masters</span>
            <i class="fa-solid fa-chevron-right text-[9px] text-slate-300"></i>
            <span class="text-brand-600">Add Designation</span>
        </div>
        <h1 class="text-2xl font-bold text-slate-900 tracking-tight">Add Designation</h1>
        <p class="text-sm text-slate-500 mt-1">Manage designation records and their location assignments.</p>
    </div>
    <div class="bg-white border border-slate-100 rounded-xl shadow-sm px-4 py-3 flex items-center gap-3">
        <span class="w-10 h-10 rounded-xl bg-brand-50 text-brand-600 flex items-center justify-center"><i class="fa-solid fa-id-badge"></i></span>
        <div>
            <div class="text-[11px] font-bold text-slate-400 uppercase tracking-widest"><?= $isFormView ? 'Form View' : 'Total Designations' ?></div>
            <div class="text-lg font-bold text-slate-900 leading-tight"><?= $isFormView ? ($formId ? 'Edit' : 'Add') : count($designations) ?></div>
        </div>
    </div>
</div>

<?php if ($flash): ?>
    <div class="mb-6 rounded-xl border border-emerald-100 bg-emerald-50 px-5 py-4 text-emerald-700 shadow-sm flex gap-3">
        <span class="mt-0.5 w-8 h-8 rounded-lg bg-emerald-100 text-emerald-600 flex items-center justify-center shrink-0"><i class="fa-solid fa-check text-sm"></i></span>
        <div><h2 class="text-base font-bold">Message</h2><p class="mt-1 text-sm font-medium"><?= h($flash) ?></p></div>
    </div>
<?php endif; ?>

<?php if ($errors): ?>
    <div class="mb-6 rounded-xl border border-red-100 bg-red-50 px-5 py-4 text-red-700 shadow-sm">
        <h2 class="text-base font-bold">Please fix the following</h2>
        <ul class="mt-2 text-sm font-medium list-disc list-inside"><?php foreach ($errors as $error): ?><li><?= h($error) ?></li><?php endforeach; ?></ul>
    </div>
<?php endif; ?>

<?php if (!$isFormView): ?>
    <section class="bg-white rounded-[1.25rem] shadow-sm border border-slate-100 overflow-hidden">
        <div class="px-6 py-5 border-b border-slate-100 flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4 bg-white">
            <div>
                <h2 class="font-semibold text-slate-800 flex items-center gap-2">
                    <span class="w-9 h-9 rounded-xl bg-brand-50 text-brand-600 flex items-center justify-center"><i class="fa-solid fa-id-badge text-sm"></i></span>
                    Add Designation List
                </h2>
                <p class="text-[12px] font-medium text-slate-400 mt-1 lg:ml-11">Source table: <span class="font-semibold">jos_app_designation</span></p>
            </div>
            <div class="flex flex-col sm:flex-row gap-2">
                <form method="get" class="flex flex-col sm:flex-row gap-2">
                    <div class="relative">
                        <i class="fa-solid fa-magnifying-glass absolute left-3 top-1/2 -translate-y-1/2 text-slate-400 text-xs"></i>
                        <input type="search" name="q" value="<?= h($search) ?>" placeholder="Search designation" class="w-full sm:w-64 rounded-lg border border-slate-200 bg-white py-2.5 pl-9 pr-3 text-sm font-medium outline-none focus:border-brand-500 focus:ring-4 focus:ring-brand-100">
                    </div>
                    <button class="rounded-lg bg-white border border-slate-200 text-slate-700 hover:bg-slate-50 px-4 py-2.5 text-sm font-semibold shadow-sm" type="submit">Search</button>
                    <?php if ($search !== ''): ?><a class="rounded-lg bg-white border border-slate-200 text-slate-700 hover:bg-slate-50 px-4 py-2.5 text-sm font-semibold shadow-sm text-center" href="/masters/designations.php">Clear</a><?php endif; ?>
                </form>
                <?php if (!empty($acl['can_add'])): ?>
                    <a href="/masters/designations.php?mode=add" class="inline-flex items-center justify-center gap-2 rounded-lg bg-brand-600 hover:bg-brand-700 px-4 py-2.5 text-sm font-semibold text-white shadow-sm transition-all">
                        <i class="fa-solid fa-plus text-xs"></i> Add
                    </a>
                <?php endif; ?>
            </div>
        </div>

        <div class="overflow-x-auto">
            <table class="w-full min-w-[860px] text-sm text-left text-slate-600">
                <thead class="bg-slate-50/80 text-[10px] font-extrabold text-slate-800 uppercase tracking-wider">
                    <tr>
                        <th class="border-b border-slate-100 px-6 py-4 w-28">Sr No</th>
                        <th class="border-b border-slate-100 px-6 py-4">Designation</th>
                        <th class="border-b border-slate-100 px-6 py-4">Locations</th>
                        <th class="border-b border-slate-100 px-6 py-4 text-right w-44">Actions</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-slate-100">
                    <?php if (!$designations): ?>
                        <tr><td colspan="4" class="px-6 py-10 text-center text-slate-400 font-semibold">No designations found.</td></tr>
                    <?php endif; ?>
                    <?php foreach ($designations as $index => $designationRow): ?>
                        <tr class="hover:bg-slate-50/80 transition-colors">
                            <td class="px-6 py-5 font-semibold text-slate-500"><?= $index + 1 ?></td>
                            <td class="px-6 py-5"><span class="font-semibold text-slate-900"><?= h($designationRow['designation']) ?></span></td>
                            <td class="px-6 py-5">
                                <?php if (empty($designationRow['locations'])): ?>
                                    <span class="text-slate-400 font-semibold">No locations</span>
                                <?php else: ?>
                                    <div class="flex flex-wrap gap-2">
                                        <?php foreach ($designationRow['locations'] as $location): ?>
                                            <?php $locationActive = (int)($location['status'] ?? 0) === 1; ?>
                                            <span class="inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-[11px] font-bold <?= $locationActive ? 'bg-emerald-50 text-emerald-700 border border-emerald-100' : 'bg-slate-100 text-slate-600 border border-slate-200' ?>">
                                                <span class="w-1.5 h-1.5 rounded-full <?= $locationActive ? 'bg-emerald-500' : 'bg-slate-400' ?>"></span><?= h((string)($location['name'] ?? 'Location #' . (int)$location['orglocation'])) ?>
                                            </span>
                                        <?php endforeach; ?>
                                    </div>
                                <?php endif; ?>
                            </td>
                            <td class="px-6 py-5">
                                <div class="flex items-center justify-end gap-2">
                                    <?php if (!empty($acl['can_edit'])): ?>
                                        <a href="/masters/designations.php?edit=<?= (int)$designationRow['id'] ?>" class="w-9 h-9 rounded-lg border border-slate-200 bg-white text-slate-500 hover:border-brand-200 hover:bg-brand-50 hover:text-brand-600 transition-colors flex items-center justify-center" aria-label="Edit <?= h($designationRow['designation']) ?>"><i class="fa-regular fa-pen-to-square text-base"></i></a>
                                    <?php endif; ?>
                                    <?php if (!empty($acl['can_delete'])): ?>
                                        <form method="post" onsubmit="return confirm('Delete this designation permanently?');">
                                            <input type="hidden" name="_csrf" value="<?= h(csrf_token()) ?>">
                                            <input type="hidden" name="action" value="delete">
                                            <input type="hidden" name="id" value="<?= (int)$designationRow['id'] ?>">
                                            <button type="submit" class="w-9 h-9 rounded-lg border border-slate-200 bg-white text-slate-500 hover:border-red-200 hover:bg-red-50 hover:text-red-600 transition-colors" aria-label="Delete <?= h($designationRow['designation']) ?>"><i class="fa-regular fa-trash-can text-base"></i></button>
                                        </form>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </section>
<?php else: ?>
    <section class="bg-white rounded-[1.25rem] shadow-sm border border-slate-100 overflow-visible">
        <div class="px-6 py-5 border-b border-slate-100 bg-white flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
            <div>
                <h2 class="font-semibold text-slate-800 flex items-center gap-2">
                    <span class="w-9 h-9 rounded-xl bg-brand-50 text-brand-600 flex items-center justify-center"><i class="fa-solid fa-id-badge text-sm"></i></span>
                    <?= $formId ? 'Edit Designation' : 'Add Designation' ?>
                </h2>
                <p class="text-[12px] font-medium text-slate-400 mt-1 sm:ml-11">Designation is required. Locations are optional.</p>
            </div>
            <a href="/masters/designations.php" class="inline-flex justify-center items-center gap-2 rounded-lg border border-slate-200 bg-white px-4 py-2.5 text-sm font-semibold text-slate-700 shadow-sm transition-all hover:bg-slate-50 hover:border-slate-300">
                <i class="fa-solid fa-arrow-left text-xs text-slate-400"></i> Back to List
            </a>
        </div>

        <?php if (($formId && empty($acl['can_edit'])) || (!$formId && empty($acl['can_add']))): ?>
            <div class="p-6 text-sm font-semibold text-amber-700 bg-amber-50 border-t border-amber-100">You can view this page, but you do not have permission to <?= $formId ? 'edit' : 'add' ?> designations.</div>
        <?php else: ?>
            <form method="post" class="p-6 sm:p-8 sm:pb-14">
                <input type="hidden" name="_csrf" value="<?= h(csrf_token()) ?>">
                <input type="hidden" name="action" value="save">
                <input type="hidden" name="id" value="<?= $formId ?>">

                <div class="max-w-5xl grid grid-cols-1 lg:grid-cols-[minmax(0,1fr)_minmax(320px,420px)] gap-5">
                    <div>
                        <label for="designation" class="block text-[12px] font-bold text-slate-700 mb-2 uppercase tracking-wider">Designation <span class="text-amber-500">*</span></label>
                        <input id="designation" name="designation" type="text" value="<?= h($formDesignation) ?>" required maxlength="255" placeholder="Designation" class="block w-full rounded-xl border border-slate-200 bg-white py-3.5 px-4 text-sm font-medium text-slate-900 placeholder:text-slate-400 shadow-sm outline-none transition-all focus:border-brand-500 focus:ring-4 focus:ring-brand-100">
                    </div>
                    <div>
                        <label for="location-search" class="block text-[12px] font-bold text-slate-700 mb-2 uppercase tracking-wider">Location</label>
                        <div
                            class="relative js-location-picker"
                            data-options='<?= h(json_encode($locationPickerOptions, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT)) ?>'
                            data-selected='<?= h(json_encode(array_values(array_map('intval', $formLocations)), JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT)) ?>'
                        >
                            <?php if (empty($locationOptions)): ?>
                                <div class="rounded-xl border border-slate-200 bg-white px-4 py-3 text-sm font-medium text-slate-400 shadow-sm">No locations configured.</div>
                            <?php else: ?>
                                <div class="js-location-control min-h-[48px] flex flex-wrap items-center gap-2 rounded-xl border border-slate-200 bg-white px-3 py-2 shadow-sm transition-all focus-within:border-brand-500 focus-within:ring-4 focus-within:ring-brand-100">
                                    <div class="js-location-tags flex flex-wrap items-center gap-2"></div>
                                    <input id="location-search" type="text" autocomplete="off" placeholder="Type or select location" class="js-location-search min-w-[180px] flex-1 border-0 bg-transparent px-1 py-2 text-sm font-medium text-slate-900 placeholder:text-slate-400 outline-none focus:ring-0">
                                </div>
                                <div class="js-location-dropdown hidden absolute left-0 right-0 top-[calc(100%+4px)] z-30 max-h-56 overflow-y-auto rounded-xl border border-slate-200 bg-white py-1 shadow-xl"></div>
                                <div class="js-location-inputs">
                                    <?php foreach ($formLocations as $locationId): ?>
                                        <input type="hidden" name="orglocation[]" value="<?= (int)$locationId ?>">
                                    <?php endforeach; ?>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>

                <div class="mt-8 flex flex-col-reverse sm:flex-row sm:items-center gap-3">
                    <button type="submit" class="inline-flex justify-center items-center gap-2 rounded-lg bg-brand-900 hover:bg-slate-800 px-6 py-3 text-sm font-semibold text-white shadow-sm transition-all active:scale-[0.98]"><i class="fa-solid fa-check text-xs"></i> Submit</button>
                    <a href="/masters/designations.php" class="inline-flex justify-center items-center gap-2 rounded-lg border border-slate-200 bg-white px-6 py-3 text-sm font-semibold text-slate-700 shadow-sm transition-all hover:bg-slate-50 hover:border-slate-300"><i class="fa-solid fa-xmark text-xs text-slate-400"></i> Cancel</a>
                </div>
            </form>
        <?php endif; ?>
    </section>
<?php endif; ?>
<script>
document.querySelectorAll('.js-location-picker').forEach((picker) => {
    const options = JSON.parse(picker.dataset.options || '[]');
    let selected = JSON.parse(picker.dataset.selected || '[]').map(Number);
    const control = picker.querySelector('.js-location-control');
    const search = picker.querySelector('.js-location-search');
    const tags = picker.querySelector('.js-location-tags');
    const dropdown = picker.querySelector('.js-location-dropdown');
    const inputs = picker.querySelector('.js-location-inputs');

    if (!control || !search || !tags || !dropdown || !inputs) {
        return;
    }

    const optionById = (id) => options.find((option) => Number(option.id) === Number(id));

    const renderHiddenInputs = () => {
        inputs.innerHTML = '';
        selected.forEach((id) => {
            const input = document.createElement('input');
            input.type = 'hidden';
            input.name = 'orglocation[]';
            input.value = String(id);
            inputs.appendChild(input);
        });
    };

    const renderTags = () => {
        tags.innerHTML = '';
        selected.forEach((id) => {
            const option = optionById(id);
            if (!option) {
                return;
            }

            const tag = document.createElement('span');
            tag.className = 'inline-flex items-center gap-1 rounded border border-slate-300 bg-slate-100 px-2 py-1 text-sm font-semibold text-slate-700';

            const text = document.createElement('span');
            text.textContent = option.name;

            const remove = document.createElement('button');
            remove.type = 'button';
            remove.className = 'text-slate-400 hover:text-red-500';
            remove.setAttribute('aria-label', `Remove ${option.name}`);
            remove.innerHTML = '&times;';
            remove.addEventListener('click', (event) => {
                event.stopPropagation();
                selected = selected.filter((selectedId) => selectedId !== id);
                render();
                search.focus();
            });

            tag.append(text, remove);
            tags.appendChild(tag);
        });
        renderHiddenInputs();
    };

    const renderDropdown = () => {
        const query = search.value.trim().toLowerCase();
        const available = options.filter((option) => {
            return !selected.includes(Number(option.id)) && option.name.toLowerCase().includes(query);
        });

        dropdown.innerHTML = '';

        const placeholder = document.createElement('button');
        placeholder.type = 'button';
        placeholder.className = 'block w-full px-4 py-2 text-left text-sm font-semibold text-white bg-brand-600';
        placeholder.textContent = '-Select Location-';
        placeholder.addEventListener('click', () => search.focus());
        dropdown.appendChild(placeholder);

        if (!available.length) {
            const empty = document.createElement('div');
            empty.className = 'px-4 py-3 text-sm font-semibold text-slate-400';
            empty.textContent = 'No matching locations';
            dropdown.appendChild(empty);
            return;
        }

        available.forEach((option) => {
            const item = document.createElement('button');
            item.type = 'button';
            item.className = 'block w-full px-4 py-2 text-left text-sm font-semibold text-slate-700 hover:bg-brand-50 hover:text-brand-700';
            item.textContent = option.name;
            item.addEventListener('click', () => {
                selected.push(Number(option.id));
                search.value = '';
                render();
                openDropdown();
                search.focus();
            });
            dropdown.appendChild(item);
        });
    };

    const openDropdown = () => {
        renderDropdown();
        dropdown.classList.remove('hidden');
    };

    const closeDropdown = () => {
        dropdown.classList.add('hidden');
    };

    const render = () => {
        renderTags();
        renderDropdown();
    };

    control.addEventListener('click', () => {
        search.focus();
        openDropdown();
    });
    search.addEventListener('focus', openDropdown);
    search.addEventListener('input', openDropdown);
    search.addEventListener('keydown', (event) => {
        if (event.key === 'Escape') {
            closeDropdown();
        }
    });
    document.addEventListener('click', (event) => {
        if (!picker.contains(event.target)) {
            closeDropdown();
        }
    });

    render();
});
</script>
<?php console_footer(); ?>
