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

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

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

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

function hc_options(mysqli $con, string $sql): array
{
    $rows = [];
    $result = $con->query($sql);
    if ($result) {
        while ($row = $result->fetch_assoc()) $rows[] = $row;
        $result->free();
    }
    return $rows;
}

function hc_columns(mysqli $con, string $table): array
{
    static $cache = [];
    if (isset($cache[$table])) return $cache[$table];
    $safeTable = preg_replace('/[^A-Za-z0-9_]/', '', $table);
    $columns = [];
    $result = $con->query('SHOW COLUMNS FROM `' . $safeTable . '`');
    if ($result) {
        while ($row = $result->fetch_assoc()) $columns[] = (string)$row['Field'];
        $result->free();
    }
    return $cache[$table] = $columns;
}

function hc_has_column(mysqli $con, string $table, string $column): bool
{
    return in_array($column, hc_columns($con, $table), true);
}

function hc_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 = hc_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 hc_exists(mysqli $con, int $id): bool
{
    $stmt = hc_stmt($con, 'SELECT id FROM jos_app_holiday_configration WHERE id=? LIMIT 1');
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $exists = (bool)$stmt->get_result()->fetch_assoc();
    $stmt->close();
    return $exists;
}

function hc_hhmm(string $value, string $label, array &$errors): string
{
    $value = trim($value);
    if ($value === '') {
        $errors[] = $label . ' is required.';
        return '';
    }
    if (!preg_match('/^\d{1,4}:[0-5]\d$/', $value)) {
        $errors[] = $label . ' must be in HH:MM format.';
        return '';
    }
    return $value;
}

function hc_non_negative_int($value, string $label, array &$errors, int $max = 999999): int
{
    $raw = trim((string)$value);
    if ($raw === '') {
        $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 > $max) $errors[] = $label . ' is outside the allowed range.';
    return $number;
}

function hc_csv_values($value, array $allowed): string
{
    $values = is_array($value) ? $value : explode(',', (string)$value);
    $clean = [];
    foreach ($values as $item) {
        $item = trim((string)$item);
        if ($item !== '' && in_array($item, $allowed, true)) $clean[] = $item;
    }
    return implode(',', array_values(array_unique($clean)));
}

function hc_save_row(mysqli $con, int $id, array $data): int
{
    $columns = hc_columns($con, 'jos_app_holiday_configration');
    $spec = [
        'org' => 'i',
        'work_before' => 'i',
        'work_after' => 'i',
        'month' => 'i',
        'year' => 'i',
        'andor' => 'i',
        'holiday_hrs' => 's',
        'reject' => 'i',
        'phw' => 'i',
        'exclude' => 's',
        'phon_presentday' => 'i',
        'deductiontype' => 'i',
        'currentmonth' => '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 holiday configuration fields available.');

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

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

function hc_history_key(mysqli $con): string
{
    if (hc_has_column($con, 'jos_app_holiday_configration_editlog', 'holiday_id')) return 'holiday_id';
    if (hc_has_column($con, 'jos_app_holiday_configration_editlog', 'config_id')) return 'config_id';
    return '';
}

function hc_insert_history(mysqli $con, int $configId): void
{
    $historyColumns = hc_columns($con, 'jos_app_holiday_configration_editlog');
    if (!$historyColumns) return;
    $stmt = hc_stmt($con, 'SELECT * FROM jos_app_holiday_configration 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 === 'holiday_id' || $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 = hc_stmt($con, 'INSERT INTO jos_app_holiday_configration_editlog (`' . implode('`,`', $fields) . '`) VALUES (' . implode(',', $placeholders) . ')');
    if ($types !== '') $stmt->bind_param($types, ...$params);
    if (!$stmt->execute()) throw new RuntimeException('Unable to save holiday configuration history.');
    $stmt->close();
}

function hc_history_rows(mysqli $con, int $configId): array
{
    if (!hc_columns($con, 'jos_app_holiday_configration_editlog')) return [];
    $key = hc_history_key($con);
    if ($key === '') return [];
    $order = hc_has_column($con, 'jos_app_holiday_configration_editlog', 'date') ? '`date` DESC,id DESC' : 'id DESC';
    $rows = [];
    $stmt = hc_stmt($con, 'SELECT * FROM jos_app_holiday_configration_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();
    return $rows;
}

function hc_label(array $labels, $value): string
{
    return $labels[(string)$value] ?? (string)$value;
}

function hc_exclude_labels(string $csv, array $labels): string
{
    $names = [];
    foreach (array_filter(array_map('trim', explode(',', $csv))) as $value) {
        $names[] = $labels[$value] ?? $value;
    }
    return implode(', ', $names);
}

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

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

$payrollLocations = hc_options($con, 'SELECT id,name FROM jos_app_payrolllocation ORDER BY name,id');
$months = hc_options($con, 'SELECT id,month AS name FROM jos_app_mmonth ORDER BY id');
$years = hc_options($con, 'SELECT id,year AS name,assessment FROM jos_app_year ORDER BY id DESC LIMIT 3');
$allYears = hc_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 ($allYears as $row) $yearMap[(int)$row['id']] = (string)$row['name'];

$andOrLabels = [0 => 'AND', 1 => 'OR'];
$currentMonthLabels = [0 => 'Month Before & After', 1 => 'Current Month'];
$deductionLabels = [0 => 'None', 1 => 'Half Day'];
$yesNoLabels = [0 => 'No', 1 => 'Yes'];
$excludeLabels = ['W' => 'Weeklyoff', 'L' => 'Leave', 'UPH' => 'Unpaid Holiday', 'COL' => 'Comp Off Leave'];
$excludeKeys = array_keys($excludeLabels);

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

if (!$isHistory && $mode === 'add' && empty($acl['can_add'])) {
    $_SESSION['flash_holiday_configuration'] = 'You do not have permission to add holiday configurations.';
    redirect('/attendance/holiday-configuration.php');
}

if (!$isHistory && $editId > 0 && empty($acl['can_edit'])) {
    $_SESSION['flash_holiday_configuration'] = 'You do not have permission to edit holiday configurations.';
    redirect('/attendance/holiday-configuration.php');
}

if ($historyId > 0) {
    $stmt = hc_stmt($con, 'SELECT c.*,p.name AS payroll_name,m.month AS month_name,y.year AS year_name FROM jos_app_holiday_configration c LEFT JOIN jos_app_payrolllocation p ON p.id=c.org 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_holiday_configuration'] = 'Holiday Configuration was not found.';
        redirect('/attendance/holiday-configuration.php');
    }
    $historyRows = hc_history_rows($con, $historyId);
}

if (!$isHistory && $editId > 0) {
    $stmt = hc_stmt($con, 'SELECT * FROM jos_app_holiday_configration WHERE id=? LIMIT 1');
    $stmt->bind_param('i', $editId);
    $stmt->execute();
    $editRow = $stmt->get_result()->fetch_assoc() ?: null;
    $stmt->close();
    if (!$editRow) {
        $_SESSION['flash_holiday_configuration'] = 'Holiday Configuration was not found.';
        redirect('/attendance/holiday-configuration.php');
    }
}

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 holiday configurations.';
        if ($id === 0 && empty($acl['can_add'])) $errors[] = 'You do not have permission to add holiday configurations.';
        if ($id > 0 && !hc_exists($con, $id)) $errors[] = 'Holiday Configuration was not found.';

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

        $holidayHrs = hc_hhmm((string)($_POST['holiday_hrs'] ?? ''), 'Holiday Hrs', $errors);
        $workBefore = hc_non_negative_int($_POST['work_before'] ?? '', 'Present Before Holiday', $errors, 31);
        $workAfter = hc_non_negative_int($_POST['work_after'] ?? '', 'Present After Holiday', $errors, 31);
        $andor = (int)($_POST['andor'] ?? 0);
        $currentmonth = (int)($_POST['currentmonth'] ?? 0);
        $deductiontype = (int)($_POST['deductiontype'] ?? 0);
        $reject = (int)($_POST['reject'] ?? 0);
        $phw = (int)($_POST['phw'] ?? 0);
        $phonPresentday = isset($_POST['phon_presentday']) ? 1 : 0;
        $exclude = hc_csv_values($_POST['exclude'] ?? [], $excludeKeys);

        if (!in_array($andor, [0, 1], true)) $errors[] = 'Select a valid AND / OR condition.';
        if (!in_array($currentmonth, [0, 1], true)) $errors[] = 'Select a valid check-present-month option.';
        if (!in_array($deductiontype, [0, 1], true)) $errors[] = 'Select a valid deduction type.';
        if (!in_array($reject, [0, 1], true)) $errors[] = 'Select a valid reject paid holidays option.';
        if (!in_array($phw, [0, 1], true)) $errors[] = 'Select a valid holiday with weekoff option.';
        if ($andor === 1) $currentmonth = 0;

        $data = [
            'org' => $org,
            'work_before' => $workBefore,
            'work_after' => $workAfter,
            'month' => $month,
            'year' => $year,
            'andor' => $andor,
            'holiday_hrs' => $holidayHrs,
            'reject' => $reject,
            'phw' => $phw,
            'exclude' => $exclude,
            'phon_presentday' => $phonPresentday,
            'deductiontype' => $deductiontype,
            'currentmonth' => $currentmonth,
        ];

        if (!$errors) {
            $con->begin_transaction();
            try {
                $savedId = hc_save_row($con, $id, $data);
                hc_insert_history($con, $savedId);
                $con->commit();
                $_SESSION['flash_holiday_configuration'] = $id > 0 ? 'Holiday Configuration updated successfully.' : 'Holiday Configuration added successfully.';
                redirect('/attendance/holiday-configuration.php');
            } catch (Throwable $e) {
                $con->rollback();
                $errors[] = 'Unable to save the holiday configuration. No changes were committed.';
            }
        }

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

$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;
$historyKey = hc_history_key($con);

if (!$isForm && !$isHistory) {
    $where = ['1=1'];
    $types = '';
    $params = [];
    if ($filterOrg > 0) { $where[] = 'c.org=?'; $types .= 'i'; $params[] = $filterOrg; }
    if ($filterMonth > 0) { $where[] = 'c.month=?'; $types .= 'i'; $params[] = $filterMonth; }
    if ($filterYear > 0) { $where[] = 'c.year=?'; $types .= 'i'; $params[] = $filterYear; }
    if ($filterQ !== '') {
        $matchedPayrollIds = [];
        foreach ($payrollMap as $id => $name) {
            if (stripos($name, $filterQ) !== false) $matchedPayrollIds[] = $id;
        }
        $searchParts = ['c.holiday_hrs LIKE ?'];
        $types .= 's';
        $params[] = '%' . $filterQ . '%';
        foreach ($matchedPayrollIds as $id) {
            $searchParts[] = 'c.org=?';
            $types .= 'i';
            $params[] = (int)$id;
        }
        $where[] = '(' . implode(' OR ', $searchParts) . ')';
    }
    $whereSql = implode(' AND ', $where);

    $stmt = hc_stmt($con, 'SELECT COUNT(*) AS total FROM jos_app_holiday_configration 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;

    $historySelect = $historyKey !== '' ? ',(SELECT COUNT(*) FROM jos_app_holiday_configration_editlog e WHERE e.`' . $historyKey . '`=c.id) AS history_count' : ',0 AS history_count';
    $stmt = hc_stmt($con, 'SELECT c.*,p.name AS payroll_name,m.month AS month_name,y.year AS year_name' . $historySelect . ' FROM jos_app_holiday_configration c LEFT JOIN jos_app_payrolllocation p ON p.id=c.org 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; };
$selectedExclude = array_filter(array_map('trim', explode(',', (string)$value('exclude'))));
$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';

console_header('Holiday 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">Holiday Configuration</span></div><h1 class="text-2xl font-bold text-slate-900">Holiday Configuration</h1><p class="mt-1 text-sm text-slate-500">Configure paid holiday eligibility, before/after presence rules, exclusions, and weekly-off behavior.</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">Holiday Configuration History</h2><p class="mt-1 text-xs font-medium text-slate-400"><?= h($historyParent['payroll_name'] ?? '') ?> · <?= h($historyParent['month_name'] ?: ($monthMap[(int)($historyParent['month'] ?? 0)] ?? '')) ?> <?= h($historyParent['year_name'] ?: ($yearMap[(int)($historyParent['year'] ?? 0)] ?? '')) ?></p></div><a href="/attendance/holiday-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-[1200px] 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">Payroll Location</th><th class="px-5 py-4">Month</th><th class="px-5 py-4">Holiday Hrs</th><th class="px-5 py-4">Before / After</th><th class="px-5 py-4">Condition</th><th class="px-5 py-4">Deduction</th><th class="px-5 py-4">Exclusions</th><th class="px-5 py-4">Flags</th></tr></thead><tbody class="divide-y divide-slate-100">
    <?php if(!$historyRows): ?><tr><td colspan="9" 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(hc_text($row, 'date')) ?></td><td class="px-5 py-4 font-bold text-slate-800"><?= h($payrollMap[hc_int($row, 'org')] ?? hc_text($row, 'org')) ?></td><td class="px-5 py-4"><?= h($monthMap[hc_int($row, 'month')] ?? hc_text($row, 'month')) ?> <?= h($yearMap[hc_int($row, 'year')] ?? hc_text($row, 'year')) ?></td><td class="px-5 py-4"><?= h(hc_text($row, 'holiday_hrs')) ?></td><td class="px-5 py-4"><?= h(hc_text($row, 'work_before')) ?> / <?= h(hc_text($row, 'work_after')) ?></td><td class="px-5 py-4"><?= h(hc_label($andOrLabels, hc_int($row, 'andor'))) ?><br><span class="text-xs text-slate-400"><?= hc_int($row, 'andor') === 0 ? h(hc_label($currentMonthLabels, hc_int($row, 'currentmonth'))) : '' ?></span></td><td class="px-5 py-4"><?= h(hc_label($deductionLabels, hc_int($row, 'deductiontype'))) ?></td><td class="px-5 py-4"><?= h(hc_exclude_labels(hc_text($row, 'exclude'), $excludeLabels)) ?></td><td class="px-5 py-4">Reject <?= h(hc_label($yesNoLabels, hc_int($row, 'reject'))) ?><br>PH+WOff <?= h(hc_label($yesNoLabels, hc_int($row, 'phw'))) ?><br>Present PH <?= h(hc_label($yesNoLabels, hc_int($row, 'phon_presentday'))) ?></td></tr><?php endforeach; ?>
  </tbody></table></div>
</section>
<?php elseif ($isForm): ?>
<form method="post" id="holiday-configuration-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-regular fa-calendar-check"></i></span><div><h2 class="font-bold text-slate-800"><?= (int)$value('id',0)>0?'Edit Holiday Configuration':'New Holiday Configuration' ?></h2><p class="text-xs text-slate-400">Fields marked with * are required.</p></div></div><a href="/attendance/holiday-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 md:col-span-2">Payroll Location *<select name="org" required class="<?= $input ?>"><option value="">Select Payroll Location</option><?php foreach($payrollLocations as $option): ?><option value="<?= (int)$option['id'] ?>" <?= (int)$value('org')===(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">Holiday Hrs (HH:MM) *<input name="holiday_hrs" required value="<?= h((string)$value('holiday_hrs')) ?>" class="<?= $input ?>" placeholder="08:00"></label>
      <label class="text-sm font-semibold text-slate-700">Present Before Holiday *<input name="work_before" inputmode="numeric" required value="<?= h((string)$value('work_before')) ?>" class="<?= $input ?>" placeholder="Days"></label>
      <label class="text-sm font-semibold text-slate-700">AND / OR<select name="andor" class="<?= $input ?> js-andor"><?php foreach($andOrLabels as $k=>$label): ?><option value="<?= $k ?>" <?= (int)$value('andor',0)===$k?'selected':'' ?>><?= h($label) ?></option><?php endforeach; ?></select></label>
      <label class="text-sm font-semibold text-slate-700">Present After Holiday *<input name="work_after" inputmode="numeric" required value="<?= h((string)$value('work_after')) ?>" class="<?= $input ?>" placeholder="Days"></label>
      <label class="text-sm font-semibold text-slate-700 js-current-month">Check Present Month<select name="currentmonth" class="<?= $input ?>"><?php foreach($currentMonthLabels as $k=>$label): ?><option value="<?= $k ?>" <?= (int)$value('currentmonth',0)===$k?'selected':'' ?>><?= h($label) ?></option><?php endforeach; ?></select></label>
      <label class="text-sm font-semibold text-slate-700">Deduction Type<select name="deductiontype" class="<?= $input ?>"><?php foreach($deductionLabels as $k=>$label): ?><option value="<?= $k ?>" <?= (int)$value('deductiontype',0)===$k?'selected':'' ?>><?= h($label) ?></option><?php endforeach; ?></select><span class="mt-1 block text-xs font-medium text-red-500">Half day applies when condition is false.</span></label>
      <label class="text-sm font-semibold text-slate-700">Reject Paid Holidays<select name="reject" class="<?= $input ?>"><?php foreach($yesNoLabels as $k=>$label): ?><option value="<?= $k ?>" <?= (int)$value('reject',0)===$k?'selected':'' ?>><?= h($label) ?></option><?php endforeach; ?></select><span class="mt-1 block text-xs font-medium text-red-500">Reject paid holidays if inactive.</span></label>
      <label class="text-sm font-semibold text-slate-700">Holiday With Weekoff<select name="phw" class="<?= $input ?>"><?php foreach($yesNoLabels as $k=>$label): ?><option value="<?= $k ?>" <?= (int)$value('phw',0)===$k?'selected':'' ?>><?= h($label) ?></option><?php endforeach; ?></select></label>
      <div class="text-sm font-semibold text-slate-700 md:col-span-2"><span>Day Exclude</span><div class="mt-2 grid gap-2 sm:grid-cols-2"><?php foreach($excludeLabels as $key=>$label): ?><label class="inline-flex items-center gap-2 rounded-lg border border-slate-200 px-3 py-2"><input type="checkbox" name="exclude[]" value="<?= h($key) ?>" <?= in_array($key, $selectedExclude, true)?'checked':'' ?>> <?= h($label) ?></label><?php endforeach; ?></div></div>
      <label class="mt-7 inline-flex items-start gap-2 rounded-xl border border-amber-100 bg-amber-50 px-4 py-3 text-sm font-semibold text-amber-800 md:col-span-2"><input class="mt-1" type="checkbox" name="phon_presentday" value="1" <?= (int)$value('phon_presentday',0)===1?'checked':'' ?>> <span>Apply PH if present On Holiday <span class="block text-xs font-medium text-amber-700">PH is applied when the employee is present on holiday; other conditions are skipped.</span></span></label>
    </div>
  </section>
  <div class="flex flex-wrap justify-end gap-2"><a href="/attendance/holiday-configuration.php" class="rounded-lg border border-slate-200 bg-white px-5 py-2.5 text-sm font-bold text-slate-600">Cancel</a><button class="rounded-lg bg-brand-600 px-5 py-2.5 text-sm font-bold text-white hover:bg-brand-700"><i class="fa-solid fa-floppy-disk mr-2"></i>Save Configuration</button></div>
</form>
<script>
(()=>{const andor=document.querySelector('.js-andor'),current=document.querySelector('.js-current-month');const sync=()=>{if(current&&andor)current.style.display=andor.value==='0'?'':'none';};if(andor)andor.addEventListener('change',sync);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">Holiday Configuration List</h2><p class="mt-1 text-xs font-medium text-slate-400">Policies are ordered by latest month and year.</p></div><?php if(!empty($acl['can_add'])): ?><a href="?mode=add" class="inline-flex items-center justify-center gap-2 rounded-lg bg-brand-600 px-4 py-2.5 text-sm font-bold text-white shadow-sm hover:bg-brand-700"><i class="fa-solid fa-plus"></i>+ Add</a><?php endif; ?></div>
  <form method="get" class="grid gap-3 border-b border-slate-100 p-5 md:grid-cols-2 xl:grid-cols-6"><input name="q" value="<?= h($filterQ) ?>" class="<?= $selectSmall ?>" placeholder="Search location or hours"><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($allYears 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/holiday-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-[1500px] 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">Payroll Location</th><th class="px-5 py-4">Month</th><th class="px-5 py-4">Holiday Hrs</th><th class="px-5 py-4">Present Before</th><th class="px-5 py-4">AND / OR</th><th class="px-5 py-4">Present After</th><th class="px-5 py-4">Deduction</th><th class="px-5 py-4">Check in Month</th><th class="px-5 py-4">Day Exclude</th><th class="px-5 py-4">Reject if Inactive</th><th class="px-5 py-4">Holiday with Weekoff</th><th class="px-5 py-4">Apply PH if Present</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="14" class="px-6 py-14 text-center font-semibold text-slate-400">No holiday 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(hc_text($row, 'payroll_name') !== '' ? hc_text($row, 'payroll_name') : ($payrollMap[hc_int($row, 'org')] ?? '')) ?><?php if(hc_int($row, 'history_count')>0): ?><div class="mt-1 text-xs font-semibold text-slate-400">History <?= hc_int($row, 'history_count') ?></div><?php endif; ?></td><td class="px-5 py-4 font-semibold"><?= h(hc_text($row, 'month_name') !== '' ? hc_text($row, 'month_name') : ($monthMap[hc_int($row, 'month')] ?? '')) ?><br><?= h(hc_text($row, 'year_name') !== '' ? hc_text($row, 'year_name') : ($yearMap[hc_int($row, 'year')] ?? '')) ?></td><td class="px-5 py-4"><?= h(hc_text($row, 'holiday_hrs')) ?></td><td class="px-5 py-4"><?= h(hc_text($row, 'work_before')) ?></td><td class="px-5 py-4"><?= h(hc_label($andOrLabels, hc_int($row, 'andor'))) ?></td><td class="px-5 py-4"><?= h(hc_text($row, 'work_after')) ?></td><td class="px-5 py-4"><?= h(hc_label($deductionLabels, hc_int($row, 'deductiontype'))) ?></td><td class="px-5 py-4"><?= hc_int($row, 'andor') === 0 ? h(hc_label($currentMonthLabels, hc_int($row, 'currentmonth'))) : '' ?></td><td class="px-5 py-4"><?= h(hc_exclude_labels(hc_text($row, 'exclude'), $excludeLabels)) ?></td><td class="px-5 py-4"><?= h(hc_label($yesNoLabels, hc_int($row, 'reject'))) ?></td><td class="px-5 py-4"><?= h(hc_label($yesNoLabels, hc_int($row, 'phw'))) ?></td><td class="px-5 py-4"><?= h(hc_label($yesNoLabels, hc_int($row, 'phon_presentday'))) ?></td><td class="px-5 py-4"><div class="flex justify-end gap-2"><?php if(hc_int($row, 'history_count')>1): ?><a href="?history=<?= hc_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-eye"></i></a><?php endif; ?><?php if(!empty($acl['can_edit'])): ?><a href="?edit=<?= hc_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 ?> configurations</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(); ?>
