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

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

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

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

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

function lcfg_columns(mysqli $con, string $table): array
{
    static $cache = [];
    if (isset($cache[$table])) return $cache[$table];
    $allowed = ['jos_app_leave_config', 'jos_app_leave_config_editlog'];
    if (!in_array($table, $allowed, true)) return $cache[$table] = [];
    $columns = [];
    $stmt = lcfg_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 lcfg_has_column(mysqli $con, string $table, string $column): bool
{
    return in_array($column, lcfg_columns($con, $table), true);
}

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

function lcfg_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 lcfg_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 lcfg_save_row(mysqli $con, int $id, array $data): int
{
    $columns = lcfg_columns($con, 'jos_app_leave_config');
    $spec = [
        'compoff_obmonth' => 'i',
        'compoff_nofdays' => 'i',
        'approveday' => 'i',
        'org' => 'i',
        'leavetype' => 'i',
        'forward' => 'i',
        'forwardmonth' => 'i',
        'year_slab' => 'i',
        'carryforward' => 'i',
    ];
    $fields = [];
    $types = '';
    $params = [];
    foreach ($spec as $field => $type) {
        if (!in_array($field, $columns, true)) continue;
        $fields[] = $field;
        $types .= $type;
        $params[] = (int)$data[$field];
    }
    if (!$fields) throw new RuntimeException('No leave configuration fields available.');

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

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

function lcfg_delete_row(mysqli $con, int $id): void
{
    $stmt = lcfg_stmt($con, 'DELETE FROM jos_app_leave_config_editlog WHERE leaveid=?');
    $stmt->bind_param('i', $id);
    if (!$stmt->execute()) throw new RuntimeException('Unable to delete leave configuration history.');
    $stmt->close();

    $stmt = lcfg_stmt($con, 'DELETE FROM jos_app_leave_config WHERE id=?');
    $stmt->bind_param('i', $id);
    if (!$stmt->execute()) throw new RuntimeException('Unable to delete leave configuration.');
    $stmt->close();
}

function lcfg_insert_history(mysqli $con, int $configId): void
{
    $historyColumns = lcfg_columns($con, 'jos_app_leave_config_editlog');
    if (!$historyColumns) return;

    $stmt = lcfg_stmt($con, 'SELECT * FROM jos_app_leave_config WHERE id=? LIMIT 1');
    $stmt->bind_param('i', $configId);
    $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 === 'leaveid') {
            $fields[] = $column; $placeholders[] = '?'; $types .= 'i'; $params[] = $configId;
        } elseif ($column === 'date') {
            $fields[] = $column; $placeholders[] = 'NOW()';
        } elseif ($column === 'modify_by') {
            $fields[] = $column; $placeholders[] = '?'; $types .= 'i'; $params[] = $userId;
        } elseif (array_key_exists($column, $source)) {
            $fields[] = $column; $placeholders[] = '?'; $types .= 'i'; $params[] = (int)$source[$column];
        }
    }
    if (!$fields) return;
    $stmt = lcfg_stmt($con, 'INSERT INTO jos_app_leave_config_editlog (`' . implode('`,`', $fields) . '`) VALUES (' . implode(',', $placeholders) . ')');
    if ($types !== '') $stmt->bind_param($types, ...$params);
    if (!$stmt->execute()) throw new RuntimeException('Unable to save leave configuration history.');
    $stmt->close();
}

function lcfg_history_rows(mysqli $con, int $configId): array
{
    if (!lcfg_columns($con, 'jos_app_leave_config_editlog')) return [];
    $order = lcfg_has_column($con, 'jos_app_leave_config_editlog', 'date') ? '`date` DESC,id DESC' : 'id DESC';
    $rows = [];
    $stmt = lcfg_stmt($con, 'SELECT * FROM jos_app_leave_config_editlog WHERE leaveid=? ORDER BY ' . $order);
    $stmt->bind_param('i', $configId);
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) $rows[] = $row;
    $stmt->close();
    return $rows;
}

function lcfg_text(array $row, string $key, string $default = ''): string
{
    return isset($row[$key]) ? (string)$row[$key] : $default;
}

function lcfg_int_row(array $row, string $key, int $default = 0): int
{
    return isset($row[$key]) ? (int)$row[$key] : $default;
}

function lcfg_label(array $map, int $key, string $default = ''): string
{
    return $map[$key] ?? $default;
}

$yesNo = [0 => 'No', 1 => 'Yes'];
$forwardLabels = [0 => 'No', 1 => 'Yes'];
$yearSlabs = [1 => 'January - December', 2 => 'April - March'];

$payrollLocations = lcfg_options($con, 'SELECT id,name FROM jos_app_payrolllocation ORDER BY name ASC');
$leaveTypes = lcfg_options($con, 'SELECT id,type FROM jos_app_mleavetype WHERE status=0 ORDER BY type ASC');
$payrollMap = [];
foreach ($payrollLocations as $row) $payrollMap[(int)$row['id']] = (string)$row['name'];
$leaveTypeMap = [];
foreach ($leaveTypes as $row) $leaveTypeMap[(int)$row['id']] = (string)$row['type'];

$isForm = ($_GET['mode'] ?? '') === 'add';
$isHistory = false;
$editId = isset($_GET['edit']) ? max(0, (int)$_GET['edit']) : 0;
$historyId = isset($_GET['history']) ? max(0, (int)$_GET['history']) : 0;
$editRow = [
    'id' => 0,
    'org' => '',
    'leavetype' => '',
    'forward' => 0,
    'year_slab' => 1,
    'carryforward' => 0,
    'forwardmonth' => 0,
    'compoff_obmonth' => 0,
    'compoff_nofdays' => 0,
    'approveday' => 0,
];
$historyRows = [];
$historyParent = null;

if ($editId > 0) {
    $isForm = true;
    $stmt = lcfg_stmt($con, 'SELECT * FROM jos_app_leave_config WHERE id=? LIMIT 1');
    $stmt->bind_param('i', $editId);
    $stmt->execute();
    $editRow = $stmt->get_result()->fetch_assoc() ?: [];
    $stmt->close();
    if (!$editRow) {
        $_SESSION['flash_leave_configuration'] = 'Leave Configuration was not found.';
        redirect('/leave/leave-configuration.php');
    }
    if (!isset($leaveTypeMap[(int)$editRow['leavetype']]) && (int)$editRow['leavetype'] > 0) {
        $stmt = lcfg_stmt($con, 'SELECT id,type FROM jos_app_mleavetype WHERE id=? LIMIT 1');
        $lt = (int)$editRow['leavetype'];
        $stmt->bind_param('i', $lt);
        $stmt->execute();
        if ($row = $stmt->get_result()->fetch_assoc()) $leaveTypeMap[(int)$row['id']] = (string)$row['type'];
        $stmt->close();
    }
}

if ($historyId > 0) {
    $isHistory = true;
    $stmt = lcfg_stmt($con, 'SELECT * FROM jos_app_leave_config WHERE id=? LIMIT 1');
    $stmt->bind_param('i', $historyId);
    $stmt->execute();
    $historyParent = $stmt->get_result()->fetch_assoc() ?: null;
    $stmt->close();
    if (!$historyParent) {
        $_SESSION['flash_leave_configuration'] = 'Leave Configuration was not found.';
        redirect('/leave/leave-configuration.php');
    }
    $historyRows = lcfg_history_rows($con, $historyId);
}

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

        $org = lcfg_int($_POST['org'] ?? '', 'Payroll Location', $errors, 1, 999999, true);
        if ($org > 0 && !isset($payrollMap[$org])) $errors[] = 'Select a valid Payroll Location.';
        $leaveType = lcfg_int($_POST['leavetype'] ?? '', 'Leave Category', $errors, 1, 999999, true);
        if ($leaveType > 0 && !isset($leaveTypeMap[$leaveType])) $errors[] = 'Select a valid Leave Category.';
        $forward = lcfg_select($_POST['forward'] ?? 0, [0, 1], 'Carry Forward option', $errors);
        $yearSlab = $forward === 0 ? lcfg_select($_POST['year_slab'] ?? 1, [1, 2], 'Year Slab', $errors) : 0;
        $carryForward = ($forward === 1 && isset($_POST['carryforward'])) ? 1 : 0;
        $forwardMonth = ($forward === 1 && $carryForward === 1) ? lcfg_int($_POST['forwardmonth'] ?? '', 'Forward No. of Month', $errors, 0, 120, true) : 0;

        $data = [
            'org' => $org,
            'leavetype' => $leaveType,
            'forward' => $forward,
            'year_slab' => $yearSlab,
            'carryforward' => $carryForward,
            'forwardmonth' => $forwardMonth,
            'compoff_obmonth' => (int)($editRow['compoff_obmonth'] ?? 0),
            'compoff_nofdays' => (int)($editRow['compoff_nofdays'] ?? 0),
            'approveday' => (int)($editRow['approveday'] ?? 0),
        ];

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

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

$filterQ = trim((string)($_GET['q'] ?? ''));
$filterForward = isset($_GET['forward']) && $_GET['forward'] !== '' ? (int)$_GET['forward'] : -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[] = '(pl.name LIKE ? OR lt.type LIKE ?)';
        $types .= 'ss';
        $params[] = '%' . $filterQ . '%';
        $params[] = '%' . $filterQ . '%';
    }
    if (in_array($filterForward, [0, 1], true)) {
        $where[] = 'c.forward=?';
        $types .= 'i';
        $params[] = $filterForward;
    }
    $whereSql = implode(' AND ', $where);

    $stmt = lcfg_stmt($con, 'SELECT COUNT(*) AS total FROM jos_app_leave_config c LEFT JOIN jos_app_payrolllocation pl ON pl.id=c.org LEFT JOIN jos_app_mleavetype lt ON lt.id=c.leavetype 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 = lcfg_stmt($con, 'SELECT c.*,pl.name AS payroll_location_name,lt.type AS leave_type_name,(SELECT COUNT(*) FROM jos_app_leave_config_editlog e WHERE e.leaveid=c.id) AS history_count FROM jos_app_leave_config c LEFT JOIN jos_app_payrolllocation pl ON pl.id=c.org LEFT JOIN jos_app_mleavetype lt ON lt.id=c.leavetype 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; };
$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('Leave 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>Leave Settings</span><i class="fa-solid fa-chevron-right text-[9px]"></i><span class="text-brand-600">Leave Configuration</span></div>
    <h1 class="text-2xl font-bold text-slate-900">Leave Configuration</h1>
    <p class="mt-1 text-sm text-slate-500">Configure leave category carry-forward rules by payroll location.</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 Configuration History</h2><p class="mt-1 text-xs font-medium text-slate-400"><?= h($payrollMap[lcfg_int_row($historyParent ?? [], 'org')] ?? '') ?> - <?= h($leaveTypeMap[lcfg_int_row($historyParent ?? [], 'leavetype')] ?? '') ?></p></div><a href="/leave/leave-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="overflow-x-auto"><table class="w-full min-w-[1100px] 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">Payroll Location</th><th class="px-5 py-4">Leave Category</th><th class="px-5 py-4">Carry Forward</th><th class="px-5 py-4">Year Slab</th><th class="px-5 py-4">Carry Forward Specified</th><th class="px-5 py-4">Forward Month</th><th class="px-5 py-4">Modified By</th></tr></thead><tbody class="divide-y divide-slate-100">
    <?php if(!$historyRows): ?><tr><td colspan="8" 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(lcfg_text($row, 'date')) ?></td><td class="px-5 py-4"><?= h($payrollMap[lcfg_int_row($row, 'org')] ?? '') ?></td><td class="px-5 py-4 font-bold text-slate-800"><?= h($leaveTypeMap[lcfg_int_row($row, 'leavetype')] ?? '') ?></td><td class="px-5 py-4"><?= h(lcfg_label($forwardLabels, lcfg_int_row($row, 'forward'))) ?></td><td class="px-5 py-4"><?= h(lcfg_label($yearSlabs, lcfg_int_row($row, 'year_slab'))) ?></td><td class="px-5 py-4"><?= h(lcfg_label($yesNo, lcfg_int_row($row, 'carryforward'))) ?></td><td class="px-5 py-4"><?= h(lcfg_text($row, 'forwardmonth')) ?></td><td class="px-5 py-4"><?= (int)lcfg_int_row($row, 'modify_by') ?></td></tr><?php endforeach; ?>
  </tbody></table></div>
</section>
<?php elseif ($isForm): ?>
<form method="post" id="leave-configuration-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-clipboard-list"></i></span><div><h2 class="font-bold text-slate-800"><?= (int)$value('id',0)>0?'Edit Leave Configuration':'New Leave Configuration' ?></h2><p class="text-xs text-slate-400">Fields marked with * are required.</p></div></div><a href="/leave/leave-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-4">
      <label class="text-sm font-semibold text-slate-700">Payroll Location *<select name="org" required class="<?= $input ?>"><option value="">Select Payroll Location</option><?php foreach($payrollLocations as $option): ?><option value="<?= (int)$option['id'] ?>" <?= (int)$value('org')===(int)$option['id']?'selected':'' ?>><?= h($option['name']) ?></option><?php endforeach; ?></select></label>
      <label class="text-sm font-semibold text-slate-700">Leave Category *<select name="leavetype" required class="<?= $input ?>"><option value="">Select Option</option><?php foreach($leaveTypeMap as $id=>$label): ?><option value="<?= (int)$id ?>" <?= (int)$value('leavetype')===(int)$id?'selected':'' ?>><?= h($label) ?></option><?php endforeach; ?></select></label>
      <label class="text-sm font-semibold text-slate-700">Carry Forward<select name="forward" class="<?= $input ?> js-forward"><?php foreach($forwardLabels as $k=>$label): ?><option value="<?= $k ?>" <?= (int)$value('forward',0)===$k?'selected':'' ?>><?= h($label) ?></option><?php endforeach; ?></select></label>
      <label class="text-sm font-semibold text-slate-700 js-year-slab">Year Slab<select name="year_slab" class="<?= $input ?>"><?php foreach($yearSlabs as $k=>$label): ?><option value="<?= $k ?>" <?= (int)$value('year_slab',1)===$k?'selected':'' ?>><?= h($label) ?></option><?php endforeach; ?></select></label>
      <label class="text-sm font-semibold text-slate-700 js-carry-specified"><span class="block">Carry Forward Specified</span><span class="mt-1 flex h-[41px] items-center rounded-lg border border-slate-200 bg-white px-3"><input type="checkbox" name="carryforward" value="1" class="h-4 w-4 rounded border-slate-300 text-brand-600" <?= (int)$value('carryforward')===1?'checked':'' ?>></span></label>
      <label class="text-sm font-semibold text-slate-700 js-forward-month">Forward No. of Month<input type="number" min="0" max="120" name="forwardmonth" value="<?= h((string)$value('forwardmonth',0)) ?>" class="<?= $input ?>" placeholder="0"></label>
    </div>
  </section>
  <div class="flex flex-wrap justify-end gap-2"><a href="/leave/leave-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>
<script>(()=>{const forward=document.querySelector('.js-forward'),carry=document.querySelector('input[name="carryforward"]'),year=document.querySelector('.js-year-slab'),specified=document.querySelector('.js-carry-specified'),month=document.querySelector('.js-forward-month');const sync=()=>{const yes=forward&&forward.value==='1';if(year)year.style.display=yes?'none':'';if(specified)specified.style.display=yes?'':'none';if(month)month.style.display=yes&&carry&&carry.checked?'':'none';const monthInput=month?month.querySelector('input'):null;if(monthInput)monthInput.required=!!(yes&&carry&&carry.checked);};if(forward)forward.addEventListener('change',sync);if(carry)carry.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 Configuration List</h2><p class="mt-1 text-xs font-medium text-slate-400">Leave 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-5"><input name="q" value="<?= h($filterQ) ?>" class="<?= $selectSmall ?>" placeholder="Search location or category"><select name="forward" class="<?= $selectSmall ?>"><option value="">All Carry Forward</option><?php foreach($forwardLabels as $k=>$label): ?><option value="<?= $k ?>" <?= $filterForward===$k?'selected':'' ?>>Carry Forward: <?= h($label) ?></option><?php endforeach; ?></select><div class="flex gap-2 xl:col-span-3"><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/leave-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-[1180px] 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">Payroll Location</th><th class="px-5 py-4">Leave Category</th><th class="px-5 py-4">Carry Forward</th><th class="px-5 py-4">Year Slab</th><th class="px-5 py-4">Carry Forward Specified</th><th class="px-5 py-4">Forward Month</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="8" class="px-6 py-14 text-center font-semibold text-slate-400">No leave 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(lcfg_text($row, 'payroll_location_name')) ?></td><td class="px-5 py-4"><?= h(lcfg_text($row, 'leave_type_name')) ?><?php if(lcfg_int_row($row, 'history_count')>1): ?><div class="mt-1 text-xs font-semibold text-slate-400">History <?= lcfg_int_row($row, 'history_count') ?></div><?php endif; ?></td><td class="px-5 py-4"><?= h(lcfg_label($forwardLabels, lcfg_int_row($row, 'forward'))) ?></td><td class="px-5 py-4"><?= h(lcfg_label($yearSlabs, lcfg_int_row($row, 'year_slab'))) ?></td><td class="px-5 py-4"><?= h(lcfg_label($yesNo, lcfg_int_row($row, 'carryforward'))) ?></td><td class="px-5 py-4"><?= h(lcfg_text($row, 'forwardmonth')) ?></td><td class="px-5 py-4"><div class="flex justify-end gap-2"><?php if(lcfg_int_row($row, 'history_count')>1): ?><a href="?history=<?= lcfg_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=<?= lcfg_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 leave configuration?');"><input type="hidden" name="_csrf" value="<?= h(csrf_token()) ?>"><input type="hidden" name="action" value="delete"><input type="hidden" name="id" value="<?= lcfg_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,'forward'=>$filterForward>=0?$filterForward:'']; 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(); ?>
