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

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

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

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

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

function pfc_columns(mysqli $con, string $table): array
{
    static $cache = [];
    if (isset($cache[$table])) return $cache[$table];
    if (!in_array($table, ['jos_app_pfconfig', 'jos_app_pfconfig_editlog'], true)) return $cache[$table] = [];
    $columns = [];
    $stmt = pfc_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 pfc_has_column(mysqli $con, string $table, string $column): bool
{
    return in_array($column, pfc_columns($con, $table), true);
}

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

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

function pfc_amount($value, array &$errors): string
{
    $raw = trim((string)$value);
    if ($raw === '') {
        $errors[] = 'PF Slab Amount is required.';
        return '0';
    }
    if (!preg_match('/^\d+(\.\d{1,2})?$/', $raw)) {
        $errors[] = 'PF Slab Amount must be a valid non-negative amount.';
        return '0';
    }
    $amount = (float)$raw;
    if ($amount < 0 || $amount > 999999999) $errors[] = 'PF Slab Amount is outside the allowed range.';
    return rtrim(rtrim(number_format($amount, 2, '.', ''), '0'), '.');
}

function pfc_save_row(mysqli $con, int $id, array $data): int
{
    $columns = pfc_columns($con, 'jos_app_pfconfig');
    $spec = ['nofmonth' => 'i', 'slab' => 'd', 'year' => 'i'];
    $fields = [];
    $types = '';
    $params = [];
    foreach ($spec as $field => $type) {
        if (!in_array($field, $columns, true)) continue;
        $fields[] = $field;
        $types .= $type;
        $params[] = $type === 'd' ? (float)$data[$field] : (int)$data[$field];
    }
    if (!$fields) throw new RuntimeException('No PF configuration fields available.');

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

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

function pfc_delete_row(mysqli $con, int $id): void
{
    if (pfc_columns($con, 'jos_app_pfconfig_editlog')) {
        $stmt = pfc_stmt($con, 'DELETE FROM jos_app_pfconfig_editlog WHERE pfid=?');
        $stmt->bind_param('i', $id);
        if (!$stmt->execute()) throw new RuntimeException('Unable to delete PF configuration history.');
        $stmt->close();
    }

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

function pfc_insert_history(mysqli $con, int $configId): void
{
    $historyColumns = pfc_columns($con, 'jos_app_pfconfig_editlog');
    if (!$historyColumns) return;
    $stmt = pfc_stmt($con, 'SELECT * FROM jos_app_pfconfig 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 === 'pfid') {
            $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[] = '?';
            if ($column === 'slab') {
                $types .= 'd'; $params[] = (float)$source[$column];
            } else {
                $types .= 'i'; $params[] = (int)$source[$column];
            }
        }
    }
    if (!$fields) return;
    $stmt = pfc_stmt($con, 'INSERT INTO jos_app_pfconfig_editlog (`' . implode('`,`', $fields) . '`) VALUES (' . implode(',', $placeholders) . ')');
    if ($types !== '') $stmt->bind_param($types, ...$params);
    if (!$stmt->execute()) throw new RuntimeException('Unable to save PF configuration history.');
    $stmt->close();
}

function pfc_history_rows(mysqli $con, int $configId): array
{
    if (!pfc_columns($con, 'jos_app_pfconfig_editlog')) return [];
    $order = pfc_has_column($con, 'jos_app_pfconfig_editlog', 'date') ? '`date` DESC,id DESC' : 'id DESC';
    $rows = [];
    $stmt = pfc_stmt($con, 'SELECT * FROM jos_app_pfconfig_editlog WHERE pfid=? 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 pfc_text(array $row, string $key, string $default = ''): string
{
    return array_key_exists($key, $row) && $row[$key] !== null ? (string)$row[$key] : $default;
}

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

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

$years = pfc_options($con, 'SELECT id,year FROM jos_app_year ORDER BY id DESC');
$yearMap = [];
foreach ($years as $row) $yearMap[(int)$row['id']] = (string)$row['year'];

$mode = (string)($_GET['mode'] ?? '');
$isForm = $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, 'nofmonth' => 0, 'slab' => '', 'year' => ''];
$historyRows = [];
$historyParent = null;

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

if ($editId > 0) {
    if (empty($acl['can_edit'])) {
        http_response_code(403);
        exit('Access denied.');
    }
    $isForm = true;
    $stmt = pfc_stmt($con, 'SELECT * FROM jos_app_pfconfig WHERE id=? LIMIT 1');
    $stmt->bind_param('i', $editId);
    $stmt->execute();
    $editRow = $stmt->get_result()->fetch_assoc() ?: [];
    $stmt->close();
    if (!$editRow) {
        $_SESSION['flash_pf_configuration'] = 'PF Configuration was not found.';
        redirect('/payroll/pf-configuration.php');
    }
}

if ($historyId > 0) {
    $isHistory = true;
    $stmt = pfc_stmt($con, 'SELECT * FROM jos_app_pfconfig WHERE id=? LIMIT 1');
    $stmt->bind_param('i', $historyId);
    $stmt->execute();
    $historyParent = $stmt->get_result()->fetch_assoc() ?: null;
    $stmt->close();
    if (!$historyParent) {
        $_SESSION['flash_pf_configuration'] = 'PF Configuration was not found.';
        redirect('/payroll/pf-configuration.php');
    }
    $historyRows = pfc_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 PF configurations.';
        if ($id === 0 && empty($acl['can_add'])) $errors[] = 'You do not have permission to add PF configurations.';
        if ($id > 0 && !pfc_exists($con, $id)) $errors[] = 'PF Configuration was not found.';

        $year = (int)($_POST['year'] ?? 0);
        if (!pfc_year_exists($con, $year)) $errors[] = 'Select a valid Year.';
        $slab = pfc_amount($_POST['amount'] ?? '', $errors);

        $data = [
            'nofmonth' => (int)($editRow['nofmonth'] ?? 0),
            'slab' => $slab,
            'year' => $year,
        ];

        if (!$errors) {
            $con->begin_transaction();
            try {
                $savedId = pfc_save_row($con, $id, $data);
                pfc_insert_history($con, $savedId);
                $con->commit();
                $_SESSION['flash_pf_configuration'] = $id > 0 ? 'PF Configuration updated successfully.' : 'PF Configuration added successfully.';
                redirect('/payroll/pf-configuration.php');
            } catch (Throwable $e) {
                $con->rollback();
                $errors[] = 'Unable to save the PF 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 PF configurations.';
        $id = max(0, (int)($_POST['id'] ?? 0));
        if ($id <= 0 || !pfc_exists($con, $id)) $errors[] = 'PF Configuration was not found.';

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

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

    $stmt = pfc_stmt($con, 'SELECT COUNT(*) AS total FROM jos_app_pfconfig c LEFT JOIN jos_app_year y ON y.id=c.year 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 = pfc_stmt($con, 'SELECT c.*,y.year AS year_label,(SELECT COUNT(*) FROM jos_app_pfconfig_editlog e WHERE e.pfid=c.id) AS history_count FROM jos_app_pfconfig c LEFT JOIN jos_app_year y ON y.id=c.year 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';
$filterInput = 'rounded-xl border border-slate-200 px-3 py-2.5 text-sm';

console_header('PF 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">PF Configuration</span></div>
    <h1 class="text-2xl font-bold text-slate-900">PF Configuration</h1>
    <p class="mt-1 text-sm text-slate-500">Configure Provident Fund slab amount by payroll year.</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">PF Configuration History</h2><p class="mt-1 text-xs font-medium text-slate-400">Year <?= h($yearMap[pfc_int_row($historyParent ?? [], 'year')] ?? pfc_text($historyParent ?? [], 'year')) ?></p></div><a href="/payroll/pf-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-[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">Date</th><th class="px-5 py-4">Year</th><th class="px-5 py-4">Slab Amount</th><th class="px-5 py-4">No. of 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="5" 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(pfc_text($row, 'date')) ?></td><td class="px-5 py-4"><?= h($yearMap[pfc_int_row($row, 'year')] ?? pfc_text($row, 'year')) ?></td><td class="px-5 py-4 font-bold text-slate-800"><?= h(pfc_amount_label(pfc_text($row, 'slab'))) ?></td><td class="px-5 py-4"><?= (int)pfc_int_row($row, 'nofmonth') ?></td><td class="px-5 py-4"><?= (int)pfc_int_row($row, 'modify_by') ?></td></tr><?php endforeach; ?>
  </tbody></table></div>
</section>
<?php elseif ($isForm): ?>
<form method="post" 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-scale-balanced"></i></span><div><h2 class="font-bold text-slate-800"><?= (int)$value('id',0)>0?'Edit PF Configuration':'New PF Configuration' ?></h2><p class="text-xs text-slate-400">Fields marked with * are required.</p></div></div><a href="/payroll/pf-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">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['year']) ?></option><?php endforeach; ?></select></label>
      <label class="text-sm font-semibold text-slate-700">PF Slab Amount *<input type="number" step="0.01" min="0" name="amount" required value="<?= h((string)$value('slab')) ?>" class="<?= $input ?>" placeholder="Amount"></label>
    </div>
  </section>
  <div class="flex flex-wrap justify-end gap-2"><a href="/payroll/pf-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>
<?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">PF Configuration List</h2><p class="mt-1 text-xs font-medium text-slate-400">PF slabs 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="<?= $filterInput ?>" placeholder="Search year or slab"><select name="year" class="<?= $filterInput ?>"><option value="">All Years</option><?php foreach($years as $option): ?><option value="<?= (int)$option['id'] ?>" <?= $filterYear===(int)$option['id']?'selected':'' ?>><?= h($option['year']) ?></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/pf-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-[820px] 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">Year</th><th class="px-5 py-4">Slab Amount</th><th class="px-5 py-4">No. of 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="5" class="px-6 py-14 text-center font-semibold text-slate-400">No PF 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(pfc_text($row, 'year_label', pfc_text($row, 'year'))) ?><?php if(pfc_int_row($row, 'history_count')>1): ?><div class="mt-1 text-xs font-semibold text-slate-400">History <?= pfc_int_row($row, 'history_count') ?></div><?php endif; ?></td><td class="px-5 py-4"><?= h(pfc_amount_label(pfc_text($row, 'slab'))) ?></td><td class="px-5 py-4"><?= (int)pfc_int_row($row, 'nofmonth') ?></td><td class="px-5 py-4"><div class="flex justify-end gap-2"><?php if(pfc_int_row($row, 'history_count')>1): ?><a href="?history=<?= pfc_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=<?= pfc_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 PF configuration?');"><input type="hidden" name="_csrf" value="<?= h(csrf_token()) ?>"><input type="hidden" name="action" value="delete"><input type="hidden" name="id" value="<?= pfc_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,'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(); ?>
