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

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

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

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

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

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

function wos_slab_exists(mysqli $con, int $id): bool
{
    $stmt = wos_stmt($con, 'SELECT id FROM jos_app_weeklyoffslab WHERE id=? LIMIT 1');
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $exists = (bool)$stmt->get_result()->fetch_assoc();
    $stmt->close();
    return $exists;
}

function wos_grid_rows(mysqli $con, int $slabId): array
{
    $rows = [];
    $stmt = wos_stmt($con, 'SELECT id,sr_no,slabid,presentday,weeklyoff FROM jos_app_weeklyoffslab_grid WHERE slabid=? ORDER BY presentday ASC,sr_no ASC,id ASC');
    $stmt->bind_param('i', $slabId);
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) $rows[] = $row;
    $stmt->close();
    return $rows;
}

function wos_history_rows(mysqli $con, int $slabId): array
{
    if (!wos_columns($con, 'jos_app_weeklyoffslab_editlog')) return [];
    $rows = [];
    $order = wos_has_column($con, 'jos_app_weeklyoffslab_editlog', 'sysdate') ? 'sysdate DESC,id DESC' : 'id DESC';
    $stmt = wos_stmt($con, 'SELECT * FROM jos_app_weeklyoffslab_editlog WHERE slabid=? ORDER BY ' . $order);
    $stmt->bind_param('i', $slabId);
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) $rows[] = $row;
    $stmt->close();

    if (!wos_columns($con, 'jos_app_weeklyoffslab_grid_editlog')) return $rows;
    foreach ($rows as &$row) {
        $row['grid'] = [];
        $logId = (int)($row['id'] ?? 0);
        if ($logId <= 0) continue;
        $stmt = wos_stmt($con, 'SELECT sr_no,presentday,weeklyoff FROM jos_app_weeklyoffslab_grid_editlog WHERE slabid=? ORDER BY presentday ASC,sr_no ASC,id ASC');
        $stmt->bind_param('i', $logId);
        $stmt->execute();
        $gridResult = $stmt->get_result();
        while ($grid = $gridResult->fetch_assoc()) $row['grid'][] = $grid;
        $stmt->close();
    }
    unset($row);
    return $rows;
}

function wos_insert_history(mysqli $con, int $slabId, array $rows): void
{
    $historyColumns = wos_columns($con, 'jos_app_weeklyoffslab_editlog');
    if (!$historyColumns) return;
    $userId = (int)(current_user()['id'] ?? 0);

    $fields = [];
    $placeholders = [];
    $types = '';
    $params = [];
    $source = null;
    $stmt = wos_stmt($con, 'SELECT * FROM jos_app_weeklyoffslab WHERE id=? LIMIT 1');
    $stmt->bind_param('i', $slabId);
    $stmt->execute();
    $source = $stmt->get_result()->fetch_assoc() ?: [];
    $stmt->close();

    foreach ($historyColumns as $column) {
        if ($column === 'id') continue;
        if ($column === 'slabid') {
            $fields[] = $column; $placeholders[] = '?'; $types .= 'i'; $params[] = $slabId;
        } elseif ($column === 'sysdate') {
            $fields[] = $column; $placeholders[] = 'NOW()';
        } elseif ($column === 'userid' || $column === 'modifed_by' || $column === 'modified_by') {
            $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;
    $sql = 'INSERT INTO jos_app_weeklyoffslab_editlog (`' . implode('`,`', $fields) . '`) VALUES (' . implode(',', $placeholders) . ')';
    $stmt = wos_stmt($con, $sql);
    if ($types !== '') $stmt->bind_param($types, ...$params);
    if (!$stmt->execute()) throw new RuntimeException('Unable to save weekly off slab history.');
    $editLogId = (int)$con->insert_id;
    $stmt->close();

    if ($editLogId <= 0 || !wos_columns($con, 'jos_app_weeklyoffslab_grid_editlog')) return;
    foreach ($rows as $row) {
        $stmt = wos_stmt($con, 'INSERT INTO jos_app_weeklyoffslab_grid_editlog (sr_no,slabid,`date`,presentday,weeklyoff) VALUES (?,?,NOW(),?,?)');
        $stmt->bind_param('iiii', $row['sr_no'], $editLogId, $row['presentday'], $row['weeklyoff']);
        if (!$stmt->execute()) throw new RuntimeException('Unable to save weekly off slab grid history.');
        $stmt->close();
    }
}

$payrollLocations = wos_options($con, 'SELECT id,name FROM jos_app_payrolllocation ORDER BY name,id');
$months = wos_options($con, 'SELECT id,month AS name FROM jos_app_mmonth ORDER BY id');
$years = wos_options($con, 'SELECT id,year AS name,assessment FROM jos_app_year ORDER BY id DESC');
$payrollMap = $monthMap = $yearMap = [];
foreach ($payrollLocations as $row) $payrollMap[(int)$row['id']] = (string)$row['name'];
foreach ($months as $row) $monthMap[(int)$row['id']] = (string)$row['name'];
foreach ($years as $row) $yearMap[(int)$row['id']] = (string)$row['name'];

$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;
$gridRows = [];
$historyParent = null;
$historyRows = [];

if ($historyId > 0) {
    $stmt = wos_stmt($con, 'SELECT s.*,p.name AS payroll_name,m.month AS month_name,y.year AS year_name FROM jos_app_weeklyoffslab s LEFT JOIN jos_app_payrolllocation p ON p.id=s.org LEFT JOIN jos_app_mmonth m ON m.id=s.month LEFT JOIN jos_app_year y ON y.id=s.year WHERE s.id=? LIMIT 1');
    $stmt->bind_param('i', $historyId);
    $stmt->execute();
    $historyParent = $stmt->get_result()->fetch_assoc() ?: null;
    $stmt->close();
    if (!$historyParent) {
        $_SESSION['flash_weekly_off_slab'] = 'Weekly Off Slab was not found.';
        redirect('/attendance/weekly-off-slab.php');
    }
    $historyRows = wos_history_rows($con, $historyId);
}

if (!$isHistory && $editId > 0) {
    $stmt = wos_stmt($con, 'SELECT * FROM jos_app_weeklyoffslab 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_slab'] = 'Weekly Off Slab was not found.';
        redirect('/attendance/weekly-off-slab.php');
    }
    $gridRows = wos_grid_rows($con, $editId);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = (string)($_POST['action'] ?? '');
    if (!verify_csrf($_POST['_csrf'] ?? null)) {
        $errors[] = 'Security token expired. Please refresh and try again.';
    } elseif ($action === 'save') {
        $id = max(0, (int)($_POST['id'] ?? 0));
        if ($id > 0 && empty($acl['can_edit'])) $errors[] = 'You do not have permission to edit weekly off slabs.';
        if ($id === 0 && empty($acl['can_add'])) $errors[] = 'You do not have permission to add weekly off slabs.';
        if ($id > 0 && !wos_slab_exists($con, $id)) $errors[] = 'Weekly Off Slab was not found.';

        $org = max(0, (int)($_POST['org'] ?? 0));
        $month = max(0, (int)($_POST['month'] ?? 0));
        $year = max(0, (int)($_POST['year'] ?? 0));
        $totalMonthDays = wos_int($_POST['total_month_days'] ?? '', 'Total month days', $errors, 1, 31);

        if (!wos_valid_id($con, 'jos_app_payrolllocation', $org)) $errors[] = 'Select a valid payroll location.';
        if (!wos_valid_id($con, 'jos_app_mmonth', $month)) $errors[] = 'Select a valid month.';
        if (!wos_valid_id($con, 'jos_app_year', $year)) $errors[] = 'Select a valid year.';

        $presentDays = (array)($_POST['presentday'] ?? []);
        $weeklyOffs = (array)($_POST['weeklyoff'] ?? []);
        $rowsToSave = [];
        $seen = [];
        foreach ($presentDays as $index => $presentValue) {
            $weeklyValue = $weeklyOffs[$index] ?? '';
            if (trim((string)$presentValue) === '' && trim((string)$weeklyValue) === '') continue;
            $presentDay = wos_int($presentValue, 'Days Present row ' . ((int)$index + 1), $errors, 0, 31);
            $weeklyOff = wos_int($weeklyValue, 'Weekly off day row ' . ((int)$index + 1), $errors, 0, 31);
            if (isset($seen[$presentDay])) $errors[] = 'Days Present value ' . $presentDay . ' is duplicated.';
            $seen[$presentDay] = true;
            $rowsToSave[] = ['sr_no' => count($rowsToSave) + 1, 'presentday' => $presentDay, 'weeklyoff' => $weeklyOff];
        }
        if (!$rowsToSave) $errors[] = 'Add at least one slab row.';

        if (!$errors) {
            $con->begin_transaction();
            try {
                $hasUserId = wos_has_column($con, 'jos_app_weeklyoffslab', 'userid');
                $userId = (int)(current_user()['id'] ?? 0);
                if ($id > 0) {
                    if ($hasUserId) {
                        $stmt = wos_stmt($con, 'UPDATE jos_app_weeklyoffslab SET userid=?,org=?,month=?,year=?,total_month_days=? WHERE id=?');
                        $stmt->bind_param('iiiiii', $userId, $org, $month, $year, $totalMonthDays, $id);
                    } else {
                        $stmt = wos_stmt($con, 'UPDATE jos_app_weeklyoffslab SET org=?,month=?,year=?,total_month_days=? WHERE id=?');
                        $stmt->bind_param('iiiii', $org, $month, $year, $totalMonthDays, $id);
                    }
                    if (!$stmt->execute()) throw new RuntimeException('Unable to update weekly off slab.');
                    $stmt->close();
                    $savedId = $id;
                } else {
                    if ($hasUserId) {
                        $stmt = wos_stmt($con, 'INSERT INTO jos_app_weeklyoffslab (userid,org,month,year,total_month_days) VALUES (?,?,?,?,?)');
                        $stmt->bind_param('iiiii', $userId, $org, $month, $year, $totalMonthDays);
                    } else {
                        $stmt = wos_stmt($con, 'INSERT INTO jos_app_weeklyoffslab (org,month,year,total_month_days) VALUES (?,?,?,?)');
                        $stmt->bind_param('iiii', $org, $month, $year, $totalMonthDays);
                    }
                    if (!$stmt->execute()) throw new RuntimeException('Unable to add weekly off slab.');
                    $savedId = (int)$con->insert_id;
                    $stmt->close();
                }

                $stmt = wos_stmt($con, 'DELETE FROM jos_app_weeklyoffslab_grid WHERE slabid=?');
                $stmt->bind_param('i', $savedId);
                $stmt->execute();
                $stmt->close();

                foreach ($rowsToSave as $row) {
                    $stmt = wos_stmt($con, 'INSERT INTO jos_app_weeklyoffslab_grid (sr_no,slabid,presentday,weeklyoff) VALUES (?,?,?,?)');
                    $stmt->bind_param('iiii', $row['sr_no'], $savedId, $row['presentday'], $row['weeklyoff']);
                    if (!$stmt->execute()) throw new RuntimeException('Unable to save weekly off slab row.');
                    $stmt->close();
                }

                wos_insert_history($con, $savedId, $rowsToSave);
                $con->commit();
                audit_log($id > 0 ? 'weekly_off_slab.update' : 'weekly_off_slab.create', 'jos_app_weeklyoffslab', (string)$savedId, $payrollMap[$org] ?? '');
                $_SESSION['flash_weekly_off_slab'] = $id > 0 ? 'Weekly Off Slab updated successfully.' : 'Weekly Off Slab added successfully.';
                redirect('/attendance/weekly-off-slab.php');
            } catch (Throwable $e) {
                $con->rollback();
                $errors[] = 'Unable to save the weekly off slab. No changes were committed.';
            }
        }

        $isForm = true;
        $isHistory = false;
        $editId = $id;
        $editRow = ['id' => $id, 'org' => $org, 'month' => $month, 'year' => $year, 'total_month_days' => $totalMonthDays];
        $gridRows = $rowsToSave;
    }
}

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

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

    $stmt = wos_stmt($con, 'SELECT COUNT(*) AS total FROM jos_app_weeklyoffslab s 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 = wos_stmt($con, 'SELECT s.*,p.name AS payroll_name,m.month AS month_name,y.year AS year_name,(SELECT COUNT(*) FROM jos_app_weeklyoffslab_editlog e WHERE e.slabid=s.id) AS history_count FROM jos_app_weeklyoffslab s LEFT JOIN jos_app_payrolllocation p ON p.id=s.org LEFT JOIN jos_app_mmonth m ON m.id=s.month LEFT JOIN jos_app_year y ON y.id=s.year WHERE ' . $whereSql . ' ORDER BY p.name ASC,DATE(CONCAT(y.year, "-", s.month, "-01")) DESC,s.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()) {
        $row['grid'] = wos_grid_rows($con, (int)$row['id']);
        $rows[] = $row;
    }
    $stmt->close();
}

$value = static function (string $key, $default = '') use (&$editRow) { return $editRow[$key] ?? $default; };
$input = 'mt-1 w-full rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm text-slate-800 outline-none focus:border-brand-500 focus:ring-2 focus:ring-brand-100';
$selectSmall = 'rounded-xl border border-slate-200 px-3 py-2.5 text-sm';
if (!$gridRows && $isForm) $gridRows = [['presentday' => '', 'weeklyoff' => '']];

console_header('Weekly Off Slab', $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 Slab</span></div><h1 class="text-2xl font-bold text-slate-900">Weekly Off Slab</h1><p class="mt-1 text-sm text-slate-500">Configure custom weekly-off slabs by payroll location and monthly present days.</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">Weekly Off Slab History</h2>
      <p class="mt-1 text-xs font-medium text-slate-400"><?= h($historyParent['payroll_name'] ?: ($payrollMap[(int)$historyParent['org']] ?? 'Unknown')) ?> · <?= h($historyParent['month_name'] ?: ($monthMap[(int)$historyParent['month']] ?? 'Unknown')) ?> <?= h($historyParent['year_name'] ?: ($yearMap[(int)$historyParent['year']] ?? (string)$historyParent['year'])) ?></p>
    </div>
    <a href="/attendance/weekly-off-slab.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] uppercase tracking-wider text-slate-400"><tr><th class="px-5 py-4 w-20">Sr No</th><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">Year</th><th class="px-5 py-4">Total Month Days</th><th class="px-5 py-4">Custom Weekly Slab</th></tr></thead>
      <tbody class="divide-y divide-slate-100">
        <?php if(!$historyRows): ?><tr><td colspan="7" class="px-6 py-14 text-center font-semibold text-slate-400">No history found.</td></tr><?php endif; ?>
        <?php foreach($historyRows as $index=>$row): ?>
          <tr class="align-top hover:bg-slate-50/70">
            <td class="px-5 py-4 font-semibold text-slate-500"><?= $index + 1 ?></td>
            <td class="px-5 py-4 font-semibold text-slate-700"><?= h((string)($row['sysdate'] ?? '')) ?></td>
            <td class="px-5 py-4 font-bold text-slate-800"><?= h($payrollMap[(int)($row['org'] ?? 0)] ?? (string)($row['org'] ?? '')) ?></td>
            <td class="px-5 py-4 font-semibold text-slate-700"><?= h($monthMap[(int)($row['month'] ?? 0)] ?? (string)($row['month'] ?? '')) ?></td>
            <td class="px-5 py-4 font-semibold text-slate-700"><?= h($yearMap[(int)($row['year'] ?? 0)] ?? (string)($row['year'] ?? '')) ?></td>
            <td class="px-5 py-4 font-semibold"><?= h((string)($row['total_month_days'] ?? '')) ?></td>
            <td class="px-5 py-4"><div class="overflow-hidden rounded-xl border border-slate-100"><table class="w-full text-xs"><thead class="bg-slate-50 text-[10px] uppercase text-slate-400"><tr><th class="px-3 py-2 text-left">No</th><th class="px-3 py-2 text-left">Days Present</th><th class="px-3 py-2 text-left">Weekly Off Day</th></tr></thead><tbody><?php if(empty($row['grid'])): ?><tr><td colspan="3" class="px-3 py-3 text-center font-semibold text-slate-400">No rows</td></tr><?php endif; ?><?php foreach($row['grid'] as $gIndex=>$grid): ?><tr class="border-t border-slate-100"><td class="px-3 py-2"><?= $gIndex + 1 ?></td><td class="px-3 py-2 font-semibold"><?= h((string)$grid['presentday']) ?></td><td class="px-3 py-2 font-semibold"><?= h((string)$grid['weeklyoff']) ?></td></tr><?php endforeach; ?></tbody></table></div></td>
          </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</section>
<?php elseif ($isForm): ?>
<form method="post" id="weekly-off-slab-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-table-cells"></i></span><div><h2 class="font-bold text-slate-800"><?= (int)$value('id',0)>0?'Edit Weekly Off Slab':'New Weekly Off Slab' ?></h2><p class="text-xs text-slate-400">Fields marked with * are required.</p></div></div><a href="/attendance/weekly-off-slab.php" class="rounded-lg border border-slate-200 bg-white px-4 py-2 text-sm font-bold text-slate-600 hover:bg-slate-50"><i class="fa-solid fa-arrow-left mr-2"></i>Back to List</a></div>
    <div class="grid gap-3 md:grid-cols-4">
      <label class="text-sm font-semibold text-slate-700">Payroll Location *<select name="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">Total Month Days *<input name="total_month_days" inputmode="numeric" pattern="\d*" required value="<?= h((string)$value('total_month_days')) ?>" class="<?= $input ?>" placeholder="Total Month Days"></label>
    </div>
  </section>

  <section class="overflow-hidden rounded-2xl border border-slate-100 bg-white shadow-sm">
    <div class="flex items-center justify-between border-b border-slate-100 px-5 py-4"><div><h2 class="font-bold text-slate-800">Custom Weekly Slab</h2><p class="mt-1 text-xs font-medium text-slate-400">Map present days to weekly off days.</p></div><button type="button" id="add-slab-row" class="rounded-lg bg-brand-600 px-4 py-2 text-sm font-bold text-white hover:bg-brand-700"><i class="fa-solid fa-plus mr-2"></i>Add Row</button></div>
    <div class="overflow-x-auto"><table class="w-full min-w-[620px] text-left text-sm"><thead class="bg-slate-50 text-[10px] uppercase tracking-wider text-slate-400"><tr><th class="px-5 py-4 w-20">No</th><th class="px-5 py-4">Days Present</th><th class="px-5 py-4">Weekly Off Day</th><th class="px-5 py-4 text-right w-24">Action</th></tr></thead><tbody id="slab-rows" class="divide-y divide-slate-100"><?php foreach($gridRows as $index=>$row): ?><tr><td class="row-number px-5 py-4 font-semibold text-slate-500"><?= $index + 1 ?></td><td class="px-5 py-4"><input name="presentday[]" inputmode="numeric" pattern="\d*" required value="<?= h((string)($row['presentday'] ?? '')) ?>" class="<?= $input ?> mt-0" placeholder="Days Present"></td><td class="px-5 py-4"><input name="weeklyoff[]" inputmode="numeric" pattern="\d*" required value="<?= h((string)($row['weeklyoff'] ?? '')) ?>" class="<?= $input ?> mt-0" placeholder="Weekly Off Day"></td><td class="px-5 py-4 text-right"><button type="button" class="remove-slab-row rounded-lg border border-red-100 px-3 py-2 text-red-500 hover:bg-red-50" title="Remove"><i class="fa-solid fa-trash"></i></button></td></tr><?php endforeach; ?></tbody></table></div>
  </section>
  <div class="flex flex-wrap justify-end gap-2"><a href="/attendance/weekly-off-slab.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 Slab</button></div>
</form>
<template id="slab-row-template"><tr><td class="row-number px-5 py-4 font-semibold text-slate-500"></td><td class="px-5 py-4"><input name="presentday[]" inputmode="numeric" pattern="\d*" required class="<?= $input ?> mt-0" placeholder="Days Present"></td><td class="px-5 py-4"><input name="weeklyoff[]" inputmode="numeric" pattern="\d*" required class="<?= $input ?> mt-0" placeholder="Weekly Off Day"></td><td class="px-5 py-4 text-right"><button type="button" class="remove-slab-row rounded-lg border border-red-100 px-3 py-2 text-red-500 hover:bg-red-50" title="Remove"><i class="fa-solid fa-trash"></i></button></td></tr></template>
<script>(()=>{const body=document.getElementById('slab-rows'),add=document.getElementById('add-slab-row'),tpl=document.getElementById('slab-row-template');const renumber=()=>[...body.querySelectorAll('tr')].forEach((row,index)=>row.querySelector('.row-number').textContent=index+1);add.addEventListener('click',()=>{body.appendChild(tpl.content.cloneNode(true));renumber();});body.addEventListener('click',event=>{const button=event.target.closest('.remove-slab-row');if(!button)return;if(body.querySelectorAll('tr').length===1){button.closest('tr').querySelectorAll('input').forEach(input=>input.value='');return;}button.closest('tr').remove();renumber();});renumber();})();</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 Slab List</h2><p class="mt-1 text-xs font-medium text-slate-400">Slabs are grouped by payroll location and ordered by latest 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"><select name="org" class="<?= $selectSmall ?>"><option value="0">All Payroll Locations</option><?php foreach($payrollLocations as $option): ?><option value="<?= (int)$option['id'] ?>" <?= $filterOrg===(int)$option['id']?'selected':'' ?>><?= h($option['name']) ?></option><?php endforeach; ?></select><select name="month" class="<?= $selectSmall ?>"><option value="0">All Months</option><?php foreach($months as $option): ?><option value="<?= (int)$option['id'] ?>" <?= $filterMonth===(int)$option['id']?'selected':'' ?>><?= h($option['name']) ?></option><?php endforeach; ?></select><select name="year" class="<?= $selectSmall ?>"><option value="0">All Years</option><?php foreach($years as $option): ?><option value="<?= (int)$option['id'] ?>" <?= $filterYear===(int)$option['id']?'selected':'' ?>><?= h($option['name']) ?></option><?php endforeach; ?></select><div class="flex gap-2 xl:col-span-2"><button class="rounded-xl bg-slate-900 px-5 py-2.5 text-sm font-bold text-white"><i class="fa-solid fa-filter mr-2"></i>Filter</button><a href="/attendance/weekly-off-slab.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-[1080px] 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">Payroll Location</th><th class="px-5 py-4">Month</th><th class="px-5 py-4">Year</th><th class="px-5 py-4">Total Month Days</th><th class="px-5 py-4">Custom Weekly Slab</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="7" class="px-6 py-14 text-center font-semibold text-slate-400">No weekly off slabs 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['payroll_name'] ?: ($payrollMap[(int)$row['org']] ?? 'Unknown')) ?></div><?php if((int)$row['history_count']>1): ?><div class="mt-1 text-xs font-semibold text-slate-400">History <?= (int)$row['history_count'] ?></div><?php endif; ?></td><td class="px-5 py-4 font-semibold text-slate-700"><?= h($row['month_name'] ?: ($monthMap[(int)$row['month']] ?? 'Unknown')) ?></td><td class="px-5 py-4 font-semibold text-slate-700"><?= h($row['year_name'] ?: ($yearMap[(int)$row['year']] ?? (string)$row['year'])) ?></td><td class="px-5 py-4 font-semibold"><?= (int)$row['total_month_days'] ?></td><td class="px-5 py-4"><div class="overflow-hidden rounded-xl border border-slate-100"><table class="w-full text-xs"><thead class="bg-slate-50 text-[10px] uppercase text-slate-400"><tr><th class="px-3 py-2 text-left">No</th><th class="px-3 py-2 text-left">Days Present</th><th class="px-3 py-2 text-left">Weekly Off Day</th></tr></thead><tbody><?php if(empty($row['grid'])): ?><tr><td colspan="3" class="px-3 py-3 text-center font-semibold text-slate-400">No rows</td></tr><?php endif; ?><?php foreach($row['grid'] as $gIndex=>$grid): ?><tr class="border-t border-slate-100"><td class="px-3 py-2"><?= $gIndex + 1 ?></td><td class="px-3 py-2 font-semibold"><?= h((string)$grid['presentday']) ?></td><td class="px-3 py-2 font-semibold"><?= h((string)$grid['weeklyoff']) ?></td></tr><?php endforeach; ?></tbody></table></div></td><td class="px-5 py-4"><div class="flex justify-end gap-2"><?php if((int)$row['history_count']>1): ?><a href="?history=<?= (int)$row['id'] ?>" class="rounded-lg border border-slate-200 px-3 py-2 text-slate-600 hover:bg-brand-50 hover:text-brand-600" title="History"><i class="fa-solid fa-clock-rotate-left"></i></a><?php endif; ?><?php if(!empty($acl['can_edit'])): ?><a href="?edit=<?= (int)$row['id'] ?>" class="rounded-lg border border-slate-200 px-3 py-2 text-slate-600 hover:bg-brand-50 hover:text-brand-600" title="Edit"><i class="fa-solid fa-pen"></i></a><?php endif; ?></div></td></tr><?php endforeach; ?>
  </tbody></table></div>
  <?php if($totalRows>$perPage): ?><div class="flex items-center justify-between border-t border-slate-100 px-5 py-4 text-sm"><span class="font-medium text-slate-500"><?= $totalRows ?> slabs</span><div class="flex gap-2"><?php $base=['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(); ?>
