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

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

$pageLink = 'payroll/gratuity-configuration.php';
$acl = require_acl('can_view', $pageLink);
$errors = [];
$flash = $_SESSION['flash_gratuity_configuration'] ?? null;
unset($_SESSION['flash_gratuity_configuration']);

function gfc_stmt(mysqli $con, string $sql): mysqli_stmt
{
    $stmt = $con->prepare($sql);
    if (!$stmt) {
        throw new RuntimeException('Unable to prepare Gratuity configuration query.');
    }
    return $stmt;
}

function gfc_options(mysqli $con, string $sql): array
{
    $rows = [];
    $stmt = gfc_stmt($con, $sql);
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $rows[] = $row;
    }
    $stmt->close();
    return $rows;
}

function gfc_exists(mysqli $con, int $id): bool
{
    if ($id <= 0) {
        return false;
    }
    $stmt = gfc_stmt($con, 'SELECT id FROM jos_app_gratuityconfig WHERE id=? LIMIT 1');
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $exists = (bool)$stmt->get_result()->fetch_assoc();
    $stmt->close();
    return $exists;
}

function gfc_month_exists(mysqli $con, int $monthId): bool
{
    if ($monthId <= 0) {
        return false;
    }
    $stmt = gfc_stmt($con, 'SELECT id FROM jos_app_mmonth WHERE id=? LIMIT 1');
    $stmt->bind_param('i', $monthId);
    $stmt->execute();
    $exists = (bool)$stmt->get_result()->fetch_assoc();
    $stmt->close();
    return $exists;
}

function gfc_year_exists(mysqli $con, int $yearId): bool
{
    if ($yearId <= 0) {
        return false;
    }
    $stmt = gfc_stmt($con, 'SELECT id FROM jos_app_year WHERE id=? LIMIT 1');
    $stmt->bind_param('i', $yearId);
    $stmt->execute();
    $exists = (bool)$stmt->get_result()->fetch_assoc();
    $stmt->close();
    return $exists;
}

function gfc_valid_components(mysqli $con, array $componentIds): array
{
    $ids = array_values(array_unique(array_filter(array_map('intval', $componentIds), static fn($id) => $id > 0)));
    if (!$ids) {
        return [];
    }
    $placeholders = implode(',', array_fill(0, count($ids), '?'));
    $types = str_repeat('i', count($ids));
    $stmt = gfc_stmt($con, "SELECT id FROM jos_app_salarycomponentmaster WHERE componenttype='2' AND id IN ($placeholders)");
    $stmt->bind_param($types, ...$ids);
    $stmt->execute();
    $result = $stmt->get_result();
    $valid = [];
    while ($row = $result->fetch_assoc()) {
        $valid[] = (int)$row['id'];
    }
    $stmt->close();
    $validLookup = array_flip($valid);
    return array_values(array_filter($ids, static fn($id) => isset($validLookup[$id])));
}

function gfc_fetch_row(mysqli $con, int $id): ?array
{
    $stmt = gfc_stmt($con, 'SELECT * FROM jos_app_gratuityconfig WHERE id=? LIMIT 1');
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc() ?: null;
    $stmt->close();
    return $row;
}

function gfc_save_row(mysqli $con, int $id, array $data): int
{
    if ($id > 0) {
        $stmt = gfc_stmt($con, 'UPDATE jos_app_gratuityconfig SET month=?, year=?, components=? WHERE id=?');
        $stmt->bind_param('iisi', $data['month'], $data['year'], $data['components'], $id);
        if (!$stmt->execute()) {
            throw new RuntimeException('Unable to update Gratuity configuration.');
        }
        $stmt->close();
        return $id;
    }

    $stmt = gfc_stmt($con, 'INSERT INTO jos_app_gratuityconfig (month, year, components) VALUES (?,?,?)');
    $stmt->bind_param('iis', $data['month'], $data['year'], $data['components']);
    if (!$stmt->execute()) {
        throw new RuntimeException('Unable to add Gratuity configuration.');
    }
    $savedId = (int)$con->insert_id;
    $stmt->close();
    return $savedId;
}

function gfc_delete_row(mysqli $con, int $id): void
{
    $stmt = gfc_stmt($con, 'DELETE FROM jos_app_gratuityconfig WHERE id=?');
    $stmt->bind_param('i', $id);
    if (!$stmt->execute()) {
        throw new RuntimeException('Unable to delete Gratuity configuration.');
    }
    $stmt->close();
}

function gfc_text(array $row, string $key, string $default = ''): string
{
    return array_key_exists($key, $row) && $row[$key] !== null ? (string)$row[$key] : $default;
}

function gfc_int_row(array $row, string $key, int $default = 0): int
{
    return array_key_exists($key, $row) && $row[$key] !== null ? (int)$row[$key] : $default;
}

function gfc_component_ids($csv): array
{
    if ($csv === null || trim((string)$csv) === '') {
        return [];
    }
    return array_values(array_unique(array_filter(array_map('intval', explode(',', (string)$csv)), static fn($id) => $id > 0)));
}

function gfc_component_names($csv, array $componentMap): string
{
    $names = [];
    foreach (gfc_component_ids($csv) as $id) {
        $names[] = $componentMap[$id] ?? ('#' . $id);
    }
    return implode(', ', $names);
}

$months = gfc_options($con, 'SELECT id,month FROM jos_app_mmonth ORDER BY id ASC');
$years = gfc_options($con, 'SELECT id,year FROM jos_app_year ORDER BY id DESC');
$formYears = gfc_options($con, 'SELECT id,year FROM jos_app_year ORDER BY id DESC LIMIT 3');
$components = gfc_options($con, "SELECT id,componentname FROM jos_app_salarycomponentmaster WHERE componenttype='2' ORDER BY componentname");

$monthMap = [];
foreach ($months as $row) {
    $monthMap[(int)$row['id']] = (string)$row['month'];
}
$yearMap = [];
foreach ($years as $row) {
    $yearMap[(int)$row['id']] = (string)$row['year'];
}
$componentMap = [];
foreach ($components as $row) {
    $componentMap[(int)$row['id']] = (string)$row['componentname'];
}

$mode = (string)($_GET['mode'] ?? '');
$isForm = $mode === 'add';
$editId = isset($_GET['edit']) ? max(0, (int)$_GET['edit']) : 0;
$editRow = ['id' => 0, 'month' => '', 'year' => '', 'components' => ''];

if ($isForm && empty($acl['can_add'])) {
    http_response_code(403);
    exit('Access denied.');
}

if ($editId > 0) {
    if (empty($acl['can_edit'])) {
        http_response_code(403);
        exit('Access denied.');
    }
    $isForm = true;
    $editRow = gfc_fetch_row($con, $editId) ?: [];
    if (!$editRow) {
        $_SESSION['flash_gratuity_configuration'] = 'Gratuity Configuration was not found.';
        redirect('/payroll/gratuity-configuration.php');
    }
}

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));
        if ($id > 0 && empty($acl['can_edit'])) {
            $errors[] = 'You do not have permission to edit Gratuity configurations.';
        }
        if ($id === 0 && empty($acl['can_add'])) {
            $errors[] = 'You do not have permission to add Gratuity configurations.';
        }
        if ($id > 0 && !gfc_exists($con, $id)) {
            $errors[] = 'Gratuity Configuration was not found.';
        }

        $month = (int)($_POST['month'] ?? 0);
        $year = (int)($_POST['year'] ?? 0);
        $componentIds = gfc_valid_components($con, (array)($_POST['componentsal'] ?? []));

        if (!gfc_month_exists($con, $month)) {
            $errors[] = 'Select a valid Month.';
        }
        if (!gfc_year_exists($con, $year)) {
            $errors[] = 'Select a valid Year.';
        }
        if (!$componentIds) {
            $errors[] = 'Select at least one valid Salary Component.';
        }

        $data = [
            'month' => $month,
            'year' => $year,
            'components' => implode(',', $componentIds),
        ];

        if (!$errors) {
            $con->begin_transaction();
            try {
                gfc_save_row($con, $id, $data);
                $con->commit();
                $_SESSION['flash_gratuity_configuration'] = $id > 0 ? 'Gratuity Configuration updated successfully.' : 'Gratuity Configuration added successfully.';
                redirect('/payroll/gratuity-configuration.php');
            } catch (Throwable $e) {
                $con->rollback();
                $errors[] = 'Unable to save the Gratuity configuration. No changes were committed.';
            }
        }
        $isForm = true;
        $editRow = $data + ['id' => $id];
    } elseif ($action === 'delete') {
        if (empty($acl['can_delete'])) {
            $errors[] = 'You do not have permission to delete Gratuity configurations.';
        }
        $id = max(0, (int)($_POST['id'] ?? 0));
        if ($id <= 0 || !gfc_exists($con, $id)) {
            $errors[] = 'Gratuity Configuration was not found.';
        }

        if (!$errors) {
            $con->begin_transaction();
            try {
                gfc_delete_row($con, $id);
                $con->commit();
                $_SESSION['flash_gratuity_configuration'] = 'Gratuity Configuration deleted successfully.';
                redirect('/payroll/gratuity-configuration.php');
            } catch (Throwable $e) {
                $con->rollback();
                $errors[] = 'Unable to delete the Gratuity configuration. No changes were committed.';
            }
        }
    }
}

$filterQ = trim((string)($_GET['q'] ?? ''));
$filterMonth = isset($_GET['month']) && $_GET['month'] !== '' ? (int)$_GET['month'] : 0;
$filterYear = isset($_GET['year']) && $_GET['year'] !== '' ? (int)$_GET['year'] : 0;
$filterComponent = isset($_GET['component']) && $_GET['component'] !== '' ? (int)$_GET['component'] : 0;
$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = 20;
$totalRows = 0;
$rows = [];
$pages = 1;

if (!$isForm) {
    $where = ['1=1'];
    $types = '';
    $params = [];
    if ($filterQ !== '') {
        $where[] = '(m.month LIKE ? OR y.year LIKE ? OR EXISTS (SELECT 1 FROM jos_app_salarycomponentmaster sc WHERE sc.componenttype=\'2\' AND FIND_IN_SET(sc.id, c.components) AND sc.componentname LIKE ?))';
        $types .= 'sss';
        $params[] = '%' . $filterQ . '%';
        $params[] = '%' . $filterQ . '%';
        $params[] = '%' . $filterQ . '%';
    }
    if ($filterMonth > 0) {
        $where[] = 'c.month=?';
        $types .= 'i';
        $params[] = $filterMonth;
    }
    if ($filterYear > 0) {
        $where[] = 'c.year=?';
        $types .= 'i';
        $params[] = $filterYear;
    }
    if ($filterComponent > 0) {
        $where[] = 'FIND_IN_SET(?, c.components)';
        $types .= 'i';
        $params[] = $filterComponent;
    }
    $whereSql = implode(' AND ', $where);

    $stmt = gfc_stmt($con, 'SELECT COUNT(*) AS total FROM jos_app_gratuityconfig c LEFT JOIN jos_app_mmonth m ON m.id=c.month LEFT JOIN jos_app_year y ON y.id=c.year WHERE ' . $whereSql);
    if ($types !== '') {
        $stmt->bind_param($types, ...$params);
    }
    $stmt->execute();
    $totalRows = (int)($stmt->get_result()->fetch_assoc()['total'] ?? 0);
    $stmt->close();
    $pages = max(1, (int)ceil($totalRows / $perPage));
    $page = min($page, $pages);
    $offset = ($page - 1) * $perPage;

    $stmt = gfc_stmt($con, 'SELECT c.*,m.month AS month_label,y.year AS year_label FROM jos_app_gratuityconfig c LEFT JOIN jos_app_mmonth m ON m.id=c.month LEFT JOIN jos_app_year y ON y.id=c.year WHERE ' . $whereSql . ' ORDER BY c.id DESC LIMIT ? OFFSET ?');
    $listTypes = $types . 'ii';
    $listParams = $params;
    $listParams[] = $perPage;
    $listParams[] = $offset;
    $stmt->bind_param($listTypes, ...$listParams);
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $rows[] = $row;
    }
    $stmt->close();
}

$selectedComponents = gfc_component_ids($editRow['components'] ?? '');
$componentPickerOptions = [];
foreach ($components as $option) {
    $componentPickerOptions[] = ['id' => (int)$option['id'], 'name' => (string)$option['componentname']];
}
$value = static function (string $key, $default = '') use (&$editRow) {
    return $editRow[$key] ?? $default;
};
$input = 'mt-1 w-full rounded-lg border border-slate-200 bg-white px-3 py-2.5 text-sm text-slate-800 outline-none focus:border-brand-500 focus:ring-2 focus:ring-brand-100';
$filterInput = 'rounded-xl border border-slate-200 px-3 py-2.5 text-sm';

console_header('Gratuity Configuration', $pageLink);
?>
<div class="mb-4 flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
  <div>
    <div class="mb-2 flex items-center gap-2 text-xs font-semibold text-slate-500"><a href="/dashboard.php">Dashboard</a><i class="fa-solid fa-chevron-right text-[9px]"></i><span>D. Masters</span><i class="fa-solid fa-chevron-right text-[9px]"></i><span>Payroll Settings</span><i class="fa-solid fa-chevron-right text-[9px]"></i><span class="text-brand-600">Gratuity Configuration</span></div>
    <h1 class="text-2xl font-bold text-slate-900">Gratuity Configuration</h1>
    <p class="mt-1 text-sm text-slate-500">Configure gratuity salary components by month and payroll year.</p>
  </div>
</div>
<?php if ($flash): ?><div class="mb-5 rounded-xl border border-emerald-100 bg-emerald-50 px-5 py-4 text-sm font-semibold text-emerald-700"><i class="fa-solid fa-circle-check mr-2"></i><?= h($flash) ?></div><?php endif; ?>
<?php if ($errors): ?><div class="mb-5 rounded-xl border border-red-100 bg-red-50 px-5 py-4 text-sm font-semibold text-red-700"><div class="font-bold">Please fix the following</div><ul class="mt-2 list-inside list-disc"><?php foreach($errors as $error): ?><li><?= h($error) ?></li><?php endforeach; ?></ul></div><?php endif; ?>

<?php if ($isForm): ?>
<form method="post" class="space-y-4 js-gratuity-form">
  <input type="hidden" name="_csrf" value="<?= h(csrf_token()) ?>"><input type="hidden" name="action" value="save"><input type="hidden" name="id" value="<?= (int)$value('id', 0) ?>">
  <section class="rounded-2xl border border-slate-100 bg-white p-4 shadow-sm">
    <div class="mb-4 flex flex-wrap items-center justify-between gap-3"><div class="flex items-center gap-3"><span class="flex h-9 w-9 items-center justify-center rounded-lg bg-brand-50 text-brand-600"><i class="fa-solid fa-hand-holding-dollar"></i></span><div><h2 class="font-bold text-slate-800"><?= (int)$value('id',0)>0?'Edit Gratuity Configuration':'New Gratuity Configuration' ?></h2><p class="text-xs text-slate-400">Fields marked with * are required.</p></div></div><a href="/payroll/gratuity-configuration.php" class="rounded-lg border border-slate-200 bg-white px-4 py-2 text-sm font-bold text-slate-600 hover:bg-slate-50"><i class="fa-solid fa-arrow-left mr-2"></i>Back to List</a></div>
    <div class="grid gap-3 md:grid-cols-2 xl:grid-cols-4">
      <label class="text-sm font-semibold text-slate-700">Month *<select name="month" required class="<?= $input ?>"><option value="">Select Month</option><?php foreach($months as $option): ?><option value="<?= (int)$option['id'] ?>" <?= (int)$value('month')===(int)$option['id']?'selected':'' ?>><?= h($option['month']) ?></option><?php endforeach; ?></select></label>
      <label class="text-sm font-semibold text-slate-700">Year *<select name="year" required class="<?= $input ?>"><option value="">Select Year</option><?php foreach($formYears as $option): ?><option value="<?= (int)$option['id'] ?>" <?= (int)$value('year')===(int)$option['id']?'selected':'' ?>><?= h($option['year']) ?></option><?php endforeach; ?></select></label>
      <div class="text-sm font-semibold text-slate-700 md:col-span-2">Salary Component *
        <div class="relative mt-1 js-component-picker" data-options='<?= h(json_encode($componentPickerOptions, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)) ?>' data-selected='<?= h(json_encode($selectedComponents)) ?>'>
          <div class="js-component-control min-h-[46px] w-full rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm text-slate-800 outline-none focus-within:border-brand-500 focus-within:ring-2 focus-within:ring-brand-100">
            <div class="js-component-tags mb-1 flex flex-wrap gap-1.5"></div>
            <input type="text" class="js-component-search w-full border-0 bg-transparent p-0 text-sm font-medium text-slate-800 outline-none placeholder:text-slate-400" placeholder="Type or select component name" autocomplete="off">
          </div>
          <div class="js-component-dropdown hidden absolute left-0 right-0 top-full z-40 max-h-72 overflow-y-auto border border-slate-300 bg-white shadow-xl"></div>
          <div class="js-component-inputs"></div>
          <p class="js-component-error mt-1 hidden text-xs font-semibold text-red-600">Select at least one salary component.</p>
        </div>
      </div>
    </div>
  </section>
  <div class="flex flex-wrap justify-end gap-2"><a href="/payroll/gratuity-configuration.php" class="rounded-lg border border-slate-200 bg-white px-5 py-2.5 text-sm font-bold text-slate-600">Cancel</a><button class="rounded-lg bg-brand-600 px-5 py-2.5 text-sm font-bold text-white hover:bg-brand-700"><i class="fa-solid fa-floppy-disk mr-2"></i>Save Configuration</button></div>
</form>
<?php else: ?>
<section class="overflow-hidden rounded-2xl border border-slate-100 bg-white shadow-sm">
  <div class="flex flex-col gap-3 border-b border-slate-100 px-5 py-4 sm:flex-row sm:items-center sm:justify-between"><div><h2 class="font-bold text-slate-800">Gratuity Configuration List</h2><p class="mt-1 text-xs font-medium text-slate-400">Configurations are ordered by latest record.</p></div><?php if(!empty($acl['can_add'])): ?><a href="?mode=add" class="inline-flex items-center justify-center gap-2 rounded-lg bg-brand-600 px-4 py-2.5 text-sm font-bold text-white shadow-sm hover:bg-brand-700"><i class="fa-solid fa-plus"></i>+ Add</a><?php endif; ?></div>
  <form method="get" class="grid gap-3 border-b border-slate-100 p-5 md:grid-cols-2 xl:grid-cols-6"><input name="q" value="<?= h($filterQ) ?>" class="<?= $filterInput ?>" placeholder="Search month, year, component"><select name="month" class="<?= $filterInput ?>"><option value="">All Months</option><?php foreach($months as $option): ?><option value="<?= (int)$option['id'] ?>" <?= $filterMonth===(int)$option['id']?'selected':'' ?>><?= h($option['month']) ?></option><?php endforeach; ?></select><select name="year" class="<?= $filterInput ?>"><option value="">All Years</option><?php foreach($years as $option): ?><option value="<?= (int)$option['id'] ?>" <?= $filterYear===(int)$option['id']?'selected':'' ?>><?= h($option['year']) ?></option><?php endforeach; ?></select><select name="component" class="<?= $filterInput ?>"><option value="">All Components</option><?php foreach($components as $option): ?><option value="<?= (int)$option['id'] ?>" <?= $filterComponent===(int)$option['id']?'selected':'' ?>><?= h($option['componentname']) ?></option><?php endforeach; ?></select><div class="flex gap-2 xl:col-span-2"><button class="rounded-xl bg-slate-900 px-5 py-2.5 text-sm font-bold text-white"><i class="fa-solid fa-filter mr-2"></i>Filter</button><a href="/payroll/gratuity-configuration.php" class="rounded-xl border border-slate-200 px-5 py-2.5 text-sm font-bold text-slate-600">Clear</a></div></form>
  <div class="overflow-x-auto"><table class="w-full min-w-[900px] text-left text-sm"><thead class="bg-slate-50 text-[10px] font-extrabold uppercase tracking-wider text-slate-700"><tr><th class="px-5 py-4 w-20">Sr No</th><th class="px-5 py-4">Month</th><th class="px-5 py-4">Year</th><th class="px-5 py-4">Component Name</th><th class="px-5 py-4 text-right">Actions</th></tr></thead><tbody class="divide-y divide-slate-100">
    <?php if(!$rows): ?><tr><td colspan="5" class="px-6 py-14 text-center font-semibold text-slate-400">No gratuity configurations found.</td></tr><?php endif; ?>
    <?php foreach($rows as $index=>$row): ?><tr class="align-top hover:bg-slate-50/70"><td class="px-5 py-4 font-semibold text-slate-500"><?= (($page-1)*$perPage)+$index+1 ?></td><td class="px-5 py-4 font-bold text-slate-800"><?= h(gfc_text($row, 'month_label', $monthMap[gfc_int_row($row, 'month')] ?? '')) ?></td><td class="px-5 py-4"><?= h(gfc_text($row, 'year_label', $yearMap[gfc_int_row($row, 'year')] ?? '')) ?></td><td class="px-5 py-4"><?= h(gfc_component_names($row['components'] ?? '', $componentMap)) ?></td><td class="px-5 py-4"><div class="flex justify-end gap-2"><?php if(!empty($acl['can_edit'])): ?><a href="?edit=<?= gfc_int_row($row, 'id') ?>" class="rounded-lg border border-slate-200 px-3 py-2 text-slate-600 hover:bg-brand-50 hover:text-brand-600" title="Edit"><i class="fa-solid fa-pen"></i></a><?php endif; ?><?php if(!empty($acl['can_delete'])): ?><form method="post" class="inline" onsubmit="return confirm('Delete this Gratuity configuration?');"><input type="hidden" name="_csrf" value="<?= h(csrf_token()) ?>"><input type="hidden" name="action" value="delete"><input type="hidden" name="id" value="<?= gfc_int_row($row, 'id') ?>"><button type="submit" class="rounded-lg border border-slate-200 px-3 py-2 text-red-600 hover:bg-red-50" title="Delete"><i class="fa-solid fa-trash"></i></button></form><?php endif; ?></div></td></tr><?php endforeach; ?>
  </tbody></table></div>
  <?php if($totalRows>$perPage): ?><div class="flex items-center justify-between border-t border-slate-100 px-5 py-4 text-sm"><span class="font-medium text-slate-500"><?= $totalRows ?> configurations</span><div class="flex gap-2"><?php $base=['q'=>$filterQ,'month'=>$filterMonth ?: '', 'year'=>$filterYear ?: '', 'component'=>$filterComponent ?: '']; if($page>1): ?><a class="rounded-lg border border-slate-200 px-4 py-2 font-semibold" href="?<?= h(http_build_query($base + ['page'=>$page-1])) ?>">Previous</a><?php endif; ?><?php if($page<$pages): ?><a class="rounded-lg border border-slate-200 px-4 py-2 font-semibold" href="?<?= h(http_build_query($base + ['page'=>$page+1])) ?>">Next</a><?php endif; ?></div></div><?php endif; ?>
</section>
<?php endif; ?>
<?php if ($isForm): ?>
<script>
document.querySelectorAll('.js-component-picker').forEach(function (picker) {
  const form = picker.closest('form');
  const options = JSON.parse(picker.dataset.options || '[]');
  let selected = JSON.parse(picker.dataset.selected || '[]').map(Number);
  const control = picker.querySelector('.js-component-control');
  const search = picker.querySelector('.js-component-search');
  const tags = picker.querySelector('.js-component-tags');
  const dropdown = picker.querySelector('.js-component-dropdown');
  const inputs = picker.querySelector('.js-component-inputs');
  const error = picker.querySelector('.js-component-error');

  function setInvalid(invalid) {
    control.classList.toggle('border-red-300', invalid);
    control.classList.toggle('ring-2', invalid);
    control.classList.toggle('ring-red-100', invalid);
    if (error) error.classList.toggle('hidden', !invalid);
  }

  function labelFor(id) {
    const option = options.find(function (item) { return Number(item.id) === Number(id); });
    return option ? option.name : '#' + id;
  }

  function syncInputs() {
    inputs.innerHTML = '';
    selected.forEach(function (id) {
      const input = document.createElement('input');
      input.type = 'hidden';
      input.name = 'componentsal[]';
      input.value = String(id);
      inputs.appendChild(input);
    });
    setInvalid(false);
  }

  function drawTags() {
    tags.innerHTML = '';
    if (!selected.length) {
      tags.classList.add('hidden');
      search.placeholder = 'Type or select component name';
    } else {
      tags.classList.remove('hidden');
      search.placeholder = '';
    }
    selected.forEach(function (id) {
      const tag = document.createElement('span');
      tag.className = 'inline-flex items-center gap-1 rounded-md bg-brand-50 px-2 py-1 text-xs font-bold text-brand-700';
      tag.textContent = labelFor(id);
      const remove = document.createElement('button');
      remove.type = 'button';
      remove.className = 'ml-1 text-brand-500 hover:text-red-600';
      remove.innerHTML = '&times;';
      remove.addEventListener('click', function () {
        selected = selected.filter(function (value) { return Number(value) !== Number(id); });
        render();
        openDropdown();
        search.focus();
      });
      tag.appendChild(remove);
      tags.appendChild(tag);
    });
  }

  function drawOptions() {
    const term = search.value.trim().toLowerCase();
    dropdown.innerHTML = '';
    const placeholder = document.createElement('button');
    placeholder.type = 'button';
    placeholder.className = 'block w-full bg-brand-600 px-3 py-2 text-left text-sm font-semibold text-white';
    placeholder.textContent = '-Select Component Name-';
    placeholder.addEventListener('click', function () {
      search.value = '';
      drawOptions();
      search.focus();
    });
    dropdown.appendChild(placeholder);

    const available = options.filter(function (option) {
      return !selected.includes(Number(option.id)) && (!term || option.name.toLowerCase().includes(term));
    });
    if (!available.length) {
      const empty = document.createElement('div');
      empty.className = 'px-3 py-3 text-sm font-medium text-slate-400';
      empty.textContent = 'No components found';
      dropdown.appendChild(empty);
      return;
    }
    available.forEach(function (option) {
      const item = document.createElement('button');
      item.type = 'button';
      item.className = 'block w-full px-3 py-2 text-left text-sm font-medium text-slate-700 hover:bg-brand-50 hover:text-brand-700';
      item.textContent = option.name;
      item.addEventListener('click', function () {
        selected.push(Number(option.id));
        search.value = '';
        setInvalid(false);
        render();
        openDropdown();
        search.focus();
      });
      dropdown.appendChild(item);
    });
  }

  function openDropdown() {
    drawOptions();
    dropdown.classList.remove('hidden');
  }

  function render() {
    drawTags();
    syncInputs();
    drawOptions();
  }

  control.addEventListener('click', function () {
    search.focus();
    openDropdown();
  });
  search.addEventListener('focus', openDropdown);
  search.addEventListener('input', openDropdown);
  search.addEventListener('keydown', function (event) {
    if (event.key === 'Escape') {
      dropdown.classList.add('hidden');
    }
  });
  document.addEventListener('click', function (event) {
    if (!picker.contains(event.target)) {
      dropdown.classList.add('hidden');
    }
  });
  if (form) {
    form.addEventListener('submit', function (event) {
      if (!selected.length) {
        event.preventDefault();
        setInvalid(true);
        openDropdown();
        search.focus();
      }
    });
  }
  render();
});
</script>
<?php endif; ?>
<?php console_footer(); ?>
