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

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

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

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

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

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

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

function tds_slab_rows(mysqli $con, int $yearId): array
{
    $rows = [];
    if ($yearId <= 0) {
        return $rows;
    }
    $stmt = tds_stmt($con, 'SELECT * FROM jos_app_tdstaxslab WHERE year=? ORDER BY fromslab ASC,id ASC');
    $stmt->bind_param('i', $yearId);
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $rows[] = $row;
    }
    $stmt->close();
    return $rows;
}

function tds_number($value, string $label, array &$errors): 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 < 0 || $number > 999999999) {
        $errors[] = $label . ' is outside the allowed range.';
    }
    return rtrim(rtrim(number_format($number, 2, '.', ''), '0'), '.');
}

function tds_amount_label($value): string
{
    $number = (float)$value;
    return rtrim(rtrim(number_format($number, 2, '.', ''), '0'), '.');
}

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

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

function tds_parse_slab_rows(array $post, array &$errors): array
{
    $fromValues = $post['fromslab'] ?? [];
    $toValues = $post['toslab'] ?? [];
    $rateValues = $post['rate'] ?? [];
    if (!is_array($fromValues) || !is_array($toValues) || !is_array($rateValues)) {
        $errors[] = 'Invalid slab row data.';
        return [];
    }

    $count = max(count($fromValues), count($toValues), count($rateValues));
    $rows = [];
    for ($i = 0; $i < $count; $i++) {
        $fromRaw = trim((string)($fromValues[$i] ?? ''));
        $toRaw = trim((string)($toValues[$i] ?? ''));
        $rateRaw = trim((string)($rateValues[$i] ?? ''));
        if ($fromRaw === '' && $toRaw === '' && $rateRaw === '') {
            continue;
        }

        $rowNo = $i + 1;
        $from = tds_number($fromRaw, 'Row ' . $rowNo . ' From TDS Slab', $errors);
        $to = tds_number($toRaw, 'Row ' . $rowNo . ' To TDS Slab', $errors);
        $rate = tds_number($rateRaw, 'Row ' . $rowNo . ' TDS Rate', $errors);
        if ((float)$to < (float)$from) {
            $errors[] = 'Row ' . $rowNo . ' To TDS Slab must be greater than or equal to From TDS Slab.';
        }
        if ((float)$rate > 100) {
            $errors[] = 'Row ' . $rowNo . ' TDS Rate must not exceed 100.';
        }

        $rows[] = ['fromslab' => $from, 'toslab' => $to, 'rate' => $rate];
    }

    if (!$rows) {
        $errors[] = 'Add at least one TDS slab row.';
    }
    return $rows;
}

function tds_save_year_rows(mysqli $con, int $yearId, array $rows): void
{
    $stmt = tds_stmt($con, 'DELETE FROM jos_app_tdstaxslab WHERE year=?');
    $stmt->bind_param('i', $yearId);
    if (!$stmt->execute()) {
        throw new RuntimeException('Unable to replace existing TDS slabs.');
    }
    $stmt->close();

    $stmt = tds_stmt($con, 'INSERT INTO jos_app_tdstaxslab (date, year, fromslab, toslab, rate) VALUES (CURDATE(), ?, ?, ?, ?)');
    foreach ($rows as $row) {
        $from = (float)$row['fromslab'];
        $to = (float)$row['toslab'];
        $rate = (float)$row['rate'];
        $stmt->bind_param('iddd', $yearId, $from, $to, $rate);
        if (!$stmt->execute()) {
            $stmt->close();
            throw new RuntimeException('Unable to save TDS slab rows.');
        }
    }
    $stmt->close();
}

$years = tds_options($con, 'SELECT id,year,assessment FROM jos_app_year ORDER BY id DESC');
$formYears = tds_options($con, 'SELECT id,year,assessment FROM jos_app_year ORDER BY id DESC LIMIT 3');
$yearMap = [];
foreach ($years as $row) {
    $yearMap[(int)$row['id']] = trim((string)($row['assessment'] ?: $row['year']));
}

$mode = (string)($_GET['mode'] ?? '');
$isForm = $mode === 'add';
$editYear = isset($_GET['edit_year']) ? max(0, (int)$_GET['edit_year']) : 0;
if ($editYear <= 0 && isset($_GET['edit'])) {
    $editYear = max(0, (int)$_GET['edit']);
}
$formYear = 0;
$formRows = [['fromslab' => '', 'toslab' => '', 'rate' => '']];

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

if ($editYear > 0) {
    if (empty($acl['can_edit'])) {
        http_response_code(403);
        exit('Access denied.');
    }
    if (!tds_year_exists($con, $editYear) || !tds_year_has_rows($con, $editYear)) {
        $_SESSION['flash_tds_slab_configuration'] = 'TDS Slab Configuration was not found.';
        redirect('/payroll/tds-slab-configuration.php');
    }
    $isForm = true;
    $formYear = $editYear;
    $formRows = tds_slab_rows($con, $editYear);
    if (!in_array($editYear, array_map(static fn($row) => (int)$row['id'], $formYears), true)) {
        $formYears[] = ['id' => $editYear, 'year' => $yearMap[$editYear] ?? (string)$editYear, 'assessment' => $yearMap[$editYear] ?? (string)$editYear];
    }
}

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') {
        $yearId = (int)($_POST['year'] ?? 0);
        $formContext = (string)($_POST['form_context'] ?? 'add');
        $originalYear = (int)($_POST['original_year'] ?? 0);
        $isExisting = tds_year_has_rows($con, $yearId);
        if ($formContext === 'edit' && $originalYear <= 0) {
            $errors[] = 'Invalid edit request. Please return to the list and try again.';
        }
        if ($formContext === 'add' && $isExisting) {
            $errors[] = 'TDS slabs already exist for this Assessment Year. Use the edit action from the list.';
        }
        if (($isExisting || $formContext === 'edit') && empty($acl['can_edit'])) {
            $errors[] = 'You do not have permission to edit TDS slabs.';
        }
        if (!$isExisting && $formContext !== 'edit' && empty($acl['can_add'])) {
            $errors[] = 'You do not have permission to add TDS slabs.';
        }
        if (!tds_year_exists($con, $yearId)) {
            $errors[] = 'Select a valid Assessment Year.';
        }

        $slabRows = tds_parse_slab_rows($_POST, $errors);

        if (!$errors) {
            $con->begin_transaction();
            try {
                tds_save_year_rows($con, $yearId, $slabRows);
                $con->commit();
                $_SESSION['flash_tds_slab_configuration'] = $isExisting ? 'TDS Slab Configuration updated successfully.' : 'TDS Slab Configuration added successfully.';
                redirect('/payroll/tds-slab-configuration.php');
            } catch (Throwable $e) {
                $con->rollback();
                $errors[] = 'Unable to save the TDS slab configuration. No changes were committed.';
            }
        }

        $isForm = true;
        $formYear = $yearId;
        $formRows = $slabRows ?: [['fromslab' => '', 'toslab' => '', 'rate' => '']];
        if ($yearId > 0 && tds_year_exists($con, $yearId) && !in_array($yearId, array_map(static fn($row) => (int)$row['id'], $formYears), true)) {
            $formYears[] = ['id' => $yearId, 'year' => $yearMap[$yearId] ?? (string)$yearId, 'assessment' => $yearMap[$yearId] ?? (string)$yearId];
        }
    }
}

$filterQ = trim((string)($_GET['q'] ?? ''));
$filterYear = isset($_GET['year']) && $_GET['year'] !== '' ? (int)$_GET['year'] : 0;
$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = 10;
$groups = [];
$totalRows = 0;
$pages = 1;

if (!$isForm) {
    $where = ['1=1'];
    $types = '';
    $params = [];
    if ($filterQ !== '') {
        $where[] = '(CAST(t.fromslab AS CHAR) LIKE ? OR CAST(t.toslab AS CHAR) LIKE ? OR CAST(t.rate AS CHAR) LIKE ? OR y.year LIKE ? OR y.assessment LIKE ?)';
        $types .= 'sssss';
        for ($i = 0; $i < 5; $i++) {
            $params[] = '%' . $filterQ . '%';
        }
    }
    if ($filterYear > 0) {
        $where[] = 't.year=?';
        $types .= 'i';
        $params[] = $filterYear;
    }
    $whereSql = implode(' AND ', $where);

    $stmt = tds_stmt($con, 'SELECT COUNT(*) AS total FROM (SELECT t.year FROM jos_app_tdstaxslab t LEFT JOIN jos_app_year y ON y.id=t.year WHERE ' . $whereSql . ' GROUP BY t.year) x');
    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 = tds_stmt($con, 'SELECT t.year,COALESCE(NULLIF(y.assessment, \'\'), y.year, t.year) AS year_label,COUNT(*) AS slab_count FROM jos_app_tdstaxslab t LEFT JOIN jos_app_year y ON y.id=t.year WHERE ' . $whereSql . ' GROUP BY t.year,year_label ORDER BY t.year 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()) {
        $yearId = (int)$row['year'];
        $row['slabs'] = tds_slab_rows($con, $yearId);
        $groups[] = $row;
    }
    $stmt->close();
}

$input = 'mt-1 w-full rounded-lg border border-slate-200 bg-white px-3 py-2.5 text-sm text-slate-800 outline-none focus:border-brand-500 focus:ring-2 focus:ring-brand-100';
$filterInput = 'rounded-xl border border-slate-200 px-3 py-2.5 text-sm';

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

<?php if ($isForm): ?>
<form method="post" class="space-y-4" id="tds-slab-form">
  <input type="hidden" name="_csrf" value="<?= h(csrf_token()) ?>"><input type="hidden" name="action" value="save"><input type="hidden" name="form_context" value="<?= $editYear > 0 ? 'edit' : 'add' ?>"><input type="hidden" name="original_year" value="<?= (int)$editYear ?>">
  <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-file-invoice-dollar"></i></span><div><h2 class="font-bold text-slate-800"><?= $editYear > 0 ? 'Edit TDS Slab Configuration' : 'New TDS Slab Configuration' ?></h2><p class="text-xs text-slate-400">Fields marked with * are required.</p></div></div><a href="/payroll/tds-slab-configuration.php" class="rounded-lg border border-slate-200 bg-white px-4 py-2 text-sm font-bold text-slate-600 hover:bg-slate-50"><i class="fa-solid fa-arrow-left mr-2"></i>Back to List</a></div>
    <div class="grid gap-3 md:grid-cols-2 xl:grid-cols-4">
      <label class="text-sm font-semibold text-slate-700">Assessment Year *<select name="year" required class="<?= $input ?>"><option value="">Select Assessment Year</option><?php foreach ($formYears as $option): $label = trim((string)($option['assessment'] ?: $option['year'])); ?><option value="<?= (int)$option['id'] ?>" <?= $formYear === (int)$option['id'] ? 'selected' : '' ?>><?= h($label) ?></option><?php endforeach; ?></select></label>
    </div>
  </section>
  <section class="overflow-hidden rounded-2xl border border-slate-100 bg-white shadow-sm">
    <div class="flex flex-wrap items-center justify-between gap-3 border-b border-slate-100 px-5 py-4"><div><h2 class="font-bold text-slate-800">Income TDS Slab</h2><p class="mt-1 text-xs font-medium text-slate-400">Rows are saved as the complete slab set for the selected year.</p></div><button type="button" id="add-tds-row" class="inline-flex items-center gap-2 rounded-lg border border-brand-200 bg-brand-50 px-4 py-2 text-sm font-bold text-brand-700 hover:bg-brand-100"><i class="fa-solid fa-plus"></i>Add Row</button></div>
    <div class="overflow-x-auto">
      <table class="w-full min-w-[760px] 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">No</th><th class="px-5 py-4">From TDS Slab</th><th class="px-5 py-4">To TDS Slab</th><th class="px-5 py-4">TDS Rate %</th><th class="px-5 py-4 w-20 text-right">Action</th></tr></thead>
        <tbody class="divide-y divide-slate-100" id="tds-slab-rows">
          <?php foreach ($formRows as $index => $row): ?>
          <tr class="tds-slab-row">
            <td class="row-number px-5 py-4 font-semibold text-slate-500"><?= $index + 1 ?></td>
            <td class="px-5 py-4"><input type="number" step="0.01" min="0" name="fromslab[]" required value="<?= h(tds_text($row, 'fromslab')) ?>" class="<?= $input ?>" placeholder="From"></td>
            <td class="px-5 py-4"><input type="number" step="0.01" min="0" name="toslab[]" required value="<?= h(tds_text($row, 'toslab')) ?>" class="<?= $input ?>" placeholder="To"></td>
            <td class="px-5 py-4"><input type="number" step="0.01" min="0" max="100" name="rate[]" required value="<?= h(tds_text($row, 'rate')) ?>" class="<?= $input ?>" placeholder="Rate"></td>
            <td class="px-5 py-4 text-right"><button type="button" class="remove-tds-row rounded-lg border border-slate-200 px-3 py-2 text-red-600 hover:bg-red-50" title="Remove row"><i class="fa-solid fa-xmark"></i></button></td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </section>
  <div class="flex flex-wrap justify-end gap-2"><a href="/payroll/tds-slab-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>
document.addEventListener('click', function (event) {
  const addButton = event.target.closest('#add-tds-row');
  const removeButton = event.target.closest('.remove-tds-row');
  const body = document.getElementById('tds-slab-rows');
  if (!body) return;
  if (addButton) {
    const row = document.createElement('tr');
    row.className = 'tds-slab-row';
    row.innerHTML = '<td class="row-number px-5 py-4 font-semibold text-slate-500"></td><td class="px-5 py-4"><input type="number" step="0.01" min="0" name="fromslab[]" required class="<?= h($input) ?>" placeholder="From"></td><td class="px-5 py-4"><input type="number" step="0.01" min="0" name="toslab[]" required class="<?= h($input) ?>" placeholder="To"></td><td class="px-5 py-4"><input type="number" step="0.01" min="0" max="100" name="rate[]" required class="<?= h($input) ?>" placeholder="Rate"></td><td class="px-5 py-4 text-right"><button type="button" class="remove-tds-row rounded-lg border border-slate-200 px-3 py-2 text-red-600 hover:bg-red-50" title="Remove row"><i class="fa-solid fa-xmark"></i></button></td>';
    body.appendChild(row);
  }
  if (removeButton && body.querySelectorAll('.tds-slab-row').length > 1) {
    removeButton.closest('.tds-slab-row').remove();
  }
  body.querySelectorAll('.row-number').forEach(function (cell, index) {
    cell.textContent = String(index + 1);
  });
});
</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">TDS Slab Configuration List</h2><p class="mt-1 text-xs font-medium text-slate-400">TDS slabs are grouped by assessment year.</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="<?= $filterInput ?>" placeholder="Search year, slab, or rate"><select name="year" class="<?= $filterInput ?>"><option value="">All Assessment Years</option><?php foreach ($years as $option): $label = trim((string)($option['assessment'] ?: $option['year'])); ?><option value="<?= (int)$option['id'] ?>" <?= $filterYear === (int)$option['id'] ? 'selected' : '' ?>><?= 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="/payroll/tds-slab-configuration.php" class="rounded-xl border border-slate-200 px-5 py-2.5 text-sm font-bold text-slate-600">Clear</a></div></form>
  <div class="overflow-x-auto"><table class="w-full min-w-[900px] text-left text-sm"><thead class="bg-slate-50 text-[10px] font-extrabold uppercase tracking-wider text-slate-700"><tr><th class="px-5 py-4 w-20">Sr No</th><th class="px-5 py-4">Assessment Year</th><th class="px-5 py-4">Slabs</th><th class="px-5 py-4 text-right">Actions</th></tr></thead><tbody class="divide-y divide-slate-100">
    <?php if (!$groups): ?><tr><td colspan="4" class="px-6 py-14 text-center font-semibold text-slate-400">No TDS slab configurations found.</td></tr><?php endif; ?>
    <?php foreach ($groups as $index => $group): ?><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(tds_text($group, 'year_label', tds_text($group, 'year'))) ?><div class="mt-1 text-xs font-semibold text-slate-400"><?= (int)$group['slab_count'] ?> slab<?= (int)$group['slab_count'] === 1 ? '' : 's' ?></div></td><td class="px-5 py-4"><div class="overflow-hidden rounded-xl border border-slate-100"><table class="w-full min-w-[520px] text-xs"><thead class="bg-slate-50 text-slate-500"><tr><th class="px-3 py-2 text-left">No</th><th class="px-3 py-2 text-left">From TDS Slab</th><th class="px-3 py-2 text-left">To TDS Slab</th><th class="px-3 py-2 text-left">TDS Rate %</th></tr></thead><tbody class="divide-y divide-slate-100"><?php foreach (($group['slabs'] ?? []) as $slabIndex => $slab): ?><tr><td class="px-3 py-2 font-semibold text-slate-500"><?= $slabIndex + 1 ?></td><td class="px-3 py-2"><?= h(tds_amount_label(tds_text($slab, 'fromslab'))) ?></td><td class="px-3 py-2"><?= h(tds_amount_label(tds_text($slab, 'toslab'))) ?></td><td class="px-3 py-2 font-semibold text-slate-800"><?= h(tds_amount_label(tds_text($slab, 'rate'))) ?></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=<?= tds_int_row($group, 'year') ?>" 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; ?></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, '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(); ?>
