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

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

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

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

$mode = (string)($_GET['mode'] ?? '');
$editId = max(0, (int)($_GET['edit'] ?? 0));
$historyId = max(0, (int)($_GET['history'] ?? 0));
$isHistoryView = $historyId > 0;
$isFormView = !$isHistoryView && ($mode === 'add' || $editId > 0);
$search = trim((string)($_GET['q'] ?? ''));
$editItem = null;
$historyItem = null;
$historyRows = [];

$hasHistoryTable = false;
$tableCheck = $con->query("SHOW TABLES LIKE 'jos_app_holiday_edit_log'");
if ($tableCheck && $tableCheck->num_rows > 0) {
    $hasHistoryTable = true;
}

function holiday_csv_ids($value): array
{
    $values = is_array($value) ? $value : explode(',', (string)$value);
    return array_values(array_unique(array_filter(
        array_map('intval', $values),
        static fn(int $id): bool => $id > 0
    )));
}

function holiday_validate_ids(mysqli $con, string $table, array $ids, string $extraWhere = ''): bool
{
    if (!$ids) {
        return true;
    }
    $allowed = ['jos_app_department', 'jos_app_payrolllocation', 'jos_app_employee'];
    if (!in_array($table, $allowed, true)) {
        return false;
    }
    $sql = "SELECT id FROM {$table} WHERE id=? {$extraWhere} LIMIT 1";
    $stmt = $con->prepare($sql);
    if (!$stmt) {
        return false;
    }
    foreach ($ids as $id) {
        $stmt->bind_param('i', $id);
        $stmt->execute();
        if (!$stmt->get_result()->fetch_assoc()) {
            $stmt->close();
            return false;
        }
    }
    $stmt->close();
    return true;
}

function holiday_lookup_options(mysqli $con, string $table, string $labelColumn, string $extraWhere = ''): array
{
    $allowed = [
        'jos_app_department' => ['department'],
        'jos_app_payrolllocation' => ['name'],
        'jos_app_employee' => ['name'],
    ];
    if (!isset($allowed[$table]) || !in_array($labelColumn, $allowed[$table], true)) {
        return [];
    }
    $items = [];
    $result = $con->query("SELECT id, {$labelColumn} AS label FROM {$table} {$extraWhere} ORDER BY {$labelColumn} ASC, id ASC");
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $items[] = ['id' => (int)$row['id'], 'name' => (string)$row['label']];
        }
        $result->free();
    }
    return $items;
}

function holiday_type_label(int $value): string
{
    $labels = [
        1 => 'Declare',
        2 => 'Undeclare',
        3 => 'Optional',
        4 => 'Compulsory',
    ];
    return $labels[$value] ?? 'Regular (National)';
}

function holiday_option_map(array $options): array
{
    $map = [];
    foreach ($options as $option) {
        $map[(int)$option['id']] = (string)$option['name'];
    }
    return $map;
}

function holiday_csv_labels($value, array $map): string
{
    $labels = [];
    foreach (holiday_csv_ids($value) as $id) {
        $labels[] = $map[$id] ?? ('#' . $id);
    }
    return implode(', ', $labels);
}

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));
        $date = trim((string)($_POST['date'] ?? ''));
        $description = trim((string)($_POST['description'] ?? ''));
        $declarePh = (int)($_POST['declareph'] ?? 0);
        $deductionType = (int)($_POST['deductiontype'] ?? 0);
        $payrollLocationIds = holiday_csv_ids($_POST['payroll_location'] ?? []);
        $departmentIds = holiday_csv_ids($_POST['depat'] ?? []);
        $employeeIds = holiday_csv_ids($_POST['empid'] ?? []);
        $rejectedEmployeeIds = holiday_csv_ids($_POST['reject_empid'] ?? []);

        if ($id > 0 && empty($acl['can_edit'])) {
            $errors[] = 'You do not have permission to edit holidays.';
        }
        if ($id === 0 && empty($acl['can_add'])) {
            $errors[] = 'You do not have permission to add holidays.';
        }
        $dateObject = DateTimeImmutable::createFromFormat('!Y-m-d', $date);
        if (!$dateObject || $dateObject->format('Y-m-d') !== $date) {
            $errors[] = 'Enter a valid holiday date.';
        }
        if ($description === '') {
            $errors[] = 'Holiday title is required.';
        } elseif (strlen($description) > 255) {
            $errors[] = 'Holiday title must be 255 characters or fewer.';
        }
        if (!in_array($declarePh, [0, 1, 2, 3, 4], true)) {
            $errors[] = 'Select a valid holiday type.';
        }
        if (!in_array($deductionType, [0, 1], true)) {
            $errors[] = 'Select a valid day type.';
        }
        if (!holiday_validate_ids($con, 'jos_app_payrolllocation', $payrollLocationIds)) {
            $errors[] = 'One or more payroll locations are invalid.';
        }
        if (!holiday_validate_ids($con, 'jos_app_department', $departmentIds)) {
            $errors[] = 'One or more departments are invalid.';
        }
        if (!holiday_validate_ids($con, 'jos_app_employee', $employeeIds, 'AND status IN (0,1)')) {
            $errors[] = 'One or more selected employees are invalid.';
        }
        if (!holiday_validate_ids($con, 'jos_app_employee', $rejectedEmployeeIds, 'AND status IN (0,1)')) {
            $errors[] = 'One or more rejected employees are invalid.';
        }

        if (!$errors) {
            $payrollLocations = implode(',', $payrollLocationIds);
            $departments = implode(',', $departmentIds);
            $employees = implode(',', $employeeIds);
            $rejectedEmployees = implode(',', $rejectedEmployeeIds);
            $status = '';
            $userId = (int)(current_user()['id'] ?? 0);
            $con->begin_transaction();
            try {
                if ($id > 0) {
                    $stmt = $con->prepare('UPDATE jos_app_holiday SET date=?, description=?, declareph=?, deductiontype=?, payroll_location=?, depat=?, empid=?, reject_empid=? WHERE id=?');
                    $stmt->bind_param('ssiissssi', $date, $description, $declarePh, $deductionType, $payrollLocations, $departments, $employees, $rejectedEmployees, $id);
                    $stmt->execute();
                    $stmt->close();
                    $holidayId = $id;
                    audit_log('holiday.update', 'jos_app_holiday', (string)$holidayId, $description);
                } else {
                    $stmt = $con->prepare('INSERT INTO jos_app_holiday (date, description, declareph, deductiontype, payroll_location, depat, empid, reject_empid, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)');
                    $stmt->bind_param('ssiisssss', $date, $description, $declarePh, $deductionType, $payrollLocations, $departments, $employees, $rejectedEmployees, $status);
                    $stmt->execute();
                    $holidayId = (int)$con->insert_id;
                    $stmt->close();
                    audit_log('holiday.create', 'jos_app_holiday', (string)$holidayId, $description);
                }

                if ($hasHistoryTable) {
                    $stmt = $con->prepare('INSERT INTO jos_app_holiday_edit_log (holiday_id, date, description, status, time, modify_by, declareph, payroll_location, depat, empid, reject_empid) SELECT id, date, description, status, NOW(), ?, declareph, payroll_location, depat, empid, reject_empid FROM jos_app_holiday WHERE id=?');
                    if ($stmt) {
                        $stmt->bind_param('ii', $userId, $holidayId);
                        $stmt->execute();
                        $stmt->close();
                    }
                }

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

        $isFormView = true;
        $editId = $id;
    } elseif ($action === 'delete') {
        if (empty($acl['can_delete'])) {
            $errors[] = 'You do not have permission to delete holidays.';
        }
        $id = max(0, (int)($_POST['id'] ?? 0));
        if ($id <= 0) {
            $errors[] = 'Invalid holiday selected.';
        }

        if (!$errors) {
            $stmt = $con->prepare('SELECT description FROM jos_app_holiday WHERE id=? LIMIT 1');
            $stmt->bind_param('i', $id);
            $stmt->execute();
            $row = $stmt->get_result()->fetch_assoc();
            $stmt->close();
            if (!$row) {
                $errors[] = 'Holiday record was not found.';
            } else {
                $stmt = $con->prepare('DELETE FROM jos_app_holiday WHERE id=?');
                $stmt->bind_param('i', $id);
                $stmt->execute();
                $stmt->close();
                audit_log('holiday.delete', 'jos_app_holiday', (string)$id, (string)$row['description']);
                $_SESSION['flash_holidays'] = 'Holiday deleted successfully.';
                redirect('/masters/holidays.php');
            }
        }
    }
}

if ($editId > 0) {
    $stmt = $con->prepare('SELECT id, date, description, declareph, deductiontype, payroll_location, depat, empid, reject_empid FROM jos_app_holiday 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_holidays'] = 'Holiday record was not found.';
        redirect('/masters/holidays.php');
    }
}

if ($historyId > 0) {
    $stmt = $con->prepare('SELECT id, description FROM jos_app_holiday WHERE id=? LIMIT 1');
    $stmt->bind_param('i', $historyId);
    $stmt->execute();
    $historyItem = $stmt->get_result()->fetch_assoc() ?: null;
    $stmt->close();
    if (!$historyItem) {
        $_SESSION['flash_holidays'] = 'Holiday record was not found.';
        redirect('/masters/holidays.php');
    }
    if ($hasHistoryTable) {
        $stmt = $con->prepare('SELECT id, date, description, time, modify_by, payroll_location, depat, empid, reject_empid FROM jos_app_holiday_edit_log WHERE holiday_id=? ORDER BY id DESC');
        $stmt->bind_param('i', $historyId);
        $stmt->execute();
        $result = $stmt->get_result();
        while ($row = $result->fetch_assoc()) {
            $historyRows[] = $row;
        }
        $stmt->close();
    }
}

$payrollLocationOptions = holiday_lookup_options($con, 'jos_app_payrolllocation', 'name');
$departmentOptions = holiday_lookup_options($con, 'jos_app_department', 'department');
$employeeOptions = holiday_lookup_options($con, 'jos_app_employee', 'name', 'WHERE status IN (0,1)');
$allEmployeeOptions = holiday_lookup_options($con, 'jos_app_employee', 'name');
$payrollLocationMap = holiday_option_map($payrollLocationOptions);
$departmentMap = holiday_option_map($departmentOptions);
$employeeMap = holiday_option_map($allEmployeeOptions);

$holidays = [];
if (!$isFormView && !$isHistoryView) {
    if ($search !== '') {
        $like = '%' . $search . '%';
        $stmt = $con->prepare('SELECT id, date, description, declareph, deductiontype, payroll_location, depat, empid, reject_empid FROM jos_app_holiday WHERE description LIKE ? OR date LIKE ? ORDER BY date ASC, id ASC');
        $stmt->bind_param('ss', $like, $like);
        $stmt->execute();
        $result = $stmt->get_result();
    } else {
        $result = $con->query('SELECT id, date, description, declareph, deductiontype, payroll_location, depat, empid, reject_empid FROM jos_app_holiday ORDER BY date ASC, id ASC');
    }
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $holidays[] = $row;
        }
        if ($search === '') {
            $result->free();
        }
    }
    if ($search !== '') {
        $stmt->close();
    }
}

$formId = (int)($editItem['id'] ?? 0);
$formDate = $errors ? trim((string)($_POST['date'] ?? '')) : (string)($editItem['date'] ?? date('Y-m-d'));
$formDescription = $errors ? trim((string)($_POST['description'] ?? '')) : (string)($editItem['description'] ?? '');
$formDeclarePh = $errors ? (int)($_POST['declareph'] ?? 0) : (int)($editItem['declareph'] ?? 0);
$formDeductionType = $errors ? (int)($_POST['deductiontype'] ?? 0) : (int)($editItem['deductiontype'] ?? 0);
$formPayrollLocations = holiday_csv_ids($errors ? ($_POST['payroll_location'] ?? []) : ($editItem['payroll_location'] ?? ''));
$formDepartments = holiday_csv_ids($errors ? ($_POST['depat'] ?? []) : ($editItem['depat'] ?? ''));
$formEmployees = holiday_csv_ids($errors ? ($_POST['empid'] ?? []) : ($editItem['empid'] ?? ''));
$formRejectedEmployees = holiday_csv_ids($errors ? ($_POST['reject_empid'] ?? []) : ($editItem['reject_empid'] ?? ''));

console_header('Holidays', $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">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">Holidays</span>
        </div>
        <h1 class="text-2xl font-bold text-slate-900 tracking-tight">Holiday Master</h1>
        <p class="text-sm text-slate-500 mt-1">Manage payroll holidays and employee 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-regular fa-calendar-days"></i></span>
        <div><div class="text-[11px] font-bold text-slate-400 uppercase tracking-widest"><?= $isFormView ? 'Form View' : ($isHistoryView ? 'History View' : 'Total Holidays') ?></div><div class="text-lg font-bold text-slate-900 leading-tight"><?= $isFormView ? ($formId ? 'Edit' : 'Add') : ($isHistoryView ? count($historyRows) : count($holidays)) ?></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="w-8 h-8 rounded-lg bg-emerald-100 flex items-center justify-center"><i class="fa-solid fa-check text-sm"></i></span><div><h2 class="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="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 && !$isHistoryView): ?>
<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">
        <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-regular fa-calendar-days"></i></span>Holiday List</h2><p class="text-[12px] font-medium text-slate-400 mt-1 lg:ml-11">Source table: <span class="font-semibold">jos_app_holiday</span></p></div>
        <div class="flex flex-col sm:flex-row gap-2">
            <form method="get" class="flex 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 holiday" class="w-full sm:w-64 rounded-lg border border-slate-200 py-2.5 pl-9 pr-3 text-sm outline-none focus:border-brand-500 focus:ring-4 focus:ring-brand-100"></div><button type="submit" class="rounded-lg border border-slate-200 px-4 py-2.5 text-sm font-semibold">Search</button><?php if ($search !== ''): ?><a href="/masters/holidays.php" class="rounded-lg border border-slate-200 px-4 py-2.5 text-sm font-semibold">Clear</a><?php endif; ?></form>
            <?php if (!empty($acl['can_add'])): ?><a href="/masters/holidays.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"><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-[1180px] 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="px-5 py-4">Sr No</th><th class="px-5 py-4">Date</th><th class="px-5 py-4">Holiday Title</th><th class="px-5 py-4">Payroll Location</th><th class="px-5 py-4">Department</th><th class="px-5 py-4">Employees</th><th class="px-5 py-4">Holiday / Day Type</th><th class="px-5 py-4">Rejected Employees</th><th class="px-5 py-4 text-right">Actions</th></tr></thead>
        <tbody class="divide-y divide-slate-100">
        <?php if (!$holidays): ?><tr><td colspan="9" class="px-6 py-10 text-center text-slate-400 font-semibold">No holidays found.</td></tr><?php endif; ?>
        <?php foreach ($holidays as $index => $holiday): ?>
            <?php $locationNames = holiday_csv_labels($holiday['payroll_location'], $payrollLocationMap); $departmentNames = holiday_csv_labels($holiday['depat'], $departmentMap); $employeeNames = holiday_csv_labels($holiday['empid'], $employeeMap); $rejectedEmployeeNames = holiday_csv_labels($holiday['reject_empid'], $employeeMap); ?>
            <tr class="hover:bg-slate-50/80"><td class="px-5 py-5 font-semibold"><?= $index + 1 ?></td><td class="px-5 py-5 whitespace-nowrap"><?= h(date('d-m-Y', strtotime((string)$holiday['date']))) ?></td><td class="px-5 py-5 font-semibold text-slate-900"><?= h($holiday['description']) ?></td><td class="px-5 py-5 max-w-52 truncate" title="<?= h($locationNames) ?>"><?= h($locationNames) ?></td><td class="px-5 py-5 max-w-52 truncate" title="<?= h($departmentNames) ?>"><?= h($departmentNames) ?></td><td class="px-5 py-5 max-w-52 truncate" title="<?= h($employeeNames) ?>"><?= h($employeeNames) ?></td><td class="px-5 py-5"><span class="font-semibold text-slate-800"><?= h(holiday_type_label((int)$holiday['declareph'])) ?></span><div class="text-xs text-slate-400 mt-1"><?= (int)$holiday['deductiontype'] === 1 ? 'Half Day' : 'Full Day' ?></div></td><td class="px-5 py-5 max-w-52 truncate" title="<?= h($rejectedEmployeeNames) ?>"><?= h($rejectedEmployeeNames) ?></td>
            <td class="px-5 py-5"><div class="flex justify-end gap-2"><?php if (!empty($acl['can_edit'])): ?><a href="/masters/holidays.php?edit=<?= (int)$holiday['id'] ?>" class="w-9 h-9 rounded-lg border border-slate-200 flex items-center justify-center text-slate-500 hover:text-brand-600" aria-label="Edit holiday"><i class="fa-regular fa-pen-to-square"></i></a><?php endif; ?><?php if ($hasHistoryTable): ?><a href="/masters/holidays.php?history=<?= (int)$holiday['id'] ?>" class="w-9 h-9 rounded-lg border border-slate-200 flex items-center justify-center text-slate-500 hover:text-brand-600" aria-label="View holiday history"><i class="fa-regular fa-eye"></i></a><?php endif; ?><?php if (!empty($acl['can_delete'])): ?><form method="post" onsubmit="return confirm('Delete this holiday permanently?');"><input type="hidden" name="_csrf" value="<?= h(csrf_token()) ?>"><input type="hidden" name="action" value="delete"><input type="hidden" name="id" value="<?= (int)$holiday['id'] ?>"><button type="submit" class="w-9 h-9 rounded-lg border border-slate-200 flex items-center justify-center text-slate-500 hover:text-red-600 hover:bg-red-50" aria-label="Delete holiday"><i class="fa-regular fa-trash-can"></i></button></form><?php endif; ?></div></td></tr>
        <?php endforeach; ?>
        </tbody>
    </table></div>
</section>

<?php elseif ($isHistoryView): ?>
<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 items-center justify-between"><div><h2 class="font-semibold text-slate-800">Holiday History: <?= h($historyItem['description'] ?? '') ?></h2><p class="text-xs text-slate-400 mt-1">Saved changes from jos_app_holiday_edit_log</p></div><a href="/masters/holidays.php" class="rounded-lg border border-slate-200 px-4 py-2.5 text-sm font-semibold"><i class="fa-solid fa-arrow-left mr-2"></i>Back to List</a></div><div class="overflow-x-auto"><table class="w-full min-w-[900px] text-sm"><thead class="bg-slate-50 text-[10px] uppercase tracking-wider"><tr><th class="text-left px-6 py-4">Date</th><th class="text-left px-6 py-4">Title</th><th class="text-left px-6 py-4">Locations</th><th class="text-left px-6 py-4">Departments</th><th class="text-left px-6 py-4">Modified</th><th class="text-left px-6 py-4">Modified By</th></tr></thead><tbody class="divide-y divide-slate-100"><?php if (!$historyRows): ?><tr><td colspan="6" class="px-6 py-10 text-center text-slate-400">No history found.</td></tr><?php endif; ?><?php foreach ($historyRows as $row): ?><tr><td class="px-6 py-4"><?= h($row['date']) ?></td><td class="px-6 py-4 font-semibold text-slate-900"><?= h($row['description']) ?></td><td class="px-6 py-4"><?= h($row['payroll_location']) ?></td><td class="px-6 py-4"><?= h($row['depat']) ?></td><td class="px-6 py-4"><?= h($row['time']) ?></td><td class="px-6 py-4"><?= (int)$row['modify_by'] ?></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 flex items-center justify-between"><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-regular fa-calendar-plus"></i></span><?= $formId ? 'Edit Holiday' : 'Add Holiday' ?></h2><p class="text-xs text-slate-400 mt-1 lg:ml-11">Holiday date and title are required.</p></div><a href="/masters/holidays.php" class="rounded-lg border border-slate-200 px-4 py-2.5 text-sm font-semibold"><i class="fa-solid fa-arrow-left mr-2"></i>Back to List</a></div>
    <form method="post" class="p-6 sm:p-8 sm:pb-16"><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="grid grid-cols-1 lg:grid-cols-4 gap-5">
            <label class="block"><span class="block text-[11px] font-extrabold text-slate-700 uppercase mb-2">Date <span class="text-amber-500">*</span></span><input type="date" name="date" required value="<?= h($formDate) ?>" class="w-full rounded-xl border border-slate-200 px-4 py-3 text-sm outline-none focus:border-brand-500 focus:ring-4 focus:ring-brand-100"></label>
            <label class="block lg:col-span-2"><span class="block text-[11px] font-extrabold text-slate-700 uppercase mb-2">Holiday Title <span class="text-amber-500">*</span></span><input type="text" name="description" maxlength="255" required value="<?= h($formDescription) ?>" placeholder="Holiday title" class="w-full rounded-xl border border-slate-200 px-4 py-3 text-sm outline-none focus:border-brand-500 focus:ring-4 focus:ring-brand-100"></label>
            <label class="block"><span class="block text-[11px] font-extrabold text-slate-700 uppercase mb-2">Holiday Type</span><select name="declareph" class="w-full rounded-xl border border-slate-200 px-4 py-3 text-sm bg-white"><?php foreach ([0 => 'Regular (National)', 1 => 'Declare', 2 => 'Undeclare', 3 => 'Optional', 4 => 'Compulsory'] as $value => $label): ?><option value="<?= $value ?>" <?= $formDeclarePh === $value ? 'selected' : '' ?>><?= h($label) ?></option><?php endforeach; ?></select></label>
            <label class="block"><span class="block text-[11px] font-extrabold text-slate-700 uppercase mb-2">Day Type</span><select name="deductiontype" class="w-full rounded-xl border border-slate-200 px-4 py-3 text-sm bg-white"><option value="0" <?= $formDeductionType === 0 ? 'selected' : '' ?>>Full Day</option><option value="1" <?= $formDeductionType === 1 ? 'selected' : '' ?>>Half Day</option></select></label>
            <?php foreach ([['payroll_location','Payroll Locations',$payrollLocationOptions,$formPayrollLocations],['depat','Departments',$departmentOptions,$formDepartments],['empid','Employee Names',$employeeOptions,$formEmployees],['reject_empid','Reject Employee Names',$employeeOptions,$formRejectedEmployees]] as $picker): ?>
            <div class="block lg:col-span-2"><span class="block text-[11px] font-extrabold text-slate-700 uppercase mb-2"><?= h($picker[1]) ?></span><div class="relative js-tag-picker" data-name="<?= h($picker[0]) ?>" data-options='<?= h(json_encode($picker[2], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)) ?>' data-selected='<?= h(json_encode($picker[3])) ?>'><div class="js-picker-control min-h-[48px] w-full rounded-xl border border-slate-200 px-3 py-2 flex flex-wrap items-center gap-2 bg-white focus-within:border-brand-500 focus-within:ring-4 focus-within:ring-brand-100"><div class="js-picker-tags contents"></div><input type="text" class="js-picker-search flex-1 min-w-40 border-0 outline-none text-sm py-1" placeholder="Type or select <?= h(strtolower($picker[1])) ?>" autocomplete="off"></div><div class="js-picker-dropdown hidden absolute left-0 right-0 top-full mt-1 z-40 max-h-56 overflow-y-auto rounded-xl border border-slate-200 bg-white shadow-xl"></div><div class="js-picker-inputs"></div></div></div>
            <?php endforeach; ?>
        </div>
        <div class="mt-7 flex gap-3"><button type="submit" class="inline-flex items-center gap-2 rounded-xl bg-brand-700 hover:bg-brand-800 px-5 py-3 text-sm font-semibold text-white"><i class="fa-solid fa-check"></i>Submit</button><a href="/masters/holidays.php" class="inline-flex items-center gap-2 rounded-xl border border-slate-200 px-5 py-3 text-sm font-semibold text-slate-700"><i class="fa-solid fa-xmark text-slate-400"></i>Cancel</a></div>
    </form>
</section>
<?php endif; ?>

<script>
document.querySelectorAll('.js-tag-picker').forEach(function (picker) {
    const name = picker.dataset.name;
    const options = JSON.parse(picker.dataset.options || '[]');
    const selected = new Set(JSON.parse(picker.dataset.selected || '[]').map(Number));
    const search = picker.querySelector('.js-picker-search');
    const tags = picker.querySelector('.js-picker-tags');
    const dropdown = picker.querySelector('.js-picker-dropdown');
    const inputs = picker.querySelector('.js-picker-inputs');

    function render() {
        tags.innerHTML = '';
        inputs.innerHTML = '';
        options.filter(function (item) { return selected.has(Number(item.id)); }).forEach(function (item) {
            const tag = document.createElement('span');
            tag.className = 'inline-flex items-center gap-1.5 rounded-lg bg-brand-50 px-2.5 py-1.5 text-xs font-semibold text-brand-700';
            tag.textContent = item.name;
            const remove = document.createElement('button');
            remove.type = 'button';
            remove.className = 'text-brand-400 hover:text-red-500';
            remove.innerHTML = '&times;';
            remove.addEventListener('click', function () { selected.delete(Number(item.id)); render(); drawOptions(); });
            tag.appendChild(remove);
            tags.appendChild(tag);
            const hidden = document.createElement('input');
            hidden.type = 'hidden'; hidden.name = name + '[]'; hidden.value = item.id;
            inputs.appendChild(hidden);
        });
    }
    function drawOptions() {
        const term = search.value.trim().toLowerCase();
        dropdown.innerHTML = '<div class="px-4 py-2.5 text-xs font-bold text-slate-500 bg-slate-50">-Select Option-</div>';
        const available = options.filter(function (item) { return !selected.has(Number(item.id)) && item.name.toLowerCase().includes(term); });
        if (!available.length) dropdown.insertAdjacentHTML('beforeend', '<div class="px-4 py-3 text-sm text-slate-400">No options found</div>');
        available.forEach(function (item) {
            const button = document.createElement('button');
            button.type = 'button'; button.className = 'block w-full px-4 py-3 text-left text-sm font-medium text-slate-700 hover:bg-brand-50 hover:text-brand-700'; button.textContent = item.name;
            button.addEventListener('click', function () { selected.add(Number(item.id)); search.value = ''; render(); drawOptions(); search.focus(); });
            dropdown.appendChild(button);
        });
    }
    function open() { drawOptions(); dropdown.classList.remove('hidden'); }
    search.addEventListener('focus', open);
    search.addEventListener('input', open);
    picker.querySelector('.js-picker-control').addEventListener('click', function () { search.focus(); });
    document.addEventListener('click', function (event) { if (!picker.contains(event.target)) dropdown.classList.add('hidden'); });
    render();
});
</script>
<?php console_footer(); ?>
