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

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

$pageLink = 'form16/form16-tax-slab.php';
$errors = [];
$flash = $_SESSION['flash_form16_tax_slab'] ?? null;
unset($_SESSION['flash_form16_tax_slab']);

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

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

function f16_regimes(): array
{
    return [1 => 'Old Regime', 2 => 'New Regime'];
}

function f16_regime_label(int $type): string
{
    $regimes = f16_regimes();
    return $regimes[$type] ?? 'Unknown Regime';
}

function f16_year_exists(mysqli $con, int $yearId): bool
{
    if ($yearId <= 0) {
        return false;
    }
    $stmt = f16_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 f16_set_exists(mysqli $con, int $yearId, int $type): bool
{
    if ($yearId <= 0 || $type <= 0) {
        return false;
    }
    $stmt = f16_stmt($con, 'SELECT id FROM jos_app_f16taxslab WHERE year=? AND type=? LIMIT 1');
    $stmt->bind_param('ii', $yearId, $type);
    $stmt->execute();
    $exists = (bool)$stmt->get_result()->fetch_assoc();
    $stmt->close();
    return $exists;
}

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

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

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

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

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

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

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

        $rowNo = $i + 1;
        $from = f16_number($fromRaw, 'Row ' . $rowNo . ' From Tax Slab', $errors);
        $to = f16_number($toRaw, 'Row ' . $rowNo . ' To Tax Slab', $errors);
        $rate = f16_number($rateRaw, 'Row ' . $rowNo . ' Tax Rate', $errors, 100.0);
        $amount = f16_number($amountRaw === '' ? '0' : $amountRaw, 'Row ' . $rowNo . ' Fixed Amount', $errors);
        if ((float)$to < (float)$from) {
            $errors[] = 'Row ' . $rowNo . ' To Tax Slab must be greater than or equal to From Tax Slab.';
        }
        $rows[] = ['fromslab' => $from, 'toslab' => $to, 'rate' => $rate, 'amount' => $amount];
    }

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

    usort($rows, static fn($a, $b) => (float)$a['fromslab'] <=> (float)$b['fromslab']);
    $previousTo = null;
    foreach ($rows as $index => $row) {
        $from = (float)$row['fromslab'];
        $to = (float)$row['toslab'];
        if ($previousTo !== null) {
            if ($from <= $previousTo) {
                $errors[] = 'Row ' . ($index + 1) . ' overlaps a previous tax slab.';
            }
            if (round($from - $previousTo, 2) > 1.00) {
                $errors[] = 'Row ' . ($index + 1) . ' must continue immediately after the previous slab.';
            }
        }
        $previousTo = $to;
    }
    return $rows;
}

function f16_save_set(mysqli $con, int $yearId, int $type, array $rows): void
{
    $stmt = f16_stmt($con, 'DELETE FROM jos_app_f16taxslab WHERE year=? AND type=?');
    $stmt->bind_param('ii', $yearId, $type);
    if (!$stmt->execute()) {
        throw new RuntimeException('Unable to replace existing Form 16 tax slabs.');
    }
    $stmt->close();

    $stmt = f16_stmt($con, 'INSERT INTO jos_app_f16taxslab (date, year, fromslab, toslab, rate, amount, type) VALUES (CURDATE(), ?, ?, ?, ?, ?, ?)');
    foreach ($rows as $row) {
        $from = (float)$row['fromslab'];
        $to = (float)$row['toslab'];
        $rate = (float)$row['rate'];
        $amount = (float)$row['amount'];
        $stmt->bind_param('iddddi', $yearId, $from, $to, $rate, $amount, $type);
        if (!$stmt->execute()) {
            $stmt->close();
            throw new RuntimeException('Unable to save Form 16 tax slab rows.');
        }
    }
    $stmt->close();
}

$acl = require_acl('can_view', $pageLink);

$years = f16_options($con, 'SELECT id,year,assessment FROM jos_app_year ORDER BY id DESC');
$formYears = f16_options($con, 'SELECT id,year,assessment FROM jos_app_year ORDER BY id DESC LIMIT 5');
$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;
$editType = isset($_GET['edit_type']) ? max(0, (int)$_GET['edit_type']) : 0;
if ($editYear <= 0 && isset($_GET['edit'])) {
    [$editYear, $editType] = array_pad(array_map('intval', explode('-', (string)$_GET['edit'], 2)), 2, 0);
}
$formYear = 0;
$formType = 1;
$formRows = [['fromslab' => '', 'toslab' => '', 'rate' => '', 'amount' => '0']];

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

if ($editYear > 0 && $editType > 0) {
    if (empty($acl['can_edit'])) {
        http_response_code(403);
        exit('Access denied.');
    }
    if (!f16_year_exists($con, $editYear) || !f16_set_exists($con, $editYear, $editType)) {
        $_SESSION['flash_form16_tax_slab'] = 'Form 16 Tax Slab Configuration was not found.';
        redirect('/form16/form16-tax-slab.php');
    }
    $isForm = true;
    $formYear = $editYear;
    $formType = $editType;
    $formRows = f16_slab_rows($con, $editYear, $editType);
    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);
        $type = (int)($_POST['type'] ?? 0);
        $formContext = (string)($_POST['form_context'] ?? 'add');
        $originalYear = (int)($_POST['original_year'] ?? 0);
        $originalType = (int)($_POST['original_type'] ?? 0);
        $isExisting = f16_set_exists($con, $yearId, $type);

        if (!f16_year_exists($con, $yearId)) {
            $errors[] = 'Select a valid Assessment Year.';
        }
        if (!array_key_exists($type, f16_regimes())) {
            $errors[] = 'Select a valid Assessment Type.';
        }
        if ($formContext === 'edit' && ($originalYear <= 0 || $originalType <= 0)) {
            $errors[] = 'Invalid edit request. Please return to the list and try again.';
        }
        if ($formContext === 'add' && $isExisting) {
            $errors[] = 'Form 16 tax slabs already exist for this Assessment Year and Assessment Type.';
        }
        if ($formContext === 'edit' && ($yearId !== $originalYear || $type !== $originalType) && $isExisting) {
            $errors[] = 'Another Form 16 tax slab set already exists for the selected Assessment Year and Assessment Type.';
        }
        if (($isExisting || $formContext === 'edit') && empty($acl['can_edit'])) {
            $errors[] = 'You do not have permission to edit Form 16 tax slabs.';
        }
        if (!$isExisting && $formContext !== 'edit' && empty($acl['can_add'])) {
            $errors[] = 'You do not have permission to add Form 16 tax slabs.';
        }

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

        if (!$errors) {
            $con->begin_transaction();
            try {
                if ($formContext === 'edit' && ($yearId !== $originalYear || $type !== $originalType)) {
                    $stmt = f16_stmt($con, 'DELETE FROM jos_app_f16taxslab WHERE year=? AND type=?');
                    $stmt->bind_param('ii', $originalYear, $originalType);
                    $stmt->execute();
                    $stmt->close();
                }
                f16_save_set($con, $yearId, $type, $slabRows);
                $con->commit();
                $_SESSION['flash_form16_tax_slab'] = $formContext === 'edit' ? 'Form 16 Tax Slab updated successfully.' : 'Form 16 Tax Slab added successfully.';
                redirect('/form16/form16-tax-slab.php');
            } catch (Throwable $e) {
                $con->rollback();
                $errors[] = 'Unable to save the Form 16 tax slab configuration. No changes were committed.';
            }
        }

        $isForm = true;
        $formYear = $yearId;
        $formType = $type ?: 1;
        $formRows = $slabRows ?: [['fromslab' => '', 'toslab' => '', 'rate' => '', 'amount' => '0']];
    } elseif ($action === 'delete') {
        if (empty($acl['can_delete'])) {
            $errors[] = 'You do not have permission to delete Form 16 tax slabs.';
        }
        $yearId = (int)($_POST['year'] ?? 0);
        $type = (int)($_POST['type'] ?? 0);
        if (!f16_set_exists($con, $yearId, $type)) {
            $errors[] = 'Form 16 Tax Slab Configuration was not found.';
        }
        if (!$errors) {
            $stmt = f16_stmt($con, 'DELETE FROM jos_app_f16taxslab WHERE year=? AND type=?');
            $stmt->bind_param('ii', $yearId, $type);
            if ($stmt->execute()) {
                $_SESSION['flash_form16_tax_slab'] = 'Form 16 Tax Slab deleted successfully.';
                $stmt->close();
                redirect('/form16/form16-tax-slab.php');
            }
            $stmt->close();
            $errors[] = 'Unable to delete the Form 16 tax slab configuration.';
        }
    }
}

$filterQ = trim((string)($_GET['q'] ?? ''));
$filterYear = isset($_GET['year']) && $_GET['year'] !== '' ? (int)$_GET['year'] : 0;
$filterType = isset($_GET['type']) && $_GET['type'] !== '' ? (int)$_GET['type'] : 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 CAST(t.amount AS CHAR) LIKE ? OR y.year LIKE ? OR y.assessment LIKE ?)';
        $types .= 'ssssss';
        for ($i = 0; $i < 6; $i++) {
            $params[] = '%' . $filterQ . '%';
        }
    }
    if ($filterYear > 0) {
        $where[] = 't.year=?';
        $types .= 'i';
        $params[] = $filterYear;
    }
    if ($filterType > 0) {
        $where[] = 't.type=?';
        $types .= 'i';
        $params[] = $filterType;
    }
    $whereSql = implode(' AND ', $where);

    $stmt = f16_stmt($con, 'SELECT COUNT(*) AS total FROM (SELECT t.year,t.type FROM jos_app_f16taxslab t LEFT JOIN jos_app_year y ON y.id=t.year WHERE ' . $whereSql . ' GROUP BY t.year,t.type) 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 = f16_stmt($con, 'SELECT t.year,t.type,COALESCE(NULLIF(y.assessment, \'\'), y.year, t.year) AS year_label,COUNT(*) AS slab_count FROM jos_app_f16taxslab t LEFT JOIN jos_app_year y ON y.id=t.year WHERE ' . $whereSql . ' GROUP BY t.year,t.type,year_label ORDER BY t.year DESC,t.type ASC 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['slabs'] = f16_slab_rows($con, (int)$row['year'], (int)$row['type']);
        $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('Form 16 Tax 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>Form 16 Configuration</span><i class="fa-solid fa-chevron-right text-[9px]"></i><span class="text-brand-600">Form 16 Tax Slab</span></div>
    <h1 class="text-2xl font-bold text-slate-900">Form 16 Tax Slab</h1>
    <p class="mt-1 text-sm text-slate-500">Configure assessment-year tax slab ranges, rates, and fixed amounts for Form 16.</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="f16-tax-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 ?>">
  <input type="hidden" name="original_type" value="<?= (int)$editType ?>">
  <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 Form 16 Tax Slab' : 'New Form 16 Tax Slab' ?></h2><p class="text-xs text-slate-400">Fields marked with * are required.</p></div></div><a href="/form16/form16-tax-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-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>
      <label class="text-sm font-semibold text-slate-700">Assessment Type *<select name="type" required class="<?= $input ?>"><option value="">Select Assessment Type</option><?php foreach (f16_regimes() as $value => $label): ?><option value="<?= (int)$value ?>" <?= $formType === (int)$value ? '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">Tax Slab Rows</h2><p class="mt-1 text-xs font-medium text-slate-400">Rows are saved as the complete slab set for the selected assessment year and type.</p></div><button type="button" id="add-f16-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-[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">No</th><th class="px-5 py-4">From Tax Slab</th><th class="px-5 py-4">To Tax Slab</th><th class="px-5 py-4">Tax Rate %</th><th class="px-5 py-4">Fixed Amount</th><th class="px-5 py-4 w-20 text-right">Action</th></tr></thead>
        <tbody class="divide-y divide-slate-100" id="f16-slab-rows">
          <?php foreach ($formRows as $index => $row): ?>
          <tr class="f16-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(f16_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(f16_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(f16_text($row, 'rate')) ?>" class="<?= $input ?>" placeholder="Rate"></td>
            <td class="px-5 py-4"><input type="number" step="0.01" min="0" name="amount[]" required value="<?= h(f16_text($row, 'amount', '0')) ?>" class="<?= $input ?>" placeholder="Amount"></td>
            <td class="px-5 py-4 text-right"><button type="button" class="remove-f16-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="/form16/form16-tax-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 Tax Slab</button></div>
</form>
<script>
document.addEventListener('click', function (event) {
  const addButton = event.target.closest('#add-f16-row');
  const removeButton = event.target.closest('.remove-f16-row');
  const body = document.getElementById('f16-slab-rows');
  if (!body) return;
  if (addButton) {
    const row = document.createElement('tr');
    row.className = 'f16-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"><input type="number" step="0.01" min="0" name="amount[]" required value="0" class="<?= h($input) ?>" placeholder="Amount"></td><td class="px-5 py-4 text-right"><button type="button" class="remove-f16-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('.f16-slab-row').length > 1) {
    removeButton.closest('.f16-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">Form 16 Tax Slab List</h2><p class="mt-1 text-xs font-medium text-slate-400">Tax slabs are grouped by assessment year and assessment type.</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, rate, or amount"><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><select name="type" class="<?= $filterInput ?>"><option value="">All Assessment Types</option><?php foreach (f16_regimes() as $value => $label): ?><option value="<?= (int)$value ?>" <?= $filterType === (int)$value ? 'selected' : '' ?>><?= 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="/form16/form16-tax-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-[1000px] 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">Assessment Type</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="5" class="px-6 py-14 text-center font-semibold text-slate-400">No Form 16 tax 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(f16_text($group, 'year_label', f16_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"><span class="rounded-full bg-brand-50 px-3 py-1 text-xs font-bold text-brand-700"><?= h(f16_regime_label(f16_int_row($group, 'type'))) ?></span></td><td class="px-5 py-4"><div class="overflow-hidden rounded-xl border border-slate-100"><table class="w-full min-w-[640px] 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 Tax Slab</th><th class="px-3 py-2 text-left">To Tax Slab</th><th class="px-3 py-2 text-left">Tax Rate %</th><th class="px-3 py-2 text-left">Fixed Amount</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(f16_amount_label(f16_text($slab, 'fromslab'))) ?></td><td class="px-3 py-2"><?= h(f16_amount_label(f16_text($slab, 'toslab'))) ?></td><td class="px-3 py-2 font-semibold text-slate-800"><?= h(f16_amount_label(f16_text($slab, 'rate'))) ?></td><td class="px-3 py-2"><?= h(f16_amount_label(f16_text($slab, '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=<?= f16_int_row($group, 'year') ?>-<?= f16_int_row($group, 'type') ?>" 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 Form 16 tax slab set?');"><input type="hidden" name="_csrf" value="<?= h(csrf_token()) ?>"><input type="hidden" name="action" value="delete"><input type="hidden" name="year" value="<?= f16_int_row($group, 'year') ?>"><input type="hidden" name="type" value="<?= f16_int_row($group, 'type') ?>"><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, 'year' => $filterYear ?: '', 'type' => $filterType ?: '']; 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(); ?>
