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

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

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

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

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

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

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

function mlwf_valid_ids(mysqli $con, string $table, array $ids): array
{
    if (!in_array($table, ['jos_app_mmonth', 'jos_app_designation'], true)) {
        return [];
    }
    $ids = array_values(array_unique(array_filter(array_map('intval', $ids), static fn($id) => $id > 0)));
    if (!$ids) {
        return [];
    }
    $placeholders = implode(',', array_fill(0, count($ids), '?'));
    $types = str_repeat('i', count($ids));
    $stmt = mlwf_stmt($con, "SELECT id FROM `$table` WHERE id IN ($placeholders)");
    $stmt->bind_param($types, ...$ids);
    $stmt->execute();
    $result = $stmt->get_result();
    $valid = [];
    while ($row = $result->fetch_assoc()) {
        $valid[] = (int)$row['id'];
    }
    $stmt->close();
    $validLookup = array_flip($valid);
    return array_values(array_filter($ids, static fn($id) => isset($validLookup[$id])));
}

function mlwf_sanitize_ids(array $ids): array
{
    return array_values(array_unique(array_filter(array_map('intval', $ids), static fn($id) => $id > 0)));
}

function mlwf_fetch_row(mysqli $con, int $id): ?array
{
    $stmt = mlwf_stmt($con, 'SELECT * FROM jos_app_mlwf WHERE id=? LIMIT 1');
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc() ?: null;
    $stmt->close();
    return $row;
}

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

function mlwf_save_row(mysqli $con, int $id, array $data): int
{
    if ($id > 0) {
        $stmt = mlwf_stmt($con, 'UPDATE jos_app_mlwf SET month=?, year=?, amount=?, apply_month=?, designation=?, conditn=?, emp_mlwf=?, empr_mlwf=? WHERE id=?');
        $stmt->bind_param('iidssiddi', $data['month'], $data['year'], $data['amount'], $data['apply_month'], $data['designation'], $data['conditn'], $data['emp_mlwf'], $data['empr_mlwf'], $id);
        if (!$stmt->execute()) {
            throw new RuntimeException('Unable to update MLWF configuration.');
        }
        $stmt->close();
        return $id;
    }

    $stmt = mlwf_stmt($con, 'INSERT INTO jos_app_mlwf (month, year, amount, apply_month, designation, conditn, emp_mlwf, empr_mlwf) VALUES (?,?,?,?,?,?,?,?)');
    $stmt->bind_param('iidssidd', $data['month'], $data['year'], $data['amount'], $data['apply_month'], $data['designation'], $data['conditn'], $data['emp_mlwf'], $data['empr_mlwf']);
    if (!$stmt->execute()) {
        throw new RuntimeException('Unable to add MLWF configuration.');
    }
    $savedId = (int)$con->insert_id;
    $stmt->close();
    return $savedId;
}

function mlwf_insert_history(mysqli $con, int $configId): void
{
    $row = mlwf_fetch_row($con, $configId);
    if (!$row) {
        return;
    }
    $userId = (int)(current_user()['id'] ?? 0);
    $stmt = mlwf_stmt($con, 'INSERT INTO jos_app_mlwf_editlog (mlwfid, date, month, year, amount, apply_month, designation, conditn, emp_mlwf, empr_mlwf, modify_by) VALUES (?, NOW(), ?, ?, ?, ?, ?, ?, ?, ?, ?)');
    $month = (int)$row['month'];
    $year = (int)$row['year'];
    $amount = (float)$row['amount'];
    $applyMonth = (string)$row['apply_month'];
    $designation = (string)$row['designation'];
    $condition = (int)$row['conditn'];
    $employee = (float)$row['emp_mlwf'];
    $employer = (float)$row['empr_mlwf'];
    $stmt->bind_param('iiidssiddi', $configId, $month, $year, $amount, $applyMonth, $designation, $condition, $employee, $employer, $userId);
    if (!$stmt->execute()) {
        throw new RuntimeException('Unable to save MLWF configuration history.');
    }
    $stmt->close();
}

function mlwf_history_rows(mysqli $con, int $configId): array
{
    $rows = [];
    $stmt = mlwf_stmt($con, 'SELECT * FROM jos_app_mlwf_editlog WHERE mlwfid=? ORDER BY date DESC,id DESC');
    $stmt->bind_param('i', $configId);
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $rows[] = $row;
    }
    $stmt->close();
    return $rows;
}

function mlwf_csv_ids($csv): array
{
    if ($csv === null || trim((string)$csv) === '') {
        return [];
    }
    return array_values(array_unique(array_filter(array_map('intval', explode(',', (string)$csv)), static fn($id) => $id > 0)));
}

function mlwf_names($csv, array $map): string
{
    $names = [];
    foreach (mlwf_csv_ids($csv) as $id) {
        $names[] = $map[$id] ?? ('#' . $id);
    }
    return implode(', ', $names);
}

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

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

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

function mlwf_condition_label(int $condition): string
{
    if ($condition === 0) {
        return 'Greater ( > )';
    }
    if ($condition === 1) {
        return 'Less ( < )';
    }
    return 'None';
}

function mlwf_ensure_year_option(array &$formYears, array $yearMap, int $yearId): void
{
    if ($yearId <= 0) {
        return;
    }
    foreach ($formYears as $row) {
        if ((int)$row['id'] === $yearId) {
            return;
        }
    }
    $label = $yearMap[$yearId] ?? (string)$yearId;
    $formYears[] = ['id' => $yearId, 'year' => $label, 'assessment' => $label];
}

function mlwf_ensure_designation_options(array &$designations, array $selectedIds, array $designationMap): void
{
    $known = [];
    foreach ($designations as $row) {
        $known[(int)$row['id']] = true;
    }
    foreach ($selectedIds as $id) {
        if ($id > 0 && !isset($known[$id])) {
            $designations[] = ['id' => $id, 'designation' => $designationMap[$id] ?? ('#' . $id)];
            $known[$id] = true;
        }
    }
}

$months = mlwf_options($con, 'SELECT id,month FROM jos_app_mmonth ORDER BY id ASC');
$years = mlwf_options($con, 'SELECT id,year,assessment FROM jos_app_year ORDER BY id DESC');
$formYears = mlwf_options($con, 'SELECT id,year,assessment FROM jos_app_year ORDER BY id DESC LIMIT 3');
$designations = mlwf_options($con, 'SELECT id,designation FROM jos_app_designation ORDER BY id ASC');

$monthMap = [];
foreach ($months as $row) {
    $monthMap[(int)$row['id']] = (string)$row['month'];
}
$yearMap = [];
foreach ($years as $row) {
    $yearMap[(int)$row['id']] = trim((string)($row['assessment'] ?: $row['year']));
}
$designationMap = [];
foreach ($designations as $row) {
    $designationMap[(int)$row['id']] = (string)$row['designation'];
}

$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, 'month' => '', 'year' => '', 'amount' => '', 'apply_month' => '', 'designation' => '', 'conditn' => '2', 'emp_mlwf' => '', 'empr_mlwf' => ''];
$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;
    $editRow = mlwf_fetch_row($con, $editId) ?: [];
    if (!$editRow) {
        $_SESSION['flash_mlwf_configuration'] = 'MLWF Configuration was not found.';
        redirect('/payroll/mlwf-configuration.php');
    }
    mlwf_ensure_year_option($formYears, $yearMap, mlwf_int_row($editRow, 'year'));
    mlwf_ensure_designation_options($designations, mlwf_csv_ids(mlwf_text($editRow, 'designation')), $designationMap);
}

if ($historyId > 0) {
    $isHistory = true;
    $historyParent = mlwf_fetch_row($con, $historyId);
    if (!$historyParent) {
        $_SESSION['flash_mlwf_configuration'] = 'MLWF Configuration was not found.';
        redirect('/payroll/mlwf-configuration.php');
    }
    $historyRows = mlwf_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 MLWF configurations.';
        }
        if ($id === 0 && empty($acl['can_add'])) {
            $errors[] = 'You do not have permission to add MLWF configurations.';
        }
        if ($id > 0 && !mlwf_exists($con, $id)) {
            $errors[] = 'MLWF Configuration was not found.';
        }

        $month = (int)($_POST['month'] ?? 0);
        $year = (int)($_POST['year'] ?? 0);
        $condition = (int)($_POST['conditn'] ?? -1);
        $applyMonthIds = mlwf_valid_ids($con, 'jos_app_mmonth', (array)($_POST['apply_month'] ?? []));
        $postedDesignationIds = mlwf_sanitize_ids((array)($_POST['designation'] ?? []));
        $validDesignationIds = mlwf_valid_ids($con, 'jos_app_designation', $postedDesignationIds);
        $legacyDesignationIds = [];
        if ($id > 0) {
            $originalRow = mlwf_fetch_row($con, $id);
            $legacyDesignationIds = mlwf_csv_ids(mlwf_text($originalRow ?? [], 'designation'));
        }
        $validDesignationLookup = array_flip($validDesignationIds);
        $legacyDesignationLookup = array_flip($legacyDesignationIds);
        $designationIds = [];
        foreach ($postedDesignationIds as $designationId) {
            if (isset($validDesignationLookup[$designationId]) || isset($legacyDesignationLookup[$designationId])) {
                $designationIds[] = $designationId;
            }
        }

        if (!mlwf_lookup_exists($con, 'jos_app_mmonth', $month)) {
            $errors[] = 'Select a valid Month.';
        }
        if (!mlwf_lookup_exists($con, 'jos_app_year', $year)) {
            $errors[] = 'Select a valid Year.';
        }
        if (!$applyMonthIds) {
            $errors[] = 'Select at least one valid Policy Apply Month.';
        }
        if (count($designationIds) !== count($postedDesignationIds)) {
            $errors[] = 'Select valid Designation exclusion values.';
        }
        if (!in_array($condition, [0, 1, 2], true)) {
            $errors[] = 'Select a valid Gross Salary condition.';
        }

        $amount = mlwf_money($_POST['amount'] ?? '', 'Gross Salary', $errors);
        $employeeMlwf = mlwf_money($_POST['emp_mlwf'] ?? '', 'Employee MLWF', $errors);
        $employerMlwf = mlwf_money($_POST['empr_mlwf'] ?? '', 'Employer MLWF', $errors);

        $data = [
            'month' => $month,
            'year' => $year,
            'amount' => $amount,
            'apply_month' => implode(',', $applyMonthIds),
            'designation' => implode(',', $designationIds),
            'conditn' => $condition,
            'emp_mlwf' => $employeeMlwf,
            'empr_mlwf' => $employerMlwf,
        ];

        if (!$errors) {
            $con->begin_transaction();
            try {
                $savedId = mlwf_save_row($con, $id, $data);
                mlwf_insert_history($con, $savedId);
                $con->commit();
                $_SESSION['flash_mlwf_configuration'] = $id > 0 ? 'MLWF Configuration updated successfully.' : 'MLWF Configuration added successfully.';
                redirect('/payroll/mlwf-configuration.php');
            } catch (Throwable $e) {
                $con->rollback();
                $errors[] = 'Unable to save the MLWF configuration. No changes were committed.';
            }
        }
        $isForm = true;
        $isHistory = false;
        $editRow = $data + ['id' => $id];
        mlwf_ensure_year_option($formYears, $yearMap, $year);
        mlwf_ensure_designation_options($designations, $designationIds, $designationMap);
    }
}

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

if (!$isForm && !$isHistory) {
    $where = ['1=1'];
    $types = '';
    $params = [];
    if ($filterQ !== '') {
        $where[] = '(CAST(c.amount AS CHAR) LIKE ? OR CAST(c.emp_mlwf AS CHAR) LIKE ? OR CAST(c.empr_mlwf AS CHAR) LIKE ? OR m.month LIKE ? OR y.year LIKE ? OR y.assessment LIKE ?)';
        $types .= 'ssssss';
        for ($i = 0; $i < 6; $i++) {
            $params[] = '%' . $filterQ . '%';
        }
    }
    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 = mlwf_stmt($con, 'SELECT COUNT(*) AS total FROM jos_app_mlwf c LEFT JOIN jos_app_mmonth m ON m.id=c.month 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 = mlwf_stmt($con, 'SELECT c.*,m.month AS month_name,COALESCE(NULLIF(y.assessment, \'\'), y.year, c.year) AS year_label,(SELECT COUNT(*) FROM jos_app_mlwf_editlog e WHERE e.mlwfid=c.id) AS history_count FROM jos_app_mlwf c 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 c.year DESC,c.month ASC,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;
};
$selectedApplyMonths = mlwf_csv_ids($value('apply_month'));
$selectedDesignations = mlwf_csv_ids($value('designation'));
$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';
$multiInput = 'mt-1 min-h-[118px] 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('MLWF 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">MLWF Configuration</span></div>
    <h1 class="text-2xl font-bold text-slate-900">MLWF Configuration</h1>
    <p class="mt-1 text-sm text-slate-500">Configure labour welfare fund contribution rules by month and 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">MLWF Configuration History</h2><p class="mt-1 text-xs font-medium text-slate-400"><?= h($monthMap[mlwf_int_row($historyParent ?? [], 'month')] ?? '') ?> <?= h($yearMap[mlwf_int_row($historyParent ?? [], 'year')] ?? '') ?></p></div><a href="/payroll/mlwf-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-[1080px] 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">Month</th><th class="px-5 py-4">Year</th><th class="px-5 py-4">Apply Months</th><th class="px-5 py-4">Excluded Designations</th><th class="px-5 py-4">Gross Salary</th><th class="px-5 py-4">Condition</th><th class="px-5 py-4">Employee MLWF</th><th class="px-5 py-4">Employer MLWF</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="10" 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(mlwf_text($row, 'date')) ?></td><td class="px-5 py-4"><?= h($monthMap[mlwf_int_row($row, 'month')] ?? ('#' . mlwf_int_row($row, 'month'))) ?></td><td class="px-5 py-4"><?= h($yearMap[mlwf_int_row($row, 'year')] ?? (string)mlwf_int_row($row, 'year')) ?></td><td class="px-5 py-4"><?= h(mlwf_names(mlwf_text($row, 'apply_month'), $monthMap)) ?></td><td class="px-5 py-4"><?= h(mlwf_names(mlwf_text($row, 'designation'), $designationMap)) ?></td><td class="px-5 py-4"><?= h(mlwf_amount_label(mlwf_text($row, 'amount'))) ?></td><td class="px-5 py-4"><?= h(mlwf_condition_label(mlwf_int_row($row, 'conditn', 2))) ?></td><td class="px-5 py-4 font-bold text-slate-800"><?= h(mlwf_amount_label(mlwf_text($row, 'emp_mlwf'))) ?></td><td class="px-5 py-4 font-bold text-slate-800"><?= h(mlwf_amount_label(mlwf_text($row, 'empr_mlwf'))) ?></td><td class="px-5 py-4"><?= (int)mlwf_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-hand-holding-dollar"></i></span><div><h2 class="font-bold text-slate-800"><?= (int)$value('id', 0) > 0 ? 'Edit MLWF Configuration' : 'New MLWF Configuration' ?></h2><p class="text-xs text-slate-400">Fields marked with * are required.</p></div></div><a href="/payroll/mlwf-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">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['month']) ?></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 ($formYears as $option): $label = trim((string)($option['assessment'] ?: $option['year'])); ?><option value="<?= (int)$option['id'] ?>" <?= (int)$value('year') === (int)$option['id'] ? 'selected' : '' ?>><?= h($label) ?></option><?php endforeach; ?></select></label>
      <label class="text-sm font-semibold text-slate-700">Gross Salary *<input type="number" step="0.01" min="0" name="amount" required value="<?= h((string)$value('amount')) ?>" class="<?= $input ?>" placeholder="Gross Salary"></label>
      <label class="text-sm font-semibold text-slate-700">Gross Salary Apply MLWF *<select name="conditn" required class="<?= $input ?>"><option value="2" <?= (int)$value('conditn', 2) === 2 ? 'selected' : '' ?>>None</option><option value="0" <?= (int)$value('conditn', 2) === 0 ? 'selected' : '' ?>>Greater ( &gt; )</option><option value="1" <?= (int)$value('conditn', 2) === 1 ? 'selected' : '' ?>>Less ( &lt; )</option></select></label>
      <label class="text-sm font-semibold text-slate-700">Employee MLWF *<input type="number" step="0.01" min="0" name="emp_mlwf" required value="<?= h((string)$value('emp_mlwf')) ?>" class="<?= $input ?>" placeholder="Employee MLWF"></label>
      <label class="text-sm font-semibold text-slate-700">Employer MLWF *<input type="number" step="0.01" min="0" name="empr_mlwf" required value="<?= h((string)$value('empr_mlwf')) ?>" class="<?= $input ?>" placeholder="Employer MLWF"></label>
      <label class="text-sm font-semibold text-slate-700 xl:col-span-2">Policy Apply Month *<select name="apply_month[]" required multiple class="<?= $multiInput ?>"><?php foreach ($months as $option): ?><option value="<?= (int)$option['id'] ?>" <?= in_array((int)$option['id'], $selectedApplyMonths, true) ? 'selected' : '' ?>><?= h($option['month']) ?></option><?php endforeach; ?></select></label>
      <label class="text-sm font-semibold text-slate-700 xl:col-span-2">Designation Not Apply MLWF<select name="designation[]" multiple class="<?= $multiInput ?>"><?php foreach ($designations as $option): ?><option value="<?= (int)$option['id'] ?>" <?= in_array((int)$option['id'], $selectedDesignations, true) ? 'selected' : '' ?>><?= h($option['designation']) ?></option><?php endforeach; ?></select></label>
    </div>
  </section>
  <div class="flex flex-wrap justify-end gap-2"><a href="/payroll/mlwf-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">MLWF Configuration List</h2><p class="mt-1 text-xs font-medium text-slate-400">MLWF rules are ordered by latest year and month.</p></div><?php if (!empty($acl['can_add'])): ?><a href="?mode=add" class="inline-flex items-center justify-center gap-2 rounded-lg bg-brand-600 px-4 py-2.5 text-sm font-bold text-white shadow-sm hover:bg-brand-700"><i class="fa-solid fa-plus"></i>Add</a><?php endif; ?></div>
  <form method="get" class="grid gap-3 border-b border-slate-100 p-5 md:grid-cols-2 xl:grid-cols-5"><input name="q" value="<?= h($filterQ) ?>" class="<?= $filterInput ?>" placeholder="Search month, year, or amount"><select name="month" class="<?= $filterInput ?>"><option value="">All Months</option><?php foreach ($months as $option): ?><option value="<?= (int)$option['id'] ?>" <?= $filterMonth === (int)$option['id'] ? 'selected' : '' ?>><?= h($option['month']) ?></option><?php endforeach; ?></select><select name="year" class="<?= $filterInput ?>"><option value="">All Years</option><?php foreach ($years as $option): $label = trim((string)($option['assessment'] ?: $option['year'])); ?><option value="<?= (int)$option['id'] ?>" <?= $filterYear === (int)$option['id'] ? 'selected' : '' ?>><?= h($label) ?></option><?php endforeach; ?></select><div class="flex gap-2 xl:col-span-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="/payroll/mlwf-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-[1160px] 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">Month</th><th class="px-5 py-4">Year</th><th class="px-5 py-4">Policy Apply Months</th><th class="px-5 py-4">Exclude Designation</th><th class="px-5 py-4">Gross Salary</th><th class="px-5 py-4">Salary Condition</th><th class="px-5 py-4">Employee MLWF</th><th class="px-5 py-4">Employer MLWF</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="10" class="px-6 py-14 text-center font-semibold text-slate-400">No MLWF 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(mlwf_text($row, 'month_name', $monthMap[mlwf_int_row($row, 'month')] ?? '')) ?><?php if (mlwf_int_row($row, 'history_count') > 0): ?><div class="mt-1 text-xs font-semibold text-slate-400">History <?= mlwf_int_row($row, 'history_count') ?></div><?php endif; ?></td><td class="px-5 py-4"><?= h(mlwf_text($row, 'year_label', $yearMap[mlwf_int_row($row, 'year')] ?? (string)mlwf_int_row($row, 'year'))) ?></td><td class="px-5 py-4"><?= h(mlwf_names(mlwf_text($row, 'apply_month'), $monthMap)) ?></td><td class="px-5 py-4"><?= h(mlwf_names(mlwf_text($row, 'designation'), $designationMap)) ?></td><td class="px-5 py-4"><?= h(mlwf_amount_label(mlwf_text($row, 'amount'))) ?></td><td class="px-5 py-4"><?= h(mlwf_condition_label(mlwf_int_row($row, 'conditn', 2))) ?></td><td class="px-5 py-4 font-bold text-slate-800"><?= h(mlwf_amount_label(mlwf_text($row, 'emp_mlwf'))) ?></td><td class="px-5 py-4 font-bold text-slate-800"><?= h(mlwf_amount_label(mlwf_text($row, 'empr_mlwf'))) ?></td><td class="px-5 py-4"><div class="flex justify-end gap-2"><?php if (mlwf_int_row($row, 'history_count') > 1): ?><a href="?history=<?= mlwf_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=<?= mlwf_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; ?></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, '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(); ?>
