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

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

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

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

function woc_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 woc_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 woc_has_column(mysqli $con, string $table, string $column): bool
{
    return in_array($column, woc_columns($con, $table), true);
}

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

function woc_valid_id(mysqli $con, string $table, int $id): bool
{
    $allowed = ['jos_app_mmonth', 'jos_app_year', 'jos_app_weekofftype', 'jos_app_mdays'];
    if ($id <= 0 || !in_array($table, $allowed, true)) return false;
    $stmt = woc_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 woc_valid_ids(mysqli $con, string $table, array $ids): bool
{
    foreach ($ids as $id) if (!woc_valid_id($con, $table, (int)$id)) return false;
    return true;
}

function woc_int($value, string $label, array &$errors, int $min = 0, int $max = 9999): int
{
    $raw = trim((string)$value);
    if ($raw === '') 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 woc_policy_exists(mysqli $con, int $id): bool
{
    $stmt = woc_stmt($con, 'SELECT id FROM jos_app_weekoff WHERE id=? LIMIT 1');
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $exists = (bool)$stmt->get_result()->fetch_assoc();
    $stmt->close();
    return $exists;
}

function woc_csv_labels(string $csv, array $map): string
{
    $ids = woc_ids(explode(',', $csv));
    $labels = [];
    foreach ($ids as $id) $labels[] = $map[$id] ?? ('#' . $id);
    return implode(', ', $labels);
}

function woc_exclude_labels(string $csv): string
{
    $map = ['W' => 'Weeklyoff', 'L' => 'Leave', 'PH' => 'Holiday'];
    $codes = array_values(array_filter(array_map('trim', explode(',', $csv))));
    $labels = [];
    foreach ($codes as $code) if (isset($map[$code])) $labels[] = $map[$code];
    return implode(', ', $labels);
}

function woc_save_history(mysqli $con, int $id): void
{
    $columns = woc_columns($con, 'jos_app_weekoff_editlog');
    if (!$columns) return;
    $sourceColumns = woc_columns($con, 'jos_app_weekoff');
    $copy = [];
    foreach ($columns as $column) {
        if ($column === 'id') continue;
        if ($column === 'weekid') {
            $copy[$column] = ['expr' => 'id'];
        } elseif ($column === 'sysdate') {
            $copy[$column] = ['expr' => 'NOW()'];
        } elseif ($column === 'modify_by') {
            $copy[$column] = ['value' => (int)(current_user()['id'] ?? 0), 'type' => 'i'];
        } elseif (in_array($column, $sourceColumns, true)) {
            $copy[$column] = ['expr' => '`' . $column . '`'];
        }
    }
    if (!$copy) return;
    $target = '`' . implode('`,`', array_keys($copy)) . '`';
    $select = [];
    $types = '';
    $params = [];
    foreach ($copy as $meta) {
        if (isset($meta['expr'])) {
            $select[] = $meta['expr'];
        } else {
            $select[] = '?';
            $types .= $meta['type'];
            $params[] = $meta['value'];
        }
    }
    $stmt = woc_stmt($con, 'INSERT INTO jos_app_weekoff_editlog (' . $target . ') SELECT ' . implode(',', $select) . ' FROM jos_app_weekoff WHERE id=?');
    $types .= 'i';
    $params[] = $id;
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $stmt->close();
}

$months = woc_options($con, 'SELECT id,month AS name FROM jos_app_mmonth ORDER BY id');
$years = woc_options($con, 'SELECT id,year AS name,assessment FROM jos_app_year ORDER BY id DESC');
$weekTypes = woc_options($con, 'SELECT id,weektype AS name FROM jos_app_weekofftype ORDER BY id');
$days = woc_options($con, 'SELECT id,day AS name FROM jos_app_mdays ORDER BY id');
$monthMap = $yearMap = $weekTypeMap = $dayMap = [];
foreach ($months as $row) $monthMap[(int)$row['id']] = (string)$row['name'];
foreach ($years as $row) $yearMap[(int)$row['id']] = (string)$row['name'];
foreach ($weekTypes as $row) $weekTypeMap[(int)$row['id']] = (string)$row['name'];
foreach ($days as $row) $dayMap[(int)$row['id']] = (string)$row['name'];

$mode = (string)($_GET['mode'] ?? '');
$editId = max(0, (int)($_GET['edit'] ?? 0));
$isForm = $mode === 'add' || $editId > 0;
$editRow = null;
$selectedWeeklyOff = [];
$selectedExclude = [];

if ($editId > 0) {
    $stmt = woc_stmt($con, 'SELECT * FROM jos_app_weekoff WHERE id=? LIMIT 1');
    $stmt->bind_param('i', $editId);
    $stmt->execute();
    $editRow = $stmt->get_result()->fetch_assoc() ?: null;
    $stmt->close();
    if (!$editRow) {
        $_SESSION['flash_weekly_off_configuration'] = 'Weekly Off Configuration was not found.';
        redirect('/attendance/weekly-off-configuration.php');
    }
    $selectedWeeklyOff = woc_ids(explode(',', (string)($editRow['weeklyoff'] ?? '')));
    $selectedExclude = array_values(array_filter(array_map('trim', explode(',', (string)($editRow['exclude'] ?? '')))));
}

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

        $name = trim((string)($_POST['name'] ?? ''));
        $month = max(0, (int)($_POST['month'] ?? 0));
        $year = max(0, (int)($_POST['year'] ?? 0));
        $currentMonth = (int)($_POST['currentmonth'] ?? 0);
        $weekoffType = max(0, (int)($_POST['weekoff_type'] ?? 0));
        $weeklyoffIds = woc_ids($_POST['weeklyoff'] ?? []);
        $alternate = max(0, (int)($_POST['alternate'] ?? 0));
        $alternateNo = woc_int($_POST['alternate_no'] ?? '', 'Alternate day number', $errors, 0, 31);
        $weekoffDates = trim((string)($_POST['Weekoffdates'] ?? ''));
        $customeWeekoff = woc_int($_POST['customeweekoff'] ?? '', 'No. of weekoff', $errors, 0, 31);
        $workinWeek = woc_int($_POST['workin_week'] ?? '', 'Minimum present in week', $errors, 0, 31);
        $policyAndOr = (int)($_POST['policyandor'] ?? 0);
        $workBefore = woc_int($_POST['work_before'] ?? '', 'Present before weekoff', $errors, 0, 31);
        $workBeforeHrs = woc_int($_POST['work_beforehrs'] ?? '', 'Present before hours', $errors, 0, 1440);
        $andOr = (int)($_POST['andor'] ?? 0);
        $workAfter = woc_int($_POST['work_after'] ?? '', 'Present after weekoff', $errors, 0, 31);
        $workAfterHrs = woc_int($_POST['work_afterhrs'] ?? '', 'Present after hours', $errors, 0, 1440);
        $wfreeShiftHrs = woc_int($_POST['wfree_shifthrs'] ?? '', 'Weeklyoff free days shift hours', $errors, 0, 1440);
        $woffOnPresentDay = isset($_POST['woffon_presentday']) ? 1 : 0;
        $exclude = array_values(array_intersect((array)($_POST['exclude'] ?? []), ['W', 'L', 'PH']));

        if ($name === '') $errors[] = 'Policy name is required.';
        if (mb_strlen($name) > 150) $errors[] = 'Policy name must be 150 characters or fewer.';
        if (!woc_valid_id($con, 'jos_app_mmonth', $month)) $errors[] = 'Select a valid month.';
        if (!woc_valid_id($con, 'jos_app_year', $year)) $errors[] = 'Select a valid year.';
        if (!woc_valid_id($con, 'jos_app_weekofftype', $weekoffType)) $errors[] = 'Select a valid week off type.';
        if (!in_array($currentMonth, [0, 1], true)) $errors[] = 'Select a valid month-check rule.';
        if (!in_array($policyAndOr, [0, 1], true)) $errors[] = 'Select a valid condition join.';
        if (!in_array($andOr, [0, 1], true)) $errors[] = 'Select a valid before/after join.';
        if (!woc_valid_ids($con, 'jos_app_mdays', $weeklyoffIds)) $errors[] = 'Select valid weekly off days.';
        if ($alternate > 0 && !woc_valid_id($con, 'jos_app_mdays', $alternate)) $errors[] = 'Select a valid alternate day.';
        if (($weekoffType === 1 || $weekoffType === 4) && !$weeklyoffIds) $errors[] = 'Select at least one week off day for this week off type.';
        if ($weekoffType === 3 && $customeWeekoff <= 0) $errors[] = 'Enter number of weekoff days for custom weekoff.';

        $weeklyoff = implode(',', $weeklyoffIds);
        $excludeCsv = implode(',', $exclude);
        $userId = (int)(current_user()['id'] ?? 0);
        $now = date('Y-m-d H:i:s');

        if (!$errors) {
            $con->begin_transaction();
            try {
                if ($id > 0) {
                    $stmt = woc_stmt($con, 'UPDATE jos_app_weekoff SET userid=?,sysdate=?,name=?,weekoff_type=?,weekoffdates=?,customeweekoff=?,workin_week=?,work_before=?,work_after=?,andor=?,modifed_by=?,month=?,year=?,currentmonth=?,exclude=?,weeklyoff=?,alternate=?,alternate_no=?,work_beforehrs=?,work_afterhrs=?,wfree_shifthrs=?,woffon_presentday=?,policyandor=? WHERE id=?');
                    $stmt->bind_param('issisiiiiiiiiissiiiiiiii', $userId, $now, $name, $weekoffType, $weekoffDates, $customeWeekoff, $workinWeek, $workBefore, $workAfter, $andOr, $userId, $month, $year, $currentMonth, $excludeCsv, $weeklyoff, $alternate, $alternateNo, $workBeforeHrs, $workAfterHrs, $wfreeShiftHrs, $woffOnPresentDay, $policyAndOr, $id);
                    if (!$stmt->execute()) throw new RuntimeException('Unable to update weekly off configuration.');
                    $stmt->close();
                    $savedId = $id;
                } else {
                    $empid = 0;
                    $stmt = woc_stmt($con, 'INSERT INTO jos_app_weekoff (userid,empid,sysdate,name,weekoff_type,weekoffdates,customeweekoff,workin_week,work_before,work_after,andor,modifed_by,month,year,currentmonth,exclude,weeklyoff,alternate,alternate_no,work_beforehrs,work_afterhrs,wfree_shifthrs,woffon_presentday,policyandor) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)');
                    $stmt->bind_param('iissisiiiiiiiiissiiiiiii', $userId, $empid, $now, $name, $weekoffType, $weekoffDates, $customeWeekoff, $workinWeek, $workBefore, $workAfter, $andOr, $userId, $month, $year, $currentMonth, $excludeCsv, $weeklyoff, $alternate, $alternateNo, $workBeforeHrs, $workAfterHrs, $wfreeShiftHrs, $woffOnPresentDay, $policyAndOr);
                    if (!$stmt->execute()) throw new RuntimeException('Unable to add weekly off configuration.');
                    $savedId = (int)$con->insert_id;
                    $stmt->close();
                }
                woc_save_history($con, $savedId);
                $con->commit();
                audit_log($id > 0 ? 'weekly_off_configuration.update' : 'weekly_off_configuration.create', 'jos_app_weekoff', (string)$savedId, $name);
                $_SESSION['flash_weekly_off_configuration'] = $id > 0 ? 'Weekly Off Configuration updated successfully.' : 'Weekly Off Configuration added successfully.';
                redirect('/attendance/weekly-off-configuration.php');
            } catch (Throwable $e) {
                $con->rollback();
                $errors[] = 'Unable to save the weekly off configuration. No changes were committed.';
            }
        }

        $isForm = true;
        $editId = $id;
        $editRow = [
            'id' => $id, 'name' => $name, 'month' => $month, 'year' => $year,
            'currentmonth' => $currentMonth, 'weekoff_type' => $weekoffType,
            'alternate' => $alternate, 'alternate_no' => $alternateNo, 'weekoffdates' => $weekoffDates,
            'customeweekoff' => $customeWeekoff, 'workin_week' => $workinWeek, 'policyandor' => $policyAndOr,
            'work_before' => $workBefore, 'work_beforehrs' => $workBeforeHrs, 'andor' => $andOr,
            'work_after' => $workAfter, 'work_afterhrs' => $workAfterHrs, 'wfree_shifthrs' => $wfreeShiftHrs,
            'woffon_presentday' => $woffOnPresentDay, 'exclude' => $excludeCsv, 'weeklyoff' => $weeklyoff
        ];
        $selectedWeeklyOff = $weeklyoffIds;
        $selectedExclude = $exclude;
    }
}

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

if (!$isForm) {
    $where = ['1=1'];
    $types = '';
    $params = [];
    if ($filterMonth > 0) { $where[] = 'w.month=?'; $types .= 'i'; $params[] = $filterMonth; }
    if ($filterYear > 0) { $where[] = 'w.year=?'; $types .= 'i'; $params[] = $filterYear; }
    if ($filterType > 0) { $where[] = 'w.weekoff_type=?'; $types .= 'i'; $params[] = $filterType; }
    if ($search !== '') { $where[] = 'w.name LIKE ?'; $types .= 's'; $params[] = '%' . $search . '%'; }
    $whereSql = implode(' AND ', $where);

    $stmt = woc_stmt($con, 'SELECT COUNT(*) AS total FROM jos_app_weekoff w 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 = woc_stmt($con, 'SELECT w.*,m.month AS month_name,y.year AS year_name,t.weektype AS week_type_name,(SELECT COUNT(*) FROM jos_app_weekoff_editlog e WHERE e.weekid=w.id) AS history_count FROM jos_app_weekoff w LEFT JOIN jos_app_mmonth m ON m.id=w.month LEFT JOIN jos_app_year y ON y.id=w.year LEFT JOIN jos_app_weekofftype t ON t.id=w.weekoff_type WHERE ' . $whereSql . ' ORDER BY w.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';

console_header('Weekly Off 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">Weekly Off Configuration</span></div><h1 class="text-2xl font-bold text-slate-900">Weekly Off Configuration</h1><p class="mt-1 text-sm text-slate-500">Configure monthly weekly-off policy rules and attendance conditions.</p></div>
</div>
<?php if ($flash): ?><div class="mb-5 rounded-xl border border-emerald-100 bg-emerald-50 px-5 py-4 text-sm font-semibold text-emerald-700"><i class="fa-solid fa-circle-check mr-2"></i><?= h($flash) ?></div><?php endif; ?>
<?php if ($errors): ?><div class="mb-5 rounded-xl border border-red-100 bg-red-50 px-5 py-4 text-sm font-semibold text-red-700"><div class="font-bold">Please fix the following</div><ul class="mt-2 list-inside list-disc"><?php foreach($errors as $error): ?><li><?= h($error) ?></li><?php endforeach; ?></ul></div><?php endif; ?>

<?php if ($isForm): ?>
<form method="post" id="weekly-off-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-calendar-week"></i></span><div><h2 class="font-bold text-slate-800"><?= (int)$value('id',0)>0?'Edit Weekly Off Configuration':'New Weekly Off Configuration' ?></h2><p class="text-xs text-slate-400">Fields marked with * are required.</p></div></div><a href="/attendance/weekly-off-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-3 xl:grid-cols-6">
      <label class="text-sm font-semibold text-slate-700 xl:col-span-2">Policy Name *<input name="name" required maxlength="150" value="<?= h((string)$value('name')) ?>" class="<?= $input ?>" placeholder="Policy Name"></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">Check Present Month<select name="currentmonth" class="<?= $input ?>"><option value="0" <?= (int)$value('currentmonth',0)===0?'selected':'' ?>>Month Before & After</option><option value="1" <?= (int)$value('currentmonth',0)===1?'selected':'' ?>>Current Month</option></select></label>
      <label class="text-sm font-semibold text-slate-700">Free Days Shift Hrs (MM)<input name="wfree_shifthrs" inputmode="numeric" pattern="\d*" value="<?= h((string)$value('wfree_shifthrs')) ?>" class="<?= $input ?>" placeholder="MM"></label>
    </div>
    <div class="mt-4 grid gap-3 md:grid-cols-3">
      <label class="text-sm font-semibold text-slate-700">Day Exclude<select name="exclude[]" multiple class="<?= $input ?> min-h-[7rem]"><option value="W" <?= in_array('W',$selectedExclude,true)?'selected':'' ?>>Weeklyoff</option><option value="L" <?= in_array('L',$selectedExclude,true)?'selected':'' ?>>Leave</option><option value="PH" <?= in_array('PH',$selectedExclude,true)?'selected':'' ?>>Holiday</option></select></label>
    </div>
  </section>

  <section class="rounded-2xl border border-slate-100 bg-white p-4 shadow-sm">
    <div class="mb-3 flex items-center gap-3"><span class="flex h-9 w-9 items-center justify-center rounded-lg bg-blue-50 text-blue-600"><i class="fa-solid fa-list-check"></i></span><div><h2 class="font-bold text-slate-800">Policy Condition 1</h2><p class="text-xs text-slate-400">Select the weekly-off type and related day/date rule.</p></div></div>
    <div class="grid gap-3 md:grid-cols-3 xl:grid-cols-6">
      <label class="text-sm font-semibold text-slate-700">Week Off Type *<select name="weekoff_type" id="weekoff-type" required class="<?= $input ?>"><option value="0">Select</option><?php foreach($weekTypes as $type): ?><option value="<?= (int)$type['id'] ?>" <?= (int)$value('weekoff_type')===(int)$type['id']?'selected':'' ?>><?= h($type['name']) ?></option><?php endforeach; ?></select></label>
      <label class="weekoff-panel weekoff-days text-sm font-semibold text-slate-700 xl:col-span-2">Week Off Day<select name="weeklyoff[]" multiple class="<?= $input ?> min-h-[7rem]"><?php foreach($days as $day): ?><option value="<?= (int)$day['id'] ?>" <?= in_array((int)$day['id'],$selectedWeeklyOff,true)?'selected':'' ?>><?= h($day['name']) ?></option><?php endforeach; ?></select></label>
      <label class="weekoff-panel weekoff-alt text-sm font-semibold text-slate-700">Alternate Of Day<select name="alternate" class="<?= $input ?>"><option value="0">No Weekoff</option><?php foreach($days as $day): ?><option value="<?= (int)$day['id'] ?>" <?= (int)$value('alternate')===(int)$day['id']?'selected':'' ?>><?= h($day['name']) ?></option><?php endforeach; ?></select></label>
      <label class="weekoff-panel weekoff-alt text-sm font-semibold text-slate-700">Alternate No<input name="alternate_no" inputmode="numeric" pattern="\d*" value="<?= h((string)$value('alternate_no')) ?>" class="<?= $input ?>" placeholder="1,2,3,4"></label>
      <label class="weekoff-panel weekoff-date text-sm font-semibold text-slate-700 xl:col-span-2">Assigned Dates<input name="Weekoffdates" value="<?= h((string)$value('weekoffdates')) ?>" class="<?= $input ?>" placeholder="Assigned from monthly schedule"></label>
      <label class="weekoff-panel weekoff-custom text-sm font-semibold text-slate-700">No. Of Weekoff<input name="customeweekoff" inputmode="numeric" pattern="\d*" value="<?= h((string)$value('customeweekoff')) ?>" class="<?= $input ?>"></label>
      <label class="text-sm font-semibold text-slate-700">Min Present In Week<input name="workin_week" inputmode="numeric" pattern="\d*" value="<?= h((string)$value('workin_week')) ?>" class="<?= $input ?>"></label>
    </div>
  </section>

  <section class="rounded-2xl border border-slate-100 bg-white p-4 shadow-sm">
    <div class="mb-3 grid gap-3 md:grid-cols-3"><div class="text-sm font-bold text-red-500">Policy Condition 1</div><label class="text-sm font-semibold text-slate-700">Condition Join<select name="policyandor" class="<?= $input ?>"><option value="0" <?= (int)$value('policyandor',0)===0?'selected':'' ?>>OR</option><option value="1" <?= (int)$value('policyandor',0)===1?'selected':'' ?>>AND</option></select></label><div class="text-sm font-bold text-red-500">Policy Condition 2</div></div>
    <div class="mb-3 flex items-center gap-3"><span class="flex h-9 w-9 items-center justify-center rounded-lg bg-violet-50 text-violet-600"><i class="fa-solid fa-code-branch"></i></span><div><h2 class="font-bold text-slate-800">Policy Condition 2</h2><p class="text-xs text-slate-400">Configure required attendance before and after weekly-off days.</p></div></div>
    <div class="grid gap-3 md:grid-cols-3 xl:grid-cols-6">
      <label class="text-sm font-semibold text-slate-700">Present Before<input name="work_before" inputmode="numeric" pattern="\d*" value="<?= h((string)$value('work_before')) ?>" class="<?= $input ?>"></label>
      <label class="text-sm font-semibold text-slate-700">Before Hrs (MM)<input name="work_beforehrs" inputmode="numeric" pattern="\d*" value="<?= h((string)$value('work_beforehrs')) ?>" class="<?= $input ?>"></label>
      <label class="text-sm font-semibold text-slate-700">AND / OR<select name="andor" class="<?= $input ?>"><option value="0" <?= (int)$value('andor',0)===0?'selected':'' ?>>AND</option><option value="1" <?= (int)$value('andor',0)===1?'selected':'' ?>>OR</option></select></label>
      <label class="text-sm font-semibold text-slate-700">Present After<input name="work_after" inputmode="numeric" pattern="\d*" value="<?= h((string)$value('work_after')) ?>" class="<?= $input ?>"></label>
      <label class="text-sm font-semibold text-slate-700">After Hrs (MM)<input name="work_afterhrs" inputmode="numeric" pattern="\d*" value="<?= h((string)$value('work_afterhrs')) ?>" class="<?= $input ?>"></label>
      <label class="flex items-center gap-3 pt-7 text-sm font-semibold text-slate-700"><input type="checkbox" name="woffon_presentday" value="1" <?= (int)$value('woffon_presentday')===1?'checked':'' ?> class="rounded border-slate-300 text-brand-600">Apply if present on week off day</label>
    </div>
  </section>

  <div class="flex flex-wrap justify-end gap-2"><a href="/attendance/weekly-off-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>
<script>
(()=>{const type=document.getElementById('weekoff-type');const panels=document.querySelectorAll('.weekoff-panel');const days=document.querySelectorAll('.weekoff-days');const alt=document.querySelectorAll('.weekoff-alt');const date=document.querySelectorAll('.weekoff-date');const custom=document.querySelectorAll('.weekoff-custom');const show=(items,on)=>items.forEach(el=>el.style.display=on?'block':'none');const update=()=>{const value=type.value;panels.forEach(el=>el.style.display='none');show(days,value==='1'||value==='4');show(alt,value==='1');show(date,value==='2');show(custom,value==='3');};type.addEventListener('change',update);update();})();
</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">Weekly Off Configuration List</h2><p class="mt-1 text-xs font-medium text-slate-400">Policies are ordered by latest saved record.</p></div><?php if(!empty($acl['can_add'])): ?><a href="?mode=add" class="inline-flex items-center justify-center gap-2 rounded-lg bg-brand-600 px-4 py-2.5 text-sm font-bold text-white shadow-sm hover:bg-brand-700"><i class="fa-solid fa-plus"></i>+ Add</a><?php endif; ?></div>
  <form method="get" class="grid gap-3 border-b border-slate-100 p-5 md:grid-cols-2 xl:grid-cols-6"><input type="search" name="q" value="<?= h($search) ?>" placeholder="Search policy name" class="<?= $selectSmall ?>"><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><select name="weekoff_type" class="<?= $selectSmall ?>"><option value="0">All Types</option><?php foreach($weekTypes as $type): ?><option value="<?= (int)$type['id'] ?>" <?= $filterType===(int)$type['id']?'selected':'' ?>><?= h($type['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/weekly-off-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] 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</th><th class="px-5 py-4">Month</th><th class="px-5 py-4">Type</th><th class="px-5 py-4">Days / Custom / Dates</th><th class="px-5 py-4">Alternate</th><th class="px-5 py-4">Min Present</th><th class="px-5 py-4">Before / Hrs</th><th class="px-5 py-4">AND / OR</th><th class="px-5 py-4">After / Hrs</th><th class="px-5 py-4">Present On WOFF</th><th class="px-5 py-4">Exclude</th><th class="px-5 py-4">Free Shift Hrs</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 weekly off 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"><div class="font-bold text-slate-800"><?= h($row['name']) ?></div><div class="text-xs text-slate-400">Condition 1 <span class="font-bold text-red-500"><?= (int)$row['policyandor']===0?'OR':'AND' ?></span> 2</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"><div class="font-semibold"><?= h($row['month_name'] ?: ($monthMap[(int)$row['month']] ?? 'Unknown')) ?></div><div class="text-xs text-slate-400"><?= h($row['year_name'] ?: ($yearMap[(int)$row['year']] ?? (string)$row['year'])) ?></div><div class="text-xs text-slate-400"><?= (int)$row['currentmonth']===0?'Month Before & After':'Current Month' ?></div></td><td class="px-5 py-4 font-semibold text-slate-700"><?= h($row['week_type_name'] ?: ($weekTypeMap[(int)$row['weekoff_type']] ?? 'Unknown')) ?></td><td class="px-5 py-4"><?php if(in_array((int)$row['weekoff_type'], [1,4], true)): ?><div class="font-semibold"><?= h(woc_csv_labels((string)$row['weeklyoff'], $dayMap)) ?></div><?php elseif((int)$row['weekoff_type']===2): ?><div class="font-semibold">Monthly schedule dates</div><?php elseif((int)$row['weekoff_type']===3): ?><div class="font-semibold"><?= h((string)$row['customeweekoff']) ?></div><?php endif; ?></td><td class="px-5 py-4"><div><?= h((string)$row['alternate_no']) ?></div><div class="text-xs text-slate-400"><?= h($dayMap[(int)$row['alternate']] ?? '') ?></div></td><td class="px-5 py-4 font-semibold"><?= (int)$row['workin_week'] > 0 ? (int)$row['workin_week'] : '' ?></td><td class="px-5 py-4"><div><?= (int)$row['work_before'] > 0 ? (int)$row['work_before'] : '' ?></div><div class="text-xs text-slate-400"><?= (int)$row['work_beforehrs'] > 0 ? (int)$row['work_beforehrs'] . ' min' : '' ?></div></td><td class="px-5 py-4 font-semibold"><?= (int)$row['andor']===0?'AND':'OR' ?></td><td class="px-5 py-4"><div><?= (int)$row['work_after'] > 0 ? (int)$row['work_after'] : '' ?></div><div class="text-xs text-slate-400"><?= (int)$row['work_afterhrs'] > 0 ? (int)$row['work_afterhrs'] . ' min' : '' ?></div></td><td class="px-5 py-4 font-semibold"><?= (int)$row['woffon_presentday']===1?'Yes':'' ?></td><td class="px-5 py-4"><?= h(woc_exclude_labels((string)$row['exclude'])) ?></td><td class="px-5 py-4"><?= (int)$row['wfree_shifthrs'] > 0 ? (int)$row['wfree_shifthrs'] . ' min' : '' ?></td><td class="px-5 py-4"><div class="flex justify-end gap-2"><?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'=>$search,'month'=>$filterMonth,'year'=>$filterYear,'weekoff_type'=>$filterType]; if($page>1): ?><a class="rounded-lg border border-slate-200 px-4 py-2 font-semibold" href="?<?= h(http_build_query($base + ['page'=>$page-1])) ?>">Previous</a><?php endif; ?><?php if($page<$pages): ?><a class="rounded-lg border border-slate-200 px-4 py-2 font-semibold" href="?<?= h(http_build_query($base + ['page'=>$page+1])) ?>">Next</a><?php endif; ?></div></div><?php endif; ?>
</section>
<?php endif; ?>
<?php console_footer(); ?>
