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

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

$pageLink = 'attendance/late-mark-policy-configuration.php';
$acl = require_acl('can_view', $pageLink);
$errors = [];
$flash = $_SESSION['flash_late_mark_policy_configuration'] ?? null;
unset($_SESSION['flash_late_mark_policy_configuration']);

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

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

function lmp_columns(mysqli $con, string $table): array
{
    static $cache = [];
    if (isset($cache[$table])) return $cache[$table];
    $allowed = [
        'jos_app_lmconfig',
        'jos_app_lmconfig_grid',
        'jos_app_lmconfig_editlog',
        'jos_app_lmconfig_grid_editlog',
    ];
    if (!in_array($table, $allowed, true)) return $cache[$table] = [];
    $columns = [];
    $stmt = lmp_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 lmp_has_column(mysqli $con, string $table, string $column): bool
{
    return in_array($column, lmp_columns($con, $table), true);
}

function lmp_valid_id(mysqli $con, string $table, int $id): bool
{
    $allowed = ['jos_app_payrolllocation', 'jos_app_mmonth', 'jos_app_year'];
    if ($id <= 0 || !in_array($table, $allowed, true)) return false;
    $stmt = lmp_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 lmp_exists(mysqli $con, int $id): bool
{
    $stmt = lmp_stmt($con, 'SELECT id FROM jos_app_lmconfig WHERE id=? LIMIT 1');
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $exists = (bool)$stmt->get_result()->fetch_assoc();
    $stmt->close();
    return $exists;
}

function lmp_int($value, string $label, array &$errors, int $min = 0, int $max = 999999, bool $required = false): int
{
    $raw = trim((string)$value);
    if ($raw === '') {
        if ($required) $errors[] = $label . ' is required.';
        return 0;
    }
    if (!preg_match('/^\d+$/', $raw)) {
        $errors[] = $label . ' must be a whole number.';
        return 0;
    }
    $number = (int)$raw;
    if ($number < $min || $number > $max) $errors[] = $label . ' must be between ' . $min . ' and ' . $max . '.';
    return $number;
}

function lmp_decimal($value, string $label, array &$errors, bool $required = false): string
{
    $raw = trim((string)$value);
    if ($raw === '') {
        if ($required) $errors[] = $label . ' is required.';
        return '';
    }
    if (!preg_match('/^\d+(\.\d{1,4})?$/', $raw)) {
        $errors[] = $label . ' must be a valid non-negative number.';
        return '';
    }
    return $raw;
}

function lmp_select($value, array $allowed, string $label, array &$errors): int
{
    $number = (int)$value;
    if (!in_array($number, $allowed, true)) $errors[] = 'Select a valid ' . $label . '.';
    return $number;
}

function lmp_save_parent(mysqli $con, int $id, array $data): int
{
    $columns = lmp_columns($con, 'jos_app_lmconfig');
    $spec = [
        'policyname' => 's',
        'month' => 'i',
        'year' => 'i',
        'orgid' => 'i',
        'monthgrace' => 'i',
        'calculate' => 'i',
    ];
    $fields = [];
    $types = '';
    $params = [];
    foreach ($spec as $field => $type) {
        if (!in_array($field, $columns, true)) continue;
        $fields[] = $field;
        $types .= $type;
        $params[] = $type === 'i' ? (int)$data[$field] : (string)$data[$field];
    }
    if (!$fields) throw new RuntimeException('No late mark policy fields available.');

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

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

function lmp_save_grid(mysqli $con, int $configId, array $rows): void
{
    $stmt = lmp_stmt($con, 'DELETE FROM jos_app_lmconfig_grid WHERE config_id=?');
    $stmt->bind_param('i', $configId);
    $stmt->execute();
    $stmt->close();

    $columns = lmp_columns($con, 'jos_app_lmconfig_grid');
    foreach ($rows as $row) {
        $spec = [
            'sr_no' => ['i', $row['sr_no']],
            'config_id' => ['i', $configId],
            'month' => ['i', $row['month']],
            'year' => ['i', $row['year']],
            'orgid' => ['i', $row['orgid']],
            'mintime' => ['i', $row['mintime']],
            'maxtime' => ['i', $row['maxtime']],
            'calculation' => ['i', $row['calculation']],
            'count' => ['s', $row['count']],
            'hrs' => ['s', $row['hrs']],
            'days' => ['s', $row['days']],
            'calculate' => ['i', $row['calculate']],
        ];
        $fields = [];
        $types = '';
        $params = [];
        foreach ($spec as $field => $item) {
            if (!in_array($field, $columns, true)) continue;
            $fields[] = $field;
            $types .= $item[0];
            $params[] = $item[0] === 'i' ? (int)$item[1] : (string)$item[1];
        }
        if (!$fields) continue;
        $stmt = lmp_stmt($con, 'INSERT INTO jos_app_lmconfig_grid (`' . implode('`,`', $fields) . '`) VALUES (' . implode(',', array_fill(0, count($fields), '?')) . ')');
        $stmt->bind_param($types, ...$params);
        if (!$stmt->execute()) throw new RuntimeException('Unable to save late mark policy slab row.');
        $stmt->close();
    }
}

function lmp_grid_rows(mysqli $con, int $configId): array
{
    $rows = [];
    $order = lmp_has_column($con, 'jos_app_lmconfig_grid', 'sr_no') ? 'sr_no ASC,id ASC' : 'mintime ASC,id ASC';
    $stmt = lmp_stmt($con, 'SELECT * FROM jos_app_lmconfig_grid WHERE config_id=? 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 lmp_history_key(mysqli $con): string
{
    if (lmp_has_column($con, 'jos_app_lmconfig_editlog', 'lmconfigid')) return 'lmconfigid';
    if (lmp_has_column($con, 'jos_app_lmconfig_editlog', 'config_id')) return 'config_id';
    return '';
}

function lmp_insert_history(mysqli $con, int $configId): void
{
    $historyColumns = lmp_columns($con, 'jos_app_lmconfig_editlog');
    if (!$historyColumns) return;
    $stmt = lmp_stmt($con, 'SELECT * FROM jos_app_lmconfig 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 === 'lmconfigid' || $column === 'config_id') {
            $fields[] = $column; $placeholders[] = '?'; $types .= 'i'; $params[] = $configId;
        } elseif ($column === 'date' || $column === 'sysdate' || $column === 'modifieddate') {
            $fields[] = $column; $placeholders[] = 'NOW()';
        } elseif ($column === 'modify_by' || $column === 'modified_by' || $column === 'modifed_by' || $column === 'userid') {
            $fields[] = $column; $placeholders[] = '?'; $types .= 'i'; $params[] = $userId;
        } elseif (array_key_exists($column, $source)) {
            $fields[] = $column; $placeholders[] = '?';
            if (is_numeric($source[$column]) && preg_match('/^-?\d+$/', (string)$source[$column])) {
                $types .= 'i'; $params[] = (int)$source[$column];
            } else {
                $types .= 's'; $params[] = (string)$source[$column];
            }
        }
    }
    if (!$fields) return;
    $stmt = lmp_stmt($con, 'INSERT INTO jos_app_lmconfig_editlog (`' . implode('`,`', $fields) . '`) VALUES (' . implode(',', $placeholders) . ')');
    if ($types !== '') $stmt->bind_param($types, ...$params);
    if (!$stmt->execute()) throw new RuntimeException('Unable to save late mark policy history.');
    $editLogId = (int)$con->insert_id;
    $stmt->close();

    if ($editLogId <= 0 || !lmp_columns($con, 'jos_app_lmconfig_grid_editlog')) return;
    $gridRows = lmp_grid_rows($con, $configId);
    $gridColumns = lmp_columns($con, 'jos_app_lmconfig_grid_editlog');
    foreach ($gridRows as $row) {
        $spec = [
            'sr_no' => ['i', $row['sr_no'] ?? 0],
            'config_id' => ['i', $editLogId],
            'grid_id' => ['i', $row['id'] ?? 0],
            'date' => ['now', null],
            'month' => ['i', $row['month'] ?? $source['month'] ?? 0],
            'year' => ['i', $row['year'] ?? $source['year'] ?? 0],
            'orgid' => ['i', $row['orgid'] ?? $source['orgid'] ?? 0],
            'mintime' => ['i', $row['mintime'] ?? 0],
            'maxtime' => ['i', $row['maxtime'] ?? 0],
            'calculation' => ['i', $row['calculation'] ?? 4],
            'count' => ['s', $row['count'] ?? ''],
            'hrs' => ['s', $row['hrs'] ?? ''],
            'days' => ['s', $row['days'] ?? ''],
            'calculate' => ['i', $row['calculate'] ?? $source['calculate'] ?? 0],
        ];
        $fields = [];
        $placeholders = [];
        $types = '';
        $params = [];
        foreach ($spec as $field => $item) {
            if (!in_array($field, $gridColumns, true)) continue;
            $fields[] = $field;
            if ($item[0] === 'now') {
                $placeholders[] = 'NOW()';
            } else {
                $placeholders[] = '?';
                $types .= $item[0];
                $params[] = $item[0] === 'i' ? (int)$item[1] : (string)$item[1];
            }
        }
        if (!$fields) continue;
        $stmt = lmp_stmt($con, 'INSERT INTO jos_app_lmconfig_grid_editlog (`' . implode('`,`', $fields) . '`) VALUES (' . implode(',', $placeholders) . ')');
        if ($types !== '') $stmt->bind_param($types, ...$params);
        if (!$stmt->execute()) throw new RuntimeException('Unable to save late mark policy grid history.');
        $stmt->close();
    }
}

function lmp_history_rows(mysqli $con, int $configId): array
{
    if (!lmp_columns($con, 'jos_app_lmconfig_editlog')) return [];
    $key = lmp_history_key($con);
    if ($key === '') return [];
    $order = lmp_has_column($con, 'jos_app_lmconfig_editlog', 'date') ? '`date` DESC,id DESC' : 'id DESC';
    $rows = [];
    $stmt = lmp_stmt($con, 'SELECT * FROM jos_app_lmconfig_editlog WHERE `' . $key . '`=? ORDER BY ' . $order);
    $stmt->bind_param('i', $configId);
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) $rows[] = $row;
    $stmt->close();

    if (!lmp_columns($con, 'jos_app_lmconfig_grid_editlog') || !lmp_has_column($con, 'jos_app_lmconfig_grid_editlog', 'config_id')) return $rows;
    $gridOrder = lmp_has_column($con, 'jos_app_lmconfig_grid_editlog', 'sr_no') ? 'sr_no ASC,id ASC' : 'mintime ASC,id ASC';
    foreach ($rows as &$row) {
        $row['grid'] = [];
        $logId = (int)($row['id'] ?? 0);
        if ($logId <= 0) continue;
        $stmt = lmp_stmt($con, 'SELECT * FROM jos_app_lmconfig_grid_editlog WHERE config_id=? ORDER BY ' . $gridOrder);
        $stmt->bind_param('i', $logId);
        $stmt->execute();
        $gridResult = $stmt->get_result();
        while ($grid = $gridResult->fetch_assoc()) $row['grid'][] = $grid;
        $stmt->close();
    }
    unset($row);
    return $rows;
}

function lmp_calc_label($value): string
{
    return (int)$value === 3 ? 'Hrs' : 'Count';
}

$payrollLocations = lmp_options($con, 'SELECT id,name FROM jos_app_payrolllocation ORDER BY name,id');
$months = lmp_options($con, 'SELECT id,month AS name FROM jos_app_mmonth ORDER BY id');
$years = lmp_options($con, 'SELECT id,year AS name,assessment FROM jos_app_year ORDER BY id DESC');
$payrollMap = $monthMap = $yearMap = [];
foreach ($payrollLocations as $row) $payrollMap[(int)$row['id']] = (string)$row['name'];
foreach ($months as $row) $monthMap[(int)$row['id']] = (string)$row['name'];
foreach ($years as $row) $yearMap[(int)$row['id']] = (string)$row['name'];
$calculateLabels = [0 => 'Daily', 1 => 'Weekly', 2 => 'Monthly'];
$calculationLabels = [4 => 'Count', 3 => 'Hrs'];

$mode = (string)($_GET['mode'] ?? '');
$editId = max(0, (int)($_GET['edit'] ?? 0));
$historyId = max(0, (int)($_GET['history'] ?? 0));
$viewId = max(0, (int)($_GET['view'] ?? 0));
$isHistory = $historyId > 0;
$isView = !$isHistory && $viewId > 0;
$isForm = !$isHistory && !$isView && ($mode === 'add' || $editId > 0);
$editRow = null;
$gridRows = [];
$historyParent = null;
$historyRows = [];
$viewParent = null;
$viewRows = [];

if (!$isHistory && !$isView && $mode === 'add' && empty($acl['can_add'])) {
    $_SESSION['flash_late_mark_policy_configuration'] = 'You do not have permission to add late mark policies.';
    redirect('/attendance/late-mark-policy-configuration.php');
}

if (!$isHistory && !$isView && $editId > 0 && empty($acl['can_edit'])) {
    $_SESSION['flash_late_mark_policy_configuration'] = 'You do not have permission to edit late mark policies.';
    redirect('/attendance/late-mark-policy-configuration.php');
}

if ($historyId > 0) {
    $stmt = lmp_stmt($con, 'SELECT c.*,p.name AS payroll_name,m.month AS month_name,y.year AS year_name FROM jos_app_lmconfig c LEFT JOIN jos_app_payrolllocation p ON p.id=c.orgid LEFT JOIN jos_app_mmonth m ON m.id=c.month LEFT JOIN jos_app_year y ON y.id=c.year WHERE c.id=? LIMIT 1');
    $stmt->bind_param('i', $historyId);
    $stmt->execute();
    $historyParent = $stmt->get_result()->fetch_assoc() ?: null;
    $stmt->close();
    if (!$historyParent) {
        $_SESSION['flash_late_mark_policy_configuration'] = 'Late Mark Policy Configuration was not found.';
        redirect('/attendance/late-mark-policy-configuration.php');
    }
    $historyRows = lmp_history_rows($con, $historyId);
}

if ($viewId > 0) {
    $stmt = lmp_stmt($con, 'SELECT c.*,p.name AS payroll_name,m.month AS month_name,y.year AS year_name FROM jos_app_lmconfig c LEFT JOIN jos_app_payrolllocation p ON p.id=c.orgid LEFT JOIN jos_app_mmonth m ON m.id=c.month LEFT JOIN jos_app_year y ON y.id=c.year WHERE c.id=? LIMIT 1');
    $stmt->bind_param('i', $viewId);
    $stmt->execute();
    $viewParent = $stmt->get_result()->fetch_assoc() ?: null;
    $stmt->close();
    if (!$viewParent) {
        $_SESSION['flash_late_mark_policy_configuration'] = 'Late Mark Policy Configuration was not found.';
        redirect('/attendance/late-mark-policy-configuration.php');
    }
    $viewRows = lmp_grid_rows($con, $viewId);
}

if (!$isHistory && !$isView && $editId > 0) {
    $stmt = lmp_stmt($con, 'SELECT * FROM jos_app_lmconfig WHERE id=? LIMIT 1');
    $stmt->bind_param('i', $editId);
    $stmt->execute();
    $editRow = $stmt->get_result()->fetch_assoc() ?: null;
    $stmt->close();
    if (!$editRow) {
        $_SESSION['flash_late_mark_policy_configuration'] = 'Late Mark Policy Configuration was not found.';
        redirect('/attendance/late-mark-policy-configuration.php');
    }
    $gridRows = lmp_grid_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 late mark policies.';
        if ($id === 0 && empty($acl['can_add'])) $errors[] = 'You do not have permission to add late mark policies.';
        if ($id > 0 && !lmp_exists($con, $id)) $errors[] = 'Late Mark Policy Configuration was not found.';

        $policyName = trim((string)($_POST['policyname'] ?? ''));
        if ($policyName === '') $errors[] = 'Policy name is required.';
        if (strlen($policyName) > 255) $errors[] = 'Policy name is too long.';

        $orgId = max(0, (int)($_POST['orgid'] ?? 0));
        $month = max(0, (int)($_POST['month'] ?? 0));
        $year = max(0, (int)($_POST['year'] ?? 0));
        if (!lmp_valid_id($con, 'jos_app_payrolllocation', $orgId)) $errors[] = 'Select a valid payroll location.';
        if (!lmp_valid_id($con, 'jos_app_mmonth', $month)) $errors[] = 'Select a valid month.';
        if (!lmp_valid_id($con, 'jos_app_year', $year)) $errors[] = 'Select a valid year.';

        $calculate = lmp_select($_POST['calculate'] ?? 0, [0, 1, 2], 'calculate cycle', $errors);
        $data = [
            'policyname' => $policyName,
            'month' => $month,
            'year' => $year,
            'orgid' => $orgId,
            'monthgrace' => lmp_int($_POST['monthgrace'] ?? '', 'Monthly grace period', $errors),
            'calculate' => $calculate,
        ];

        $mins = (array)($_POST['min'] ?? []);
        $maxes = (array)($_POST['max'] ?? []);
        $calcs = (array)($_POST['calculation'] ?? []);
        $counts = (array)($_POST['count'] ?? []);
        $hrsValues = (array)($_POST['hrs'] ?? []);
        $daysValues = (array)($_POST['days'] ?? []);
        $rowsToSave = [];
        foreach ($mins as $index => $minValue) {
            $rawMax = $maxes[$index] ?? '';
            $rawCount = $counts[$index] ?? '';
            $rawHrs = $hrsValues[$index] ?? '';
            $rawDays = $daysValues[$index] ?? '';
            if (trim((string)$minValue) === '' && trim((string)$rawMax) === '' && trim((string)$rawCount) === '' && trim((string)$rawHrs) === '' && trim((string)$rawDays) === '') continue;
            $rowNo = (int)$index + 1;
            $minTime = lmp_int($minValue, 'Min time row ' . $rowNo, $errors, 0, 999999, true);
            $maxTime = lmp_int($rawMax, 'Max time row ' . $rowNo, $errors, 0, 999999, true);
            if ($maxTime < $minTime) $errors[] = 'Max time must be greater than or equal to min time on row ' . $rowNo . '.';
            $calc = lmp_select($calcs[$index] ?? 4, [3, 4], 'calculation type on row ' . $rowNo, $errors);
            $count = $calc === 4 ? lmp_decimal($rawCount, 'Count row ' . $rowNo, $errors, true) : '';
            $hrs = lmp_decimal($rawHrs, 'Hrs row ' . $rowNo, $errors);
            $days = lmp_decimal($rawDays, 'Days row ' . $rowNo, $errors);
            if ($calc === 3 && $hrs === '') $errors[] = 'Hrs is required on row ' . $rowNo . ' when type is Hrs.';
            $rowsToSave[] = [
                'sr_no' => count($rowsToSave) + 1,
                'config_id' => $id,
                'month' => $month,
                'year' => $year,
                'orgid' => $orgId,
                'mintime' => $minTime,
                'maxtime' => $maxTime,
                'calculation' => $calc,
                'count' => $count,
                'hrs' => $hrs,
                'days' => $days,
                'calculate' => $calculate,
            ];
        }
        if (!$rowsToSave) $errors[] = 'Add at least one late mark slab row.';

        if (!$errors) {
            $con->begin_transaction();
            try {
                $savedId = lmp_save_parent($con, $id, $data);
                lmp_save_grid($con, $savedId, $rowsToSave);
                lmp_insert_history($con, $savedId);
                $con->commit();
                $_SESSION['flash_late_mark_policy_configuration'] = $id > 0 ? 'Late Mark Policy Configuration updated successfully.' : 'Late Mark Policy Configuration added successfully.';
                redirect('/attendance/late-mark-policy-configuration.php');
            } catch (Throwable $e) {
                $con->rollback();
                $errors[] = 'Unable to save the late mark policy. No changes were committed.';
            }
        }

        $isForm = true;
        $isHistory = false;
        $isView = false;
        $editId = $id;
        $editRow = $data + ['id' => $id];
        $gridRows = $rowsToSave;
    }
}

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

if (!$isForm && !$isHistory && !$isView) {
    $where = ['1=1'];
    $types = '';
    $params = [];
    if ($filterQ !== '') { $where[] = 'c.policyname LIKE ?'; $types .= 's'; $params[] = '%' . $filterQ . '%'; }
    if ($filterOrg > 0) { $where[] = 'c.orgid=?'; $types .= 'i'; $params[] = $filterOrg; }
    if ($filterMonth > 0) { $where[] = 'c.month=?'; $types .= 'i'; $params[] = $filterMonth; }
    if ($filterYear > 0) { $where[] = 'c.year=?'; $types .= 'i'; $params[] = $filterYear; }
    $whereSql = implode(' AND ', $where);

    $stmt = lmp_stmt($con, 'SELECT COUNT(*) AS total FROM jos_app_lmconfig c 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;
    $historyKey = lmp_history_key($con);
    $historySelect = $historyKey !== '' ? ',(SELECT COUNT(*) FROM jos_app_lmconfig_editlog e WHERE e.`' . $historyKey . '`=c.id) AS history_count' : ',0 AS history_count';

    $stmt = lmp_stmt($con, 'SELECT c.*,p.name AS payroll_name,m.month AS month_name,y.year AS year_name' . $historySelect . ' FROM jos_app_lmconfig c LEFT JOIN jos_app_payrolllocation p ON p.id=c.orgid LEFT JOIN jos_app_mmonth m ON m.id=c.month LEFT JOIN jos_app_year y ON y.id=c.year WHERE ' . $whereSql . ' ORDER BY DATE(CONCAT(y.year, "-", c.month, "-01")) DESC,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 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 = [['mintime' => '', 'maxtime' => '', 'calculation' => 4, 'count' => '', 'hrs' => '', 'days' => '']];

console_header('Late Mark Policy 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>Attendance Settings</span><i class="fa-solid fa-chevron-right text-[9px]"></i><span class="text-brand-600">Late Mark Policy Configuration</span></div><h1 class="text-2xl font-bold text-slate-900">Late Mark Policy Configuration</h1><p class="mt-1 text-sm text-slate-500">Configure late mark grace, calculation cycle, and count/hour deduction slabs.</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">Late Mark Policy History</h2><p class="mt-1 text-xs font-medium text-slate-400"><?= h((string)($historyParent['policyname'] ?? '')) ?> · <?= h((string)($historyParent['payroll_name'] ?? '')) ?></p></div><a href="/attendance/late-mark-policy-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-[1220px] text-left text-sm"><thead class="bg-slate-50 text-[10px] uppercase tracking-wider text-slate-400"><tr><th class="px-5 py-4">Date</th><th class="px-5 py-4">Policy</th><th class="px-5 py-4">Payroll</th><th class="px-5 py-4">Month</th><th class="px-5 py-4">Calculate</th><th class="px-5 py-4">Month Grace</th><th class="px-5 py-4">Slabs</th></tr></thead><tbody class="divide-y divide-slate-100">
    <?php if(!$historyRows): ?><tr><td colspan="7" 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((string)($row['date'] ?? '')) ?></td><td class="px-5 py-4 font-bold text-slate-800"><?= h((string)($row['policyname'] ?? '')) ?></td><td class="px-5 py-4"><?= h($payrollMap[(int)($row['orgid'] ?? 0)] ?? (string)($row['orgid'] ?? '')) ?></td><td class="px-5 py-4"><?= h($monthMap[(int)($row['month'] ?? 0)] ?? (string)($row['month'] ?? '')) ?> <?= h($yearMap[(int)($row['year'] ?? 0)] ?? (string)($row['year'] ?? '')) ?></td><td class="px-5 py-4"><?= h($calculateLabels[(int)($row['calculate'] ?? 0)] ?? '') ?></td><td class="px-5 py-4"><?= h((string)($row['monthgrace'] ?? '')) ?> MM</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">Min</th><th class="px-3 py-2 text-left">Max</th><th class="px-3 py-2 text-left">Type</th><th class="px-3 py-2 text-left">Count</th><th class="px-3 py-2 text-left">Hrs</th><th class="px-3 py-2 text-left">Days</th></tr></thead><tbody><?php if(empty($row['grid'])): ?><tr><td colspan="7" 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['mintime'] ?? '')) ?></td><td class="px-3 py-2 font-semibold"><?= h((string)($grid['maxtime'] ?? '')) ?></td><td class="px-3 py-2"><?= h(lmp_calc_label($grid['calculation'] ?? 4)) ?></td><td class="px-3 py-2"><?= h((string)($grid['count'] ?? '')) ?></td><td class="px-3 py-2"><?= h((string)($grid['hrs'] ?? '')) ?></td><td class="px-3 py-2"><?= h((string)($grid['days'] ?? '')) ?></td></tr><?php endforeach; ?></tbody></table></div></td></tr><?php endforeach; ?>
  </tbody></table></div>
</section>
<?php elseif ($isView): ?>
<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"><?= h((string)($viewParent['policyname'] ?? 'Late Mark Policy')) ?></h2><p class="mt-1 text-xs font-medium text-slate-400"><?= h((string)($viewParent['payroll_name'] ?? '')) ?> · <?= h((string)($viewParent['month_name'] ?? '')) ?> <?= h((string)($viewParent['year_name'] ?? '')) ?></p></div><a href="/attendance/late-mark-policy-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-[860px] 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">Min Time (MM)</th><th class="px-5 py-4">Max Time (MM)</th><th class="px-5 py-4">Type</th><th class="px-5 py-4">Count</th><th class="px-5 py-4">Hrs (MM)</th><th class="px-5 py-4">Days</th></tr></thead><tbody class="divide-y divide-slate-100"><?php if(!$viewRows): ?><tr><td colspan="7" class="px-6 py-14 text-center font-semibold text-slate-400">No slab rows found.</td></tr><?php endif; ?><?php foreach($viewRows as $index=>$row): ?><tr><td class="px-5 py-4 font-semibold text-slate-500"><?= $index + 1 ?></td><td class="px-5 py-4 font-semibold"><?= h((string)($row['mintime'] ?? '')) ?></td><td class="px-5 py-4 font-semibold"><?= h((string)($row['maxtime'] ?? '')) ?></td><td class="px-5 py-4"><?= h(lmp_calc_label($row['calculation'] ?? 4)) ?></td><td class="px-5 py-4"><?= h((string)($row['count'] ?? '')) ?></td><td class="px-5 py-4"><?= h((string)($row['hrs'] ?? '')) ?></td><td class="px-5 py-4"><?= h((string)($row['days'] ?? '')) ?></td></tr><?php endforeach; ?></tbody></table></div>
</section>
<?php elseif ($isForm): ?>
<form method="post" id="late-mark-policy-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-person-running"></i></span><div><h2 class="font-bold text-slate-800"><?= (int)$value('id',0)>0?'Edit Late Mark Policy':'New Late Mark Policy' ?></h2><p class="text-xs text-slate-400">Fields marked with * are required.</p></div></div><a href="/attendance/late-mark-policy-configuration.php" class="rounded-lg border border-slate-200 bg-white px-4 py-2 text-sm font-bold text-slate-600 hover:bg-slate-50"><i class="fa-solid fa-arrow-left mr-2"></i>Back to List</a></div>
    <div class="grid gap-3 md:grid-cols-4">
      <label class="text-sm font-semibold text-slate-700">Payroll Location *<select name="orgid" required class="<?= $input ?>"><option value="">Select Payroll Location</option><?php foreach($payrollLocations as $option): ?><option value="<?= (int)$option['id'] ?>" <?= (int)$value('orgid')===(int)$option['id']?'selected':'' ?>><?= h($option['name']) ?></option><?php endforeach; ?></select></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>
      <label class="text-sm font-semibold text-slate-700">Policy Name *<input name="policyname" required maxlength="255" value="<?= h((string)$value('policyname')) ?>" class="<?= $input ?>" placeholder="Policy Name"></label>
      <label class="text-sm font-semibold text-slate-700">Calculate<select name="calculate" class="<?= $input ?>"><?php foreach($calculateLabels as $k=>$label): ?><option value="<?= $k ?>" <?= (int)$value('calculate',0)===$k?'selected':'' ?>><?= h($label) ?></option><?php endforeach; ?></select></label>
      <label class="text-sm font-semibold text-slate-700 md:col-span-2">Monthly Grace Period for Late Mark Calculation (MM)<input name="monthgrace" inputmode="numeric" pattern="\d*" value="<?= h((string)$value('monthgrace')) ?>" class="<?= $input ?>" placeholder="MM"><span class="mt-1 block text-xs text-red-500">For eg. Component Late Mark - Grace Period.</span></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">Late Mark Slabs</h2><p class="mt-1 text-xs font-medium text-slate-400">Set minute ranges and apply a count or hour/day deduction rule.</p></div><button type="button" id="add-lm-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-[980px] 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">Min Time (MM)</th><th class="px-5 py-4">Max Time (MM)</th><th class="px-5 py-4">Type</th><th class="px-5 py-4">Count</th><th class="px-5 py-4">Hrs (MM)</th><th class="px-5 py-4">Days</th><th class="px-5 py-4 text-right w-24">Action</th></tr></thead><tbody id="lm-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="min[]" inputmode="numeric" pattern="\d*" required value="<?= h((string)($row['mintime'] ?? $row['min'] ?? '')) ?>" class="<?= $input ?> mt-0" placeholder="Min"></td><td class="px-5 py-4"><input name="max[]" inputmode="numeric" pattern="\d*" required value="<?= h((string)($row['maxtime'] ?? $row['max'] ?? '')) ?>" class="<?= $input ?> mt-0" placeholder="Max"></td><td class="px-5 py-4"><select name="calculation[]" class="<?= $input ?> mt-0 js-calc"><?php foreach($calculationLabels as $k=>$label): ?><option value="<?= $k ?>" <?= (int)($row['calculation'] ?? 4)===$k?'selected':'' ?>><?= h($label) ?></option><?php endforeach; ?></select></td><td class="px-5 py-4"><input name="count[]" inputmode="decimal" value="<?= h((string)($row['count'] ?? '')) ?>" class="<?= $input ?> mt-0 js-count" placeholder="Count"></td><td class="px-5 py-4"><input name="hrs[]" inputmode="decimal" value="<?= h((string)($row['hrs'] ?? '')) ?>" class="<?= $input ?> mt-0 js-hrs" placeholder="Hrs"></td><td class="px-5 py-4"><input name="days[]" inputmode="decimal" value="<?= h((string)($row['days'] ?? '')) ?>" class="<?= $input ?> mt-0" placeholder="Days"></td><td class="px-5 py-4 text-right"><button type="button" class="remove-lm-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/late-mark-policy-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 Policy</button></div>
</form>
<template id="lm-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="min[]" inputmode="numeric" pattern="\d*" required class="<?= $input ?> mt-0" placeholder="Min"></td><td class="px-5 py-4"><input name="max[]" inputmode="numeric" pattern="\d*" required class="<?= $input ?> mt-0" placeholder="Max"></td><td class="px-5 py-4"><select name="calculation[]" class="<?= $input ?> mt-0 js-calc"><?php foreach($calculationLabels as $k=>$label): ?><option value="<?= $k ?>"><?= h($label) ?></option><?php endforeach; ?></select></td><td class="px-5 py-4"><input name="count[]" inputmode="decimal" class="<?= $input ?> mt-0 js-count" placeholder="Count"></td><td class="px-5 py-4"><input name="hrs[]" inputmode="decimal" class="<?= $input ?> mt-0 js-hrs" placeholder="Hrs"></td><td class="px-5 py-4"><input name="days[]" inputmode="decimal" class="<?= $input ?> mt-0" placeholder="Days"></td><td class="px-5 py-4 text-right"><button type="button" class="remove-lm-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('lm-rows'),add=document.getElementById('add-lm-row'),tpl=document.getElementById('lm-row-template');const syncRow=row=>{const calc=row.querySelector('.js-calc'),count=row.querySelector('.js-count'),hrs=row.querySelector('.js-hrs');if(!calc||!count||!hrs)return;const isCount=calc.value==='4';count.readOnly=!isCount;count.required=isCount;hrs.required=!isCount;if(!isCount)count.value='';count.classList.toggle('bg-slate-50',!isCount);};const sync=()=>{[...body.querySelectorAll('tr')].forEach((row,index)=>{row.querySelector('.row-number').textContent=index+1;syncRow(row);});};add.addEventListener('click',()=>{body.appendChild(tpl.content.cloneNode(true));sync();});body.addEventListener('click',event=>{const button=event.target.closest('.remove-lm-row');if(!button)return;if(body.querySelectorAll('tr').length===1){button.closest('tr').querySelectorAll('input').forEach(input=>input.value='');return;}button.closest('tr').remove();sync();});body.addEventListener('change',event=>{if(event.target.matches('.js-calc'))syncRow(event.target.closest('tr'));});sync();})();</script>
<?php else: ?>
<section class="overflow-hidden rounded-2xl border border-slate-100 bg-white shadow-sm">
  <div class="flex flex-col gap-3 border-b border-slate-100 px-5 py-4 sm:flex-row sm:items-center sm:justify-between"><div><h2 class="font-bold text-slate-800">Late Mark Policy List</h2><p class="mt-1 text-xs font-medium text-slate-400">Policies are ordered by latest configured 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-6"><input name="q" value="<?= h($filterQ) ?>" class="<?= $selectSmall ?>" placeholder="Search policy"><select name="org" class="<?= $selectSmall ?>"><option value="0">All Payroll Locations</option><?php foreach($payrollLocations as $option): ?><option value="<?= (int)$option['id'] ?>" <?= $filterOrg===(int)$option['id']?'selected':'' ?>><?= h($option['name']) ?></option><?php endforeach; ?></select><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/late-mark-policy-configuration.php" class="rounded-xl border border-slate-200 px-5 py-2.5 text-sm font-bold text-slate-600">Clear</a></div></form>
  <div class="overflow-x-auto"><table class="w-full min-w-[1180px] text-left text-sm"><thead class="bg-slate-50 text-[10px] 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">Payroll Location</th><th class="px-5 py-4">Monthly Grace</th><th class="px-5 py-4">Month</th><th class="px-5 py-4">Year</th><th class="px-5 py-4">Calculate</th><th class="px-5 py-4 text-right">Actions</th></tr></thead><tbody class="divide-y divide-slate-100">
    <?php if(!$rows): ?><tr><td colspan="8" class="px-6 py-14 text-center font-semibold text-slate-400">No late mark 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((string)($row['policyname'] ?? '')) ?></div><?php if((int)$row['history_count']>1): ?><div class="mt-1 text-xs font-semibold text-slate-400">History <?= (int)$row['history_count'] ?></div><?php endif; ?></td><td class="px-5 py-4 font-semibold text-slate-700"><?= h($row['payroll_name'] ?: ($payrollMap[(int)$row['orgid']] ?? '')) ?></td><td class="px-5 py-4"><?= h((string)($row['monthgrace'] ?? '')) ?> MM</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"><?= h($calculateLabels[(int)($row['calculate'] ?? 0)] ?? '') ?></td><td class="px-5 py-4"><div class="flex justify-end gap-2"><a href="?view=<?= (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="View Slabs"><i class="fa-solid fa-table-list"></i></a><?php if((int)$row['history_count']>1): ?><a href="?history=<?= (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="History"><i class="fa-solid fa-clock-rotate-left"></i></a><?php endif; ?><?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; ?></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'=>$filterQ,'org'=>$filterOrg,'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(); ?>
