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

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

$pageLink = 'attendance/login-time-allowance-slab.php';
$acl = require_acl('can_view', $pageLink);
$errors = [];
$flash = $_SESSION['flash_login_time_allowance_slab'] ?? null;
unset($_SESSION['flash_login_time_allowance_slab']);

function asc_stmt(mysqli $con, string $sql): mysqli_stmt
{
    $stmt = $con->prepare($sql);
    if (!$stmt) throw new RuntimeException('Unable to prepare login time allowance slab query.');
    return $stmt;
}

function asc_options(mysqli $con, string $sql): array
{
    $rows = [];
    $result = $con->query($sql);
    if ($result) {
        while ($row = $result->fetch_assoc()) $rows[] = $row;
        $result->free();
    }
    return $rows;
}

function asc_columns(mysqli $con, string $table): array
{
    static $cache = [];
    if (isset($cache[$table])) return $cache[$table];
    $safeTable = preg_replace('/[^A-Za-z0-9_]/', '', $table);
    $columns = [];
    $result = $con->query('SHOW COLUMNS FROM `' . $safeTable . '`');
    if ($result) {
        while ($row = $result->fetch_assoc()) $columns[] = (string)$row['Field'];
        $result->free();
    }
    return $cache[$table] = $columns;
}

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

function asc_valid_id(mysqli $con, string $table, int $id): bool
{
    $allowed = ['jos_app_mmonth', 'jos_app_year'];
    if ($id <= 0 || !in_array($table, $allowed, true)) return false;
    $stmt = asc_stmt($con, 'SELECT id FROM `' . $table . '` WHERE id=? LIMIT 1');
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $valid = (bool)$stmt->get_result()->fetch_assoc();
    $stmt->close();
    return $valid;
}

function asc_decimal($value, string $label, array &$errors, float $max = 9999999.99): string
{
    $raw = trim((string)$value);
    if ($raw === '') {
        $errors[] = $label . ' is required.';
        return '0';
    }
    if (!preg_match('/^\d+(\.\d{1,2})?$/', $raw)) {
        $errors[] = $label . ' must be a valid non-negative number.';
        return '0';
    }
    $number = (float)$raw;
    if ($number > $max) $errors[] = $label . ' is outside the allowed range.';
    return rtrim(rtrim(number_format($number, 2, '.', ''), '0'), '.');
}

function asc_int_value($value, string $label, array &$errors, int $min = 0, int $max = 9999): int
{
    $raw = trim((string)$value);
    if ($raw === '') {
        $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 asc_slab_exists(mysqli $con, int $id): bool
{
    $stmt = asc_stmt($con, 'SELECT id FROM jos_app_loginllowslab WHERE id=? LIMIT 1');
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $exists = (bool)$stmt->get_result()->fetch_assoc();
    $stmt->close();
    return $exists;
}

function asc_slab_rows(mysqli $con, int $slabId): array
{
    $rows = [];
    $stmt = asc_stmt($con, 'SELECT id,sr_no,slabid,presentday,amount FROM jos_app_loginllowslab_grid WHERE slabid=? ORDER BY presentday ASC,sr_no ASC,id ASC');
    $stmt->bind_param('i', $slabId);
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) $rows[] = $row;
    $stmt->close();
    return $rows;
}

function asc_total_month_days(mysqli $con, int $month, int $year): int
{
    $stmt = asc_stmt($con, 'SELECT year FROM jos_app_year WHERE id=? LIMIT 1');
    $stmt->bind_param('i', $year);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    $yearValue = (int)($row['year'] ?? date('Y'));
    return cal_days_in_month(CAL_GREGORIAN, max(1, min(12, $month)), $yearValue);
}

function asc_save_parent(mysqli $con, int $id, string $policyName, int $month, int $year, int $totalDays): int
{
    $userId = (int)(current_user()['id'] ?? 0);
    $hasTotal = asc_has_column($con, 'jos_app_loginllowslab', 'total_month_days');
    $hasUser = asc_has_column($con, 'jos_app_loginllowslab', 'userid');
    if ($id > 0) {
        if ($hasTotal && $hasUser) {
            $stmt = asc_stmt($con, 'UPDATE jos_app_loginllowslab SET policyname=?,month=?,year=?,total_month_days=?,userid=? WHERE id=?');
            $stmt->bind_param('siiiii', $policyName, $month, $year, $totalDays, $userId, $id);
        } elseif ($hasTotal) {
            $stmt = asc_stmt($con, 'UPDATE jos_app_loginllowslab SET policyname=?,month=?,year=?,total_month_days=? WHERE id=?');
            $stmt->bind_param('siiii', $policyName, $month, $year, $totalDays, $id);
        } elseif ($hasUser) {
            $stmt = asc_stmt($con, 'UPDATE jos_app_loginllowslab SET policyname=?,month=?,year=?,userid=? WHERE id=?');
            $stmt->bind_param('siiii', $policyName, $month, $year, $userId, $id);
        } else {
            $stmt = asc_stmt($con, 'UPDATE jos_app_loginllowslab SET policyname=?,month=?,year=? WHERE id=?');
            $stmt->bind_param('siii', $policyName, $month, $year, $id);
        }
        if (!$stmt->execute()) throw new RuntimeException('Unable to update login time allowance slab policy.');
        $stmt->close();
        return $id;
    }

    if ($hasTotal && $hasUser) {
        $stmt = asc_stmt($con, 'INSERT INTO jos_app_loginllowslab (policyname,month,year,total_month_days,userid) VALUES (?,?,?,?,?)');
        $stmt->bind_param('siiii', $policyName, $month, $year, $totalDays, $userId);
    } elseif ($hasTotal) {
        $stmt = asc_stmt($con, 'INSERT INTO jos_app_loginllowslab (policyname,month,year,total_month_days) VALUES (?,?,?,?)');
        $stmt->bind_param('siii', $policyName, $month, $year, $totalDays);
    } elseif ($hasUser) {
        $stmt = asc_stmt($con, 'INSERT INTO jos_app_loginllowslab (policyname,month,year,userid) VALUES (?,?,?,?)');
        $stmt->bind_param('siii', $policyName, $month, $year, $userId);
    } else {
        $stmt = asc_stmt($con, 'INSERT INTO jos_app_loginllowslab (policyname,month,year) VALUES (?,?,?)');
        $stmt->bind_param('sii', $policyName, $month, $year);
    }
    if (!$stmt->execute()) throw new RuntimeException('Unable to add login time allowance slab policy.');
    $newId = (int)$con->insert_id;
    $stmt->close();
    return $newId;
}

$months = asc_options($con, 'SELECT id,month AS name FROM jos_app_mmonth ORDER BY id');
$years = asc_options($con, 'SELECT id,year AS name,assessment FROM jos_app_year ORDER BY id DESC');
$monthMap = $yearMap = [];
foreach ($months as $row) $monthMap[(int)$row['id']] = (string)$row['name'];
foreach ($years as $row) $yearMap[(int)$row['id']] = (string)$row['name'];

$mode = (string)($_GET['mode'] ?? '');
$editId = max(0, (int)($_GET['edit'] ?? 0));
$isForm = $mode === 'add' || $editId > 0;
$editRow = null;
$gridRows = [];

if ($editId > 0) {
    $stmt = asc_stmt($con, 'SELECT * FROM jos_app_loginllowslab WHERE id=? LIMIT 1');
    $stmt->bind_param('i', $editId);
    $stmt->execute();
    $editRow = $stmt->get_result()->fetch_assoc() ?: null;
    $stmt->close();
    if (!$editRow) {
        $_SESSION['flash_login_time_allowance_slab'] = 'Log in time allowance slab policy was not found.';
        redirect('/attendance/login-time-allowance-slab.php');
    }
    $gridRows = asc_slab_rows($con, $editId);
}

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 login time allowance slab policies.';
        if ($id === 0 && empty($acl['can_add'])) $errors[] = 'You do not have permission to add login time allowance slab policies.';
        if ($id > 0 && !asc_slab_exists($con, $id)) $errors[] = 'Log in time allowance slab policy was not found.';

        $policyName = trim((string)($_POST['policyname'] ?? ''));
        $month = max(0, (int)($_POST['month'] ?? 0));
        $year = max(0, (int)($_POST['year'] ?? 0));
        if ($policyName === '') $errors[] = 'Policy name is required.';
        if (mb_strlen($policyName) > 150) $errors[] = 'Policy name must be 150 characters or fewer.';
        if (!asc_valid_id($con, 'jos_app_mmonth', $month)) $errors[] = 'Select a valid month.';
        if (!asc_valid_id($con, 'jos_app_year', $year)) $errors[] = 'Select a valid year.';

        $presentDays = (array)($_POST['presentday'] ?? []);
        $amounts = (array)($_POST['amount'] ?? []);
        $rowsToSave = [];
        $seenDays = [];
        foreach ($presentDays as $index => $presentValue) {
            $amountValue = $amounts[$index] ?? '';
            if (trim((string)$presentValue) === '' && trim((string)$amountValue) === '') continue;
            $presentDay = asc_int_value($presentValue, 'No. Of Login row ' . ((int)$index + 1), $errors, 0, 9999);
            $amount = asc_decimal($amountValue, 'Amount row ' . ((int)$index + 1), $errors);
            if (isset($seenDays[$presentDay])) $errors[] = 'No. Of Login value ' . $presentDay . ' is duplicated.';
            $seenDays[$presentDay] = true;
            $rowsToSave[] = ['sr_no' => count($rowsToSave) + 1, 'presentday' => (string)$presentDay, 'amount' => $amount];
        }
        if (!$rowsToSave) $errors[] = 'Add at least one slab row.';
        if (!$errors) {
            $con->begin_transaction();
            try {
                $totalDays = asc_total_month_days($con, $month, $year);
                $savedId = asc_save_parent($con, $id, $policyName, $month, $year, $totalDays);
                $stmt = asc_stmt($con, 'DELETE FROM jos_app_loginllowslab_grid WHERE slabid=?');
                $stmt->bind_param('i', $savedId);
                $stmt->execute();
                $stmt->close();
                foreach ($rowsToSave as $row) {
                    $stmt = asc_stmt($con, 'INSERT INTO jos_app_loginllowslab_grid (sr_no,slabid,presentday,amount) VALUES (?,?,?,?)');
                    $stmt->bind_param('iiss', $row['sr_no'], $savedId, $row['presentday'], $row['amount']);
                    if (!$stmt->execute()) throw new RuntimeException('Unable to save login time allowance slab row.');
                    $stmt->close();
                }
                $con->commit();
                audit_log($id > 0 ? 'login_time_allowance_slab.update' : 'login_time_allowance_slab.create', 'jos_app_loginllowslab', (string)$savedId, $policyName);
                $_SESSION['flash_login_time_allowance_slab'] = $id > 0 ? 'Log in time allowance slab policy updated successfully.' : 'Log in time allowance slab policy added successfully.';
                redirect('/attendance/login-time-allowance-slab.php');
            } catch (Throwable $e) {
                $con->rollback();
                $errors[] = 'Unable to save the login time allowance slab policy. No changes were committed.';
            }
        }

        $isForm = true;
        $editId = $id;
        $editRow = ['id' => $id, 'policyname' => $policyName, 'month' => $month, 'year' => $year];
        $gridRows = $rowsToSave;
    } elseif ($action === 'delete') {
        if (empty($acl['can_delete'])) $errors[] = 'You do not have permission to delete login time allowance slab policies.';
        $id = max(0, (int)($_POST['id'] ?? 0));
        if ($id <= 0 || !asc_slab_exists($con, $id)) $errors[] = 'Log in time allowance slab policy was not found.';
        if (!$errors) {
            $stmt = asc_stmt($con, 'SELECT policyname FROM jos_app_loginllowslab WHERE id=? LIMIT 1');
            $stmt->bind_param('i', $id);
            $stmt->execute();
            $record = $stmt->get_result()->fetch_assoc();
            $stmt->close();
            $con->begin_transaction();
            try {
                $stmt = asc_stmt($con, 'DELETE FROM jos_app_loginllowslab_grid WHERE slabid=?');
                $stmt->bind_param('i', $id);
                $stmt->execute();
                $stmt->close();
                $stmt = asc_stmt($con, 'DELETE FROM jos_app_loginllowslab WHERE id=?');
                $stmt->bind_param('i', $id);
                $stmt->execute();
                $stmt->close();
                $con->commit();
                audit_log('login_time_allowance_slab.delete', 'jos_app_loginllowslab', (string)$id, (string)($record['policyname'] ?? ''));
                $_SESSION['flash_login_time_allowance_slab'] = 'Log in time allowance slab policy deleted successfully.';
                redirect('/attendance/login-time-allowance-slab.php');
            } catch (Throwable $e) {
                $con->rollback();
                $errors[] = 'Unable to delete the login time allowance slab policy.';
            }
        }
    }
}

$filterMonth = max(0, (int)($_GET['month'] ?? 0));
$filterYear = max(0, (int)($_GET['year'] ?? 0));
$search = trim((string)($_GET['q'] ?? ''));
$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = 20;
$totalRows = 0;
$rows = [];
$pages = 1;

if (!$isForm) {
    $where = ['1=1'];
    $types = '';
    $params = [];
    if ($filterMonth > 0) { $where[] = 'a.month=?'; $types .= 'i'; $params[] = $filterMonth; }
    if ($filterYear > 0) { $where[] = 'a.year=?'; $types .= 'i'; $params[] = $filterYear; }
    if ($search !== '') { $where[] = 'a.policyname LIKE ?'; $types .= 's'; $params[] = '%' . $search . '%'; }
    $whereSql = implode(' AND ', $where);

    $stmt = asc_stmt($con, 'SELECT COUNT(*) AS total FROM jos_app_loginllowslab a 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 = asc_stmt($con, 'SELECT a.*,m.month AS month_name,y.year AS year_name,COUNT(g.id) AS slab_count,MIN(CAST(g.presentday AS UNSIGNED)) AS min_day,MAX(CAST(g.presentday AS UNSIGNED)) AS max_day FROM jos_app_loginllowslab a LEFT JOIN jos_app_mmonth m ON m.id=a.month LEFT JOIN jos_app_year y ON y.id=a.year LEFT JOIN jos_app_loginllowslab_grid g ON g.slabid=a.id WHERE ' . $whereSql . ' GROUP BY a.id,m.month,y.year ORDER BY y.year DESC,a.year DESC,a.month DESC,a.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()) {
        $row['grid'] = asc_slab_rows($con, (int)$row['id']);
        $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 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';
if (!$gridRows && $isForm) $gridRows = [['presentday' => '', 'amount' => '']];

console_header('Log In Time Allowance Slab', $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>Attendance Settings</span><i class="fa-solid fa-chevron-right text-[9px]"></i><span class="text-brand-600">Log In Time Allowance Slab</span></div><h1 class="text-2xl font-bold text-slate-900">Log In Time Allowance Slab</h1><p class="mt-1 text-sm text-slate-500">Configure login time allowance amounts by number of logins.</p></div>
</div>
<?php if ($flash): ?><div class="mb-5 rounded-xl border border-emerald-100 bg-emerald-50 px-5 py-4 text-sm font-semibold text-emerald-700"><i class="fa-solid fa-circle-check mr-2"></i><?= h($flash) ?></div><?php endif; ?>
<?php if ($errors): ?><div class="mb-5 rounded-xl border border-red-100 bg-red-50 px-5 py-4 text-sm font-semibold text-red-700"><div class="font-bold">Please fix the following</div><ul class="mt-2 list-inside list-disc"><?php foreach($errors as $error): ?><li><?= h($error) ?></li><?php endforeach; ?></ul></div><?php endif; ?>

<?php if ($isForm): ?>
<form method="post" id="login-time-slab-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-layer-group"></i></span><div><h2 class="font-bold text-slate-800"><?= (int)$value('id',0)>0?'Edit Log In Time Allowance Slab':'New Log In Time Allowance Slab' ?></h2><p class="text-xs text-slate-400">Fields marked with * are required.</p></div></div><a href="/attendance/login-time-allowance-slab.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-3">
      <label class="text-sm font-semibold text-slate-700">Policy Name *<input name="policyname" required maxlength="150" value="<?= h((string)$value('policyname')) ?>" class="<?= $input ?>" placeholder="Policy Name"></label>
      <label class="text-sm font-semibold text-slate-700">Month *<select name="month" required class="<?= $input ?>"><option value="">Select Month</option><?php foreach($months as $option): ?><option value="<?= (int)$option['id'] ?>" <?= (int)$value('month')===(int)$option['id']?'selected':'' ?>><?= h($option['name']) ?></option><?php endforeach; ?></select></label>
      <label class="text-sm font-semibold text-slate-700">Year *<select name="year" required class="<?= $input ?>"><option value="">Select Year</option><?php foreach($years as $option): ?><option value="<?= (int)$option['id'] ?>" <?= (int)$value('year')===(int)$option['id']?'selected':'' ?>><?= h($option['name']) ?><?= $option['assessment']?' · '.h($option['assessment']):'' ?></option><?php endforeach; ?></select></label>
    </div>
  </section>
  <section class="overflow-hidden rounded-2xl border border-slate-100 bg-white shadow-sm">
    <div class="flex items-center justify-between border-b border-slate-100 px-5 py-4"><div><h2 class="font-bold text-slate-800">Slab Rows</h2><p class="mt-1 text-xs font-medium text-slate-400">Each login count maps to one allowance amount.</p></div><button type="button" id="add-slab-row" class="rounded-lg bg-brand-600 px-4 py-2 text-sm font-bold text-white hover:bg-brand-700"><i class="fa-solid fa-plus mr-2"></i>Add Row</button></div>
    <div class="overflow-x-auto"><table class="w-full min-w-[620px] text-left text-sm"><thead class="bg-slate-50 text-[10px] uppercase tracking-wider text-slate-400"><tr><th class="px-5 py-4 w-20">No</th><th class="px-5 py-4">No. Of Login</th><th class="px-5 py-4">Amount</th><th class="px-5 py-4 text-right w-24">Action</th></tr></thead><tbody id="slab-rows" class="divide-y divide-slate-100"><?php foreach($gridRows as $index=>$row): ?><tr><td class="row-number px-5 py-4 font-semibold text-slate-500"><?= $index + 1 ?></td><td class="px-5 py-4"><input name="presentday[]" inputmode="numeric" pattern="\d*" required value="<?= h((string)($row['presentday'] ?? '')) ?>" class="<?= $input ?> mt-0" placeholder="No. Of Login"></td><td class="px-5 py-4"><input name="amount[]" inputmode="decimal" required value="<?= h((string)($row['amount'] ?? '')) ?>" class="<?= $input ?> mt-0" placeholder="Amount"></td><td class="px-5 py-4 text-right"><button type="button" class="remove-slab-row rounded-lg border border-red-100 px-3 py-2 text-red-500 hover:bg-red-50" title="Remove"><i class="fa-solid fa-trash"></i></button></td></tr><?php endforeach; ?></tbody></table></div>
  </section>
  <div class="flex flex-wrap justify-end gap-2"><a href="/attendance/login-time-allowance-slab.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 Policy</button></div>
</form>
<template id="slab-row-template"><tr><td class="row-number px-5 py-4 font-semibold text-slate-500"></td><td class="px-5 py-4"><input name="presentday[]" inputmode="numeric" pattern="\d*" required class="<?= $input ?> mt-0" placeholder="No. Of Login"></td><td class="px-5 py-4"><input name="amount[]" inputmode="decimal" required class="<?= $input ?> mt-0" placeholder="Amount"></td><td class="px-5 py-4 text-right"><button type="button" class="remove-slab-row rounded-lg border border-red-100 px-3 py-2 text-red-500 hover:bg-red-50" title="Remove"><i class="fa-solid fa-trash"></i></button></td></tr></template>
<script>(()=>{const body=document.getElementById('slab-rows'),add=document.getElementById('add-slab-row'),tpl=document.getElementById('slab-row-template');const renumber=()=>[...body.querySelectorAll('tr')].forEach((row,index)=>row.querySelector('.row-number').textContent=index+1);add.addEventListener('click',()=>{body.appendChild(tpl.content.cloneNode(true));renumber();});body.addEventListener('click',event=>{const button=event.target.closest('.remove-slab-row');if(!button)return;if(body.querySelectorAll('tr').length===1){button.closest('tr').querySelectorAll('input').forEach(input=>input.value='');return;}button.closest('tr').remove();renumber();});renumber();})();</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">Log In Time Allowance Slab List</h2><p class="mt-1 text-xs font-medium text-slate-400">Policies are ordered by latest year and month.</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 type="search" name="q" value="<?= h($search) ?>" placeholder="Search policy name" class="<?= $selectSmall ?>"><select name="month" class="<?= $selectSmall ?>"><option value="0">All Months</option><?php foreach($months as $option): ?><option value="<?= (int)$option['id'] ?>" <?= $filterMonth===(int)$option['id']?'selected':'' ?>><?= h($option['name']) ?></option><?php endforeach; ?></select><select name="year" class="<?= $selectSmall ?>"><option value="0">All Years</option><?php foreach($years as $option): ?><option value="<?= (int)$option['id'] ?>" <?= $filterYear===(int)$option['id']?'selected':'' ?>><?= h($option['name']) ?></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="/attendance/login-time-allowance-slab.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-[1120px] text-left text-sm"><thead class="bg-slate-50 text-[10px] uppercase tracking-wider text-slate-400"><tr><th class="px-5 py-4 w-20">Sr No</th><th class="px-5 py-4">Policy Name</th><th class="px-5 py-4">Month</th><th class="px-5 py-4">Year</th><th class="px-5 py-4">Policy</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="6" class="px-6 py-14 text-center font-semibold text-slate-400">No login time allowance slab policies 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"><div class="font-bold text-slate-800"><?= h($row['policyname']) ?></div><div class="text-xs text-slate-400">Policy #<?= (int)$row['id'] ?></div></td><td class="px-5 py-4 font-semibold text-slate-700"><?= h($row['month_name'] ?: ($monthMap[(int)$row['month']] ?? 'Unknown')) ?></td><td class="px-5 py-4 font-semibold text-slate-700"><?= h($row['year_name'] ?: ($yearMap[(int)$row['year']] ?? (string)$row['year'])) ?></td><td class="px-5 py-4"><div class="overflow-hidden rounded-xl border border-slate-100"><table class="w-full text-xs"><thead class="bg-slate-50 text-[10px] uppercase text-slate-400"><tr><th class="px-3 py-2 text-left">No</th><th class="px-3 py-2 text-left">No. Of Login</th><th class="px-3 py-2 text-left">Amount</th></tr></thead><tbody><?php if(empty($row['grid'])): ?><tr><td colspan="3" class="px-3 py-3 text-center font-semibold text-slate-400">No rows</td></tr><?php endif; ?><?php foreach($row['grid'] as $gIndex=>$grid): ?><tr class="border-t border-slate-100"><td class="px-3 py-2"><?= $gIndex + 1 ?></td><td class="px-3 py-2 font-semibold"><?= h((string)$grid['presentday']) ?></td><td class="px-3 py-2 font-semibold"><?= h((string)$grid['amount']) ?></td></tr><?php endforeach; ?></tbody></table></div></td><td class="px-5 py-4"><div class="flex justify-end gap-2"><?php if(!empty($acl['can_edit'])): ?><a href="?edit=<?= (int)$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" onsubmit="return confirm('Delete this login time allowance slab policy?');"><input type="hidden" name="_csrf" value="<?= h(csrf_token()) ?>"><input type="hidden" name="action" value="delete"><input type="hidden" name="id" value="<?= (int)$row['id'] ?>"><button class="rounded-lg border border-red-100 px-3 py-2 text-red-500 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 ?> policies</span><div class="flex gap-2"><?php $base=['q'=>$search,'month'=>$filterMonth,'year'=>$filterYear]; 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(); ?>
