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

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

$pageLink = 'leave/add-leave-category.php';
$acl = require_acl('can_view', $pageLink);
$errors = [];
$flash = $_SESSION['flash_add_leave_category'] ?? null;
unset($_SESSION['flash_add_leave_category']);

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

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

function alc_columns(mysqli $con, string $table): array
{
    static $cache = [];
    if (isset($cache[$table])) return $cache[$table];
    $allowed = ['jos_app_mleavetype', 'jos_app_mleavetype_editlog'];
    if (!in_array($table, $allowed, true)) return $cache[$table] = [];
    $columns = [];
    $stmt = alc_stmt($con, 'SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=? ORDER BY ORDINAL_POSITION');
    $stmt->bind_param('s', $table);
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) $columns[] = (string)$row['COLUMN_NAME'];
    $stmt->close();
    return $cache[$table] = $columns;
}

function alc_has_column(mysqli $con, string $table, string $column): bool
{
    return in_array($column, alc_columns($con, $table), true);
}

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

function alc_int($value, string $label, array &$errors, int $min = 0, int $max = 999999, bool $required = false): int
{
    $raw = trim((string)$value);
    if ($raw === '') {
        if ($required) $errors[] = $label . ' is required.';
        return 0;
    }
    if (!preg_match('/^\d+$/', $raw)) {
        $errors[] = $label . ' must be a whole number.';
        return 0;
    }
    $number = (int)$raw;
    if ($number < $min || $number > $max) $errors[] = $label . ' must be between ' . $min . ' and ' . $max . '.';
    return $number;
}

function alc_select($value, array $allowed, string $label, array &$errors): int
{
    $number = (int)$value;
    if (!in_array($number, $allowed, true)) $errors[] = 'Select a valid ' . $label . '.';
    return $number;
}

function alc_time(string $value, string $label, array &$errors, bool $required): string
{
    $value = trim($value);
    if ($value === '') {
        if ($required) $errors[] = $label . ' is required.';
        return '';
    }
    if (!preg_match('/^\d{2}:\d{2}(:\d{2})?$/', $value)) {
        $errors[] = $label . ' must be a valid time.';
        return '';
    }
    $date = DateTimeImmutable::createFromFormat(strlen($value) === 5 ? '!H:i' : '!H:i:s', $value);
    if (!$date) {
        $errors[] = $label . ' must be a valid time.';
        return '';
    }
    return $date->format('H:i:s');
}

function alc_csv_ids($value, array $allowedIds): string
{
    $values = is_array($value) ? $value : explode(',', (string)$value);
    $clean = [];
    foreach ($values as $item) {
        $id = (int)$item;
        if ($id > 0 && isset($allowedIds[$id])) $clean[] = (string)$id;
    }
    return implode(',', array_values(array_unique($clean)));
}

function alc_save_row(mysqli $con, int $id, array $data): int
{
    $columns = alc_columns($con, 'jos_app_mleavetype');
    $spec = [
        'type' => 's',
        'cal_type' => 'i',
        'status' => 'i',
        'noofdays' => 'i',
        'afterdays' => 'i',
        'validate_time' => 'i',
        'start_time' => 's',
        'end_time' => 's',
        'blockleave' => 's',
        'document' => 'i',
        'validate' => 'i',
        'staffapp' => 'i',
        'extraleave' => 'i',
        'employment_status' => 's',
    ];
    $fields = [];
    $types = '';
    $params = [];
    foreach ($spec as $field => $type) {
        if (!in_array($field, $columns, true)) continue;
        $fields[] = $field;
        $types .= $type;
        $params[] = $type === 'i' ? (int)$data[$field] : (string)$data[$field];
    }
    if (!$fields) throw new RuntimeException('No leave category fields available.');

    if ($id > 0) {
        $sets = array_map(static fn($field) => '`' . $field . '`=?', $fields);
        $stmt = alc_stmt($con, 'UPDATE jos_app_mleavetype SET ' . implode(',', $sets) . ' WHERE id=?');
        $types .= 'i';
        $params[] = $id;
        $stmt->bind_param($types, ...$params);
        if (!$stmt->execute()) throw new RuntimeException('Unable to update leave category.');
        $stmt->close();
        return $id;
    }

    $stmt = alc_stmt($con, 'INSERT INTO jos_app_mleavetype (`' . implode('`,`', $fields) . '`) VALUES (' . implode(',', array_fill(0, count($fields), '?')) . ')');
    $stmt->bind_param($types, ...$params);
    if (!$stmt->execute()) throw new RuntimeException('Unable to add leave category.');
    $savedId = (int)$con->insert_id;
    $stmt->close();
    return $savedId;
}

function alc_update_status(mysqli $con, int $id, int $status): void
{
    $stmt = alc_stmt($con, 'UPDATE jos_app_mleavetype SET status=? WHERE id=?');
    $stmt->bind_param('ii', $status, $id);
    if (!$stmt->execute()) throw new RuntimeException('Unable to update leave category status.');
    $stmt->close();
}

function alc_insert_history(mysqli $con, int $categoryId): void
{
    $historyColumns = alc_columns($con, 'jos_app_mleavetype_editlog');
    if (!$historyColumns) return;
    $stmt = alc_stmt($con, 'SELECT * FROM jos_app_mleavetype WHERE id=? LIMIT 1');
    $stmt->bind_param('i', $categoryId);
    $stmt->execute();
    $source = $stmt->get_result()->fetch_assoc() ?: [];
    $stmt->close();
    if (!$source) return;

    $userId = (int)(current_user()['id'] ?? 0);
    $fields = [];
    $placeholders = [];
    $types = '';
    $params = [];
    foreach ($historyColumns as $column) {
        if ($column === 'id') continue;
        if ($column === 'mid') {
            $fields[] = $column; $placeholders[] = '?'; $types .= 'i'; $params[] = $categoryId;
        } elseif ($column === 'date' || $column === 'sysdate' || $column === 'modifieddate') {
            $fields[] = $column; $placeholders[] = 'NOW()';
        } elseif ($column === 'modify_by' || $column === 'modified_by' || $column === 'modifed_by' || $column === 'userid') {
            $fields[] = $column; $placeholders[] = '?'; $types .= 'i'; $params[] = $userId;
        } elseif (array_key_exists($column, $source)) {
            $fields[] = $column; $placeholders[] = '?';
            if (is_numeric($source[$column]) && preg_match('/^-?\d+$/', (string)$source[$column])) {
                $types .= 'i'; $params[] = (int)$source[$column];
            } else {
                $types .= 's'; $params[] = (string)$source[$column];
            }
        }
    }
    if (!$fields) return;
    $stmt = alc_stmt($con, 'INSERT INTO jos_app_mleavetype_editlog (`' . implode('`,`', $fields) . '`) VALUES (' . implode(',', $placeholders) . ')');
    if ($types !== '') $stmt->bind_param($types, ...$params);
    if (!$stmt->execute()) throw new RuntimeException('Unable to save leave category history.');
    $stmt->close();
}

function alc_history_rows(mysqli $con, int $categoryId): array
{
    if (!alc_columns($con, 'jos_app_mleavetype_editlog')) return [];
    $order = alc_has_column($con, 'jos_app_mleavetype_editlog', 'date') ? '`date` DESC,id DESC' : 'id DESC';
    $rows = [];
    $stmt = alc_stmt($con, 'SELECT * FROM jos_app_mleavetype_editlog WHERE mid=? ORDER BY ' . $order);
    $stmt->bind_param('i', $categoryId);
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) $rows[] = $row;
    $stmt->close();
    return $rows;
}

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

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

function alc_label(array $labels, $value): string
{
    return $labels[(string)$value] ?? (string)$value;
}

function alc_employment_names(string $csv, array $map): string
{
    $names = [];
    foreach (array_filter(array_map('trim', explode(',', $csv))) as $id) {
        $key = (int)$id;
        if (isset($map[$key])) $names[] = $map[$key];
    }
    return implode(', ', $names);
}

function alc_time_label(string $time): string
{
    $time = trim($time);
    if ($time === '') return '';
    $stamp = strtotime($time);
    return $stamp ? date('h:i a', $stamp) : $time;
}

$dayOptions = alc_options($con, 'SELECT id,day FROM jos_app_mdays ORDER BY id');
$employmentStatuses = alc_options($con, 'SELECT id,status_name FROM jos_app_employment_status ORDER BY id ASC');
$dayMap = [];
$employmentMap = [];
foreach ($dayOptions as $row) $dayMap[(string)$row['day']] = (string)$row['day'];
foreach ($employmentStatuses as $row) $employmentMap[(int)$row['id']] = (string)$row['status_name'];

$yesNoLabels = [0 => 'No', 1 => 'Yes'];
$statusLabels = [0 => 'Active', 1 => 'Inactive'];

$mode = (string)($_GET['mode'] ?? '');
$editId = max(0, (int)($_GET['edit'] ?? 0));
$historyId = max(0, (int)($_GET['history'] ?? 0));
$isHistory = $historyId > 0;
$isForm = !$isHistory && ($mode === 'add' || $editId > 0);
$editRow = null;
$historyParent = null;
$historyRows = [];

if (!$isHistory && $mode === 'add' && empty($acl['can_add'])) {
    $_SESSION['flash_add_leave_category'] = 'You do not have permission to add leave categories.';
    redirect('/leave/add-leave-category.php');
}

if (!$isHistory && $editId > 0 && empty($acl['can_edit'])) {
    $_SESSION['flash_add_leave_category'] = 'You do not have permission to edit leave categories.';
    redirect('/leave/add-leave-category.php');
}

if ($historyId > 0) {
    $stmt = alc_stmt($con, 'SELECT * FROM jos_app_mleavetype WHERE id=? LIMIT 1');
    $stmt->bind_param('i', $historyId);
    $stmt->execute();
    $historyParent = $stmt->get_result()->fetch_assoc() ?: null;
    $stmt->close();
    if (!$historyParent) {
        $_SESSION['flash_add_leave_category'] = 'Leave Category was not found.';
        redirect('/leave/add-leave-category.php');
    }
    $historyRows = alc_history_rows($con, $historyId);
}

if (!$isHistory && $editId > 0) {
    $stmt = alc_stmt($con, 'SELECT * FROM jos_app_mleavetype WHERE id=? LIMIT 1');
    $stmt->bind_param('i', $editId);
    $stmt->execute();
    $editRow = $stmt->get_result()->fetch_assoc() ?: null;
    $stmt->close();
    if (!$editRow) {
        $_SESSION['flash_add_leave_category'] = 'Leave Category was not found.';
        redirect('/leave/add-leave-category.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 leave categories.';
        if ($id === 0 && empty($acl['can_add'])) $errors[] = 'You do not have permission to add leave categories.';
        if ($id > 0 && !alc_exists($con, $id)) $errors[] = 'Leave Category was not found.';

        $type = trim((string)($_POST['type'] ?? ''));
        if ($type === '') $errors[] = 'Leave Category is required.';
        if (strlen($type) > 255) $errors[] = 'Leave Category is too long.';

        $status = alc_select($_POST['status'] ?? 0, [0, 1], 'activate status', $errors);
        $validate = alc_select($_POST['validate'] ?? 0, [0, 1], 'validate leave option', $errors);
        $validateTime = alc_select($_POST['validate_time'] ?? 0, [0, 1], 'validate time option', $errors);
        $document = alc_select($_POST['document'] ?? 0, [0, 1], 'upload document option', $errors);
        $staffapp = alc_select($_POST['staffapp'] ?? 0, [0, 1], 'staff app option', $errors);
        $extraleave = alc_select($_POST['extraleave'] ?? 0, [0, 1], 'extra leave option', $errors);
        $noofdays = $validate === 1 ? alc_int($_POST['noofdays'] ?? '', 'No. of days before current date', $errors, 0, 365, true) : 0;
        $afterdays = $validate === 1 ? alc_int($_POST['afterdays'] ?? '', 'No. of days after current date', $errors, 0, 365, true) : 0;
        $startTime = alc_time((string)($_POST['start_time'] ?? ''), 'Start Time', $errors, $validateTime === 1);
        $endTime = alc_time((string)($_POST['end_time'] ?? ''), 'End Time', $errors, $validateTime === 1);
        if ($validateTime === 0) {
            $startTime = '';
            $endTime = '';
        }

        $blockleave = trim((string)($_POST['blockleave'] ?? ''));
        if ($blockleave !== '' && !isset($dayMap[$blockleave])) $errors[] = 'Select a valid Block Leave day.';
        $employmentStatus = alc_csv_ids($_POST['employment_status'] ?? [], $employmentMap);

        $data = [
            'type' => $type,
            'cal_type' => (int)($editRow['cal_type'] ?? 0),
            'status' => $status,
            'noofdays' => $noofdays,
            'afterdays' => $afterdays,
            'validate_time' => $validateTime,
            'start_time' => $startTime,
            'end_time' => $endTime,
            'blockleave' => $blockleave,
            'document' => $document,
            'validate' => $validate,
            'staffapp' => $staffapp,
            'extraleave' => $extraleave,
            'employment_status' => $employmentStatus,
        ];

        if (!$errors) {
            $con->begin_transaction();
            try {
                $savedId = alc_save_row($con, $id, $data);
                alc_insert_history($con, $savedId);
                $con->commit();
                $_SESSION['flash_add_leave_category'] = $id > 0 ? 'Leave Category updated successfully.' : 'Leave Category added successfully.';
                redirect('/leave/add-leave-category.php');
            } catch (Throwable $e) {
                $con->rollback();
                $errors[] = 'Unable to save the leave category. No changes were committed.';
            }
        }

        $isForm = true;
        $isHistory = false;
        $editId = $id;
        $editRow = $data + ['id' => $id];
    } elseif ($action === 'toggle_status') {
        if (empty($acl['can_delete'])) $errors[] = 'You do not have permission to activate or deactivate leave categories.';
        $id = max(0, (int)($_POST['id'] ?? 0));
        $targetStatus = alc_select($_POST['status'] ?? -1, [0, 1], 'status', $errors);
        if ($id <= 0 || !alc_exists($con, $id)) $errors[] = 'Leave Category was not found.';

        if (!$errors) {
            $con->begin_transaction();
            try {
                alc_update_status($con, $id, $targetStatus);
                alc_insert_history($con, $id);
                $con->commit();
                $_SESSION['flash_add_leave_category'] = $targetStatus === 0 ? 'Leave Category activated successfully.' : 'Leave Category deactivated successfully.';
                redirect('/leave/add-leave-category.php');
            } catch (Throwable $e) {
                $con->rollback();
                $errors[] = 'Unable to update the leave category status. No changes were committed.';
            }
        }
    }
}

$filterQ = trim((string)($_GET['q'] ?? ''));
$filterStatus = isset($_GET['status']) && $_GET['status'] !== '' ? (int)$_GET['status'] : -1;
$filterStaffapp = isset($_GET['staffapp']) && $_GET['staffapp'] !== '' ? (int)$_GET['staffapp'] : -1;
$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = 20;
$totalRows = 0;
$rows = [];
$pages = 1;

if (!$isForm && !$isHistory) {
    $where = ['1=1'];
    $types = '';
    $params = [];
    if ($filterQ !== '') { $where[] = '(c.type LIKE ? OR c.blockleave LIKE ?)'; $types .= 'ss'; $params[] = '%' . $filterQ . '%'; $params[] = '%' . $filterQ . '%'; }
    if (in_array($filterStatus, [0, 1], true)) { $where[] = 'c.status=?'; $types .= 'i'; $params[] = $filterStatus; }
    if (in_array($filterStaffapp, [0, 1], true)) { $where[] = 'c.staffapp=?'; $types .= 'i'; $params[] = $filterStaffapp; }
    $whereSql = implode(' AND ', $where);

    $stmt = alc_stmt($con, 'SELECT COUNT(*) AS total FROM jos_app_mleavetype c 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 = alc_stmt($con, 'SELECT c.*,(SELECT COUNT(*) FROM jos_app_mleavetype_editlog e WHERE e.mid=c.id) AS history_count FROM jos_app_mleavetype c 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();
}

$value = static function (string $key, $default = '') use (&$editRow) { return $editRow[$key] ?? $default; };
$selectedEmployment = array_filter(array_map('intval', explode(',', (string)$value('employment_status'))));
$selectedEmploymentId = (int)($selectedEmployment[0] ?? 0);
$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';
$selectSmall = 'rounded-xl border border-slate-200 px-3 py-2.5 text-sm';

console_header('Add Leave Category', $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>Leave Settings</span><i class="fa-solid fa-chevron-right text-[9px]"></i><span class="text-brand-600">Add Leave Category</span></div><h1 class="text-2xl font-bold text-slate-900">Add Leave Category</h1><p class="mt-1 text-sm text-slate-500">Configure leave category validation windows, time limits, staff app visibility, and employment status applicability.</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 ($isHistory): ?>
<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">Leave Category History</h2><p class="mt-1 text-xs font-medium text-slate-400"><?= h(alc_text($historyParent ?? [], 'type')) ?></p></div><a href="/leave/add-leave-category.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="overflow-x-auto"><table class="w-full min-w-[1320px] 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">Date</th><th class="px-5 py-4">Leave Category</th><th class="px-5 py-4">Status</th><th class="px-5 py-4">Block Leave</th><th class="px-5 py-4">Validate Leave</th><th class="px-5 py-4">Before / After</th><th class="px-5 py-4">Validate Time</th><th class="px-5 py-4">Start / End</th><th class="px-5 py-4">Document</th><th class="px-5 py-4">Staff App</th><th class="px-5 py-4">Extra Leave</th><th class="px-5 py-4">Employment Status</th></tr></thead><tbody class="divide-y divide-slate-100">
    <?php if(!$historyRows): ?><tr><td colspan="12" class="px-6 py-14 text-center font-semibold text-slate-400">No history found.</td></tr><?php endif; ?>
    <?php foreach($historyRows as $row): ?><tr class="align-top hover:bg-slate-50/70"><td class="px-5 py-4 font-semibold text-slate-700"><?= h(alc_text($row, 'date')) ?></td><td class="px-5 py-4 font-bold text-slate-800"><?= h(alc_text($row, 'type')) ?></td><td class="px-5 py-4"><?= h(alc_label($statusLabels, alc_int_row($row, 'status'))) ?></td><td class="px-5 py-4"><?= h(alc_text($row, 'blockleave')) ?></td><td class="px-5 py-4"><?= h(alc_label($yesNoLabels, alc_int_row($row, 'validate'))) ?></td><td class="px-5 py-4"><?= h(alc_text($row, 'noofdays')) ?> / <?= h(alc_text($row, 'afterdays')) ?></td><td class="px-5 py-4"><?= h(alc_label($yesNoLabels, alc_int_row($row, 'validate_time'))) ?></td><td class="px-5 py-4"><?= h(alc_time_label(alc_text($row, 'start_time'))) ?> / <?= h(alc_time_label(alc_text($row, 'end_time'))) ?></td><td class="px-5 py-4"><?= h(alc_label($yesNoLabels, alc_int_row($row, 'document'))) ?></td><td class="px-5 py-4"><?= h(alc_label($yesNoLabels, alc_int_row($row, 'staffapp'))) ?></td><td class="px-5 py-4"><?= h(alc_label($yesNoLabels, alc_int_row($row, 'extraleave'))) ?></td><td class="px-5 py-4"><?= h(alc_employment_names(alc_text($row, 'employment_status'), $employmentMap)) ?></td></tr><?php endforeach; ?>
  </tbody></table></div>
</section>
<?php elseif ($isForm): ?>
<form method="post" id="leave-category-form" class="space-y-4">
  <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-person-walking-arrow-right"></i></span><div><h2 class="font-bold text-slate-800"><?= (int)$value('id',0)>0?'Edit Leave Category':'New Leave Category' ?></h2><p class="text-xs text-slate-400">Fields marked with * are required.</p></div></div><a href="/leave/add-leave-category.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-4">
      <label class="text-sm font-semibold text-slate-700">Leave Category *<input name="type" required maxlength="255" value="<?= h((string)$value('type')) ?>" class="<?= $input ?>" placeholder="CL - Casual Leave"></label>
      <label class="text-sm font-semibold text-slate-700">Activate Status<select name="status" class="<?= $input ?>"><?php foreach($statusLabels as $k=>$label): ?><option value="<?= $k ?>" <?= (int)$value('status',0)===$k?'selected':'' ?>><?= h($label) ?></option><?php endforeach; ?></select></label>
      <label class="text-sm font-semibold text-slate-700">Validate Leave<select name="validate" class="<?= $input ?> js-validate-leave"><?php foreach($yesNoLabels as $k=>$label): ?><option value="<?= $k ?>" <?= (int)$value('validate',0)===$k?'selected':'' ?>><?= h($label) ?></option><?php endforeach; ?></select></label>
      <div class="hidden md:block"></div>
      <label class="text-sm font-semibold text-slate-700">Validate Time<select name="validate_time" class="<?= $input ?> js-validate-time"><?php foreach($yesNoLabels as $k=>$label): ?><option value="<?= $k ?>" <?= (int)$value('validate_time',0)===$k?'selected':'' ?>><?= h($label) ?></option><?php endforeach; ?></select></label>
      <label class="text-sm font-semibold text-slate-700">Block Leave<select name="blockleave" class="<?= $input ?>"><option value="">Select Option</option><?php foreach($dayOptions as $option): ?><option value="<?= h($option['day']) ?>" <?= (string)$value('blockleave')===(string)$option['day']?'selected':'' ?>><?= h($option['day']) ?></option><?php endforeach; ?></select></label>
      <label class="text-sm font-semibold text-slate-700">Upload Document<select name="document" class="<?= $input ?>"><?php foreach($yesNoLabels as $k=>$label): ?><option value="<?= $k ?>" <?= (int)$value('document',0)===$k?'selected':'' ?>><?= h($label) ?></option><?php endforeach; ?></select></label>
      <label class="text-sm font-semibold text-slate-700">Activate In Staff App<select name="staffapp" class="<?= $input ?>"><?php foreach($yesNoLabels as $k=>$label): ?><option value="<?= $k ?>" <?= (int)$value('staffapp',0)===$k?'selected':'' ?>><?= h($label) ?></option><?php endforeach; ?></select></label>
      <label class="text-sm font-semibold text-slate-700">Extra Leave<select name="extraleave" class="<?= $input ?>"><?php foreach($yesNoLabels as $k=>$label): ?><option value="<?= $k ?>" <?= (int)$value('extraleave',0)===$k?'selected':'' ?>><?= h($label) ?></option><?php endforeach; ?></select></label>
      <label class="text-sm font-semibold text-slate-700 md:col-span-2">Applicable for Employment Status<select name="employment_status[]" class="<?= $input ?>"><option value="">Select Option</option><?php foreach($employmentStatuses as $option): ?><option value="<?= (int)$option['id'] ?>" <?= $selectedEmploymentId===(int)$option['id']?'selected':'' ?>><?= h($option['status_name']) ?></option><?php endforeach; ?></select></label>
      <div class="hidden md:block"></div>
      <label class="text-sm font-semibold text-slate-700 js-validate-days">No. of days before current date<input name="noofdays" inputmode="numeric" value="<?= h((string)$value('noofdays',0)) ?>" class="<?= $input ?>" placeholder="0"></label>
      <label class="text-sm font-semibold text-slate-700 js-validate-days">No. of days after current date<input name="afterdays" inputmode="numeric" value="<?= h((string)$value('afterdays',0)) ?>" class="<?= $input ?>" placeholder="0"></label>
      <label class="text-sm font-semibold text-slate-700 js-time-field">Start Time<input type="time" name="start_time" value="<?= h(substr((string)$value('start_time'), 0, 5)) ?>" class="<?= $input ?>"></label>
      <label class="text-sm font-semibold text-slate-700 js-time-field">End Time<input type="time" name="end_time" value="<?= h(substr((string)$value('end_time'), 0, 5)) ?>" class="<?= $input ?>"></label>
    </div>
  </section>
  <div class="flex flex-wrap justify-end gap-2"><a href="/leave/add-leave-category.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 Category</button></div>
</form>
<script>(()=>{const v=document.querySelector('.js-validate-leave'),t=document.querySelector('.js-validate-time');const sync=()=>{document.querySelectorAll('.js-validate-days').forEach(el=>{el.style.display=v&&v.value==='1'?'':'none';el.querySelector('input').required=v&&v.value==='1';});document.querySelectorAll('.js-time-field').forEach(el=>{el.style.display=t&&t.value==='1'?'':'none';el.querySelector('input').required=t&&t.value==='1';});};if(v)v.addEventListener('change',sync);if(t)t.addEventListener('change',sync);sync();})();</script>
<?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">Leave Category List</h2><p class="mt-1 text-xs font-medium text-slate-400">Leave categories 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-5"><input name="q" value="<?= h($filterQ) ?>" class="<?= $selectSmall ?>" placeholder="Search category or day"><select name="status" class="<?= $selectSmall ?>"><option value="">All Status</option><?php foreach($statusLabels as $k=>$label): ?><option value="<?= $k ?>" <?= $filterStatus===$k?'selected':'' ?>><?= h($label) ?></option><?php endforeach; ?></select><select name="staffapp" class="<?= $selectSmall ?>"><option value="">All Staff App</option><?php foreach($yesNoLabels as $k=>$label): ?><option value="<?= $k ?>" <?= $filterStaffapp===$k?'selected':'' ?>>Staff App: <?= h($label) ?></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="/leave/add-leave-category.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-[1460px] 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">Leave Category</th><th class="px-5 py-4">Status</th><th class="px-5 py-4">Block Leave</th><th class="px-5 py-4">Before Days</th><th class="px-5 py-4">After Days</th><th class="px-5 py-4">Start Time</th><th class="px-5 py-4">End Time</th><th class="px-5 py-4">Staff App</th><th class="px-5 py-4">Document</th><th class="px-5 py-4">Extra Leave</th><th class="px-5 py-4">Employment Status</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="13" class="px-6 py-14 text-center font-semibold text-slate-400">No leave categories found.</td></tr><?php endif; ?>
    <?php foreach($rows as $index=>$row): ?>
      <?php $rowStatus = alc_int_row($row, 'status'); $nextStatus = $rowStatus === 0 ? 1 : 0; ?>
      <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"><div class="font-bold text-slate-800"><?= h(alc_text($row, 'type')) ?></div><?php if(alc_int_row($row, 'history_count')>1): ?><div class="mt-1 text-xs font-semibold text-slate-400">History <?= alc_int_row($row, 'history_count') ?></div><?php endif; ?></td>
        <td class="px-5 py-4"><span class="rounded-full <?= $rowStatus===0?'bg-emerald-50 text-emerald-700':'bg-slate-100 text-slate-600' ?> px-3 py-1 text-xs font-bold"><?= h(alc_label($statusLabels, $rowStatus)) ?></span></td>
        <td class="px-5 py-4"><?= h(alc_text($row, 'blockleave')) ?></td>
        <td class="px-5 py-4"><?= h(alc_text($row, 'noofdays')) ?></td>
        <td class="px-5 py-4"><?= h(alc_text($row, 'afterdays')) ?></td>
        <td class="px-5 py-4"><?= h(alc_time_label(alc_text($row, 'start_time'))) ?></td>
        <td class="px-5 py-4"><?= h(alc_time_label(alc_text($row, 'end_time'))) ?></td>
        <td class="px-5 py-4"><?= h(alc_label($yesNoLabels, alc_int_row($row, 'staffapp'))) ?></td>
        <td class="px-5 py-4"><?= h(alc_label($yesNoLabels, alc_int_row($row, 'document'))) ?></td>
        <td class="px-5 py-4"><?= alc_int_row($row, 'extraleave')===1?'Yes':'' ?></td>
        <td class="px-5 py-4"><?= h(alc_employment_names(alc_text($row, 'employment_status'), $employmentMap)) ?></td>
        <td class="px-5 py-4">
          <div class="flex justify-end gap-2">
            <?php if(alc_int_row($row, 'history_count')>1): ?><a href="?history=<?= alc_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="History"><i class="fa-solid fa-eye"></i></a><?php endif; ?>
            <?php if(!empty($acl['can_edit'])): ?><a href="?edit=<?= alc_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('<?= $nextStatus === 0 ? 'Activate' : 'Deactivate' ?> this leave category?');">
                <input type="hidden" name="_csrf" value="<?= h(csrf_token()) ?>">
                <input type="hidden" name="action" value="toggle_status">
                <input type="hidden" name="id" value="<?= alc_int_row($row, 'id') ?>">
                <input type="hidden" name="status" value="<?= $nextStatus ?>">
                <button type="submit" class="rounded-lg border border-slate-200 px-3 py-2 <?= $rowStatus===0?'text-amber-600 hover:bg-amber-50':'text-emerald-600 hover:bg-emerald-50' ?>" title="<?= $rowStatus===0?'Deactivate':'Activate' ?>"><i class="fa-solid <?= $rowStatus===0?'fa-ban':'fa-circle-check' ?>"></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 ?> categories</span><div class="flex gap-2"><?php $base=['q'=>$filterQ,'status'=>$filterStatus>=0?$filterStatus:'','staffapp'=>$filterStaffapp>=0?$filterStaffapp:'']; 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 console_footer(); ?>
