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

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

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

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

function cc_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 cc_ids($value): array
{
    $ids = array_map('intval', (array)$value);
    $ids = array_values(array_unique(array_filter($ids, static function ($id) { return $id > 0; })));
    sort($ids, SORT_NUMERIC);
    return $ids;
}

function cc_valid_id(mysqli $con, string $table, int $id, string $extra = ''): bool
{
    $allowed = ['jos_app_salarytype', 'jos_app_mmonth', 'jos_app_year', 'jos_app_payrolllocation'];
    if ($id <= 0 || !in_array($table, $allowed, true)) return false;
    $stmt = cc_stmt($con, 'SELECT id FROM `' . $table . '` WHERE id=? ' . $extra . ' LIMIT 1');
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $valid = (bool)$stmt->get_result()->fetch_assoc();
    $stmt->close();
    return $valid;
}

function cc_valid_ids(mysqli $con, string $table, array $ids, string $extra = ''): bool
{
    foreach ($ids as $id) if (!cc_valid_id($con, $table, (int)$id, $extra)) return false;
    return (bool)$ids;
}

function cc_write_history(mysqli $con, int $id): void
{
    $modifiedBy = (int)((current_user()['id'] ?? 0));
    $stmt = cc_stmt($con, 'INSERT INTO jos_app_calender_config_editlog (calenderid,date,month,year,org,salary_type,total_month_days,mwday_woff,std_weeklyoff,max_working_days,min_working_days,min_paidoff_days,allowance_day,max_working_hrs,min_working_hrs,otrate_woff,modify_by,days_calculation) SELECT id,NOW(),month,year,org,salary_type,total_month_days,mwday_woff,std_weeklyoff,max_working_days,min_working_days,min_paidoff_days,allowance_day,max_working_hrs,min_working_hrs,otrate_woff,?,days_calculation FROM jos_app_calender_config WHERE id=?');
    $stmt->bind_param('ii', $modifiedBy, $id);
    if (!$stmt->execute()) throw new RuntimeException('Unable to write configuration history.');
    $stmt->close();
}

$salaryTypes = cc_options($con, 'SELECT id,name FROM jos_app_salarytype ORDER BY id');
$months = cc_options($con, 'SELECT id,month AS name FROM jos_app_mmonth ORDER BY id');
$years = cc_options($con, 'SELECT id,year AS name,assessment FROM jos_app_year ORDER BY id DESC');
$payrollLocations = cc_options($con, 'SELECT id,name FROM jos_app_payrolllocation WHERE status=1 ORDER BY name,id');
$salaryMap = $monthMap = $yearMap = $payrollMap = [];
foreach ($salaryTypes as $row) $salaryMap[(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'];
foreach ($payrollLocations as $row) $payrollMap[(int)$row['id']] = (string)$row['name'];

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

if ($editId > 0) {
    $stmt = cc_stmt($con, 'SELECT * FROM jos_app_calender_config WHERE id=? LIMIT 1');
    $stmt->bind_param('i', $editId);
    $stmt->execute();
    $editRow = $stmt->get_result()->fetch_assoc() ?: null;
    $stmt->close();
    if (!$editRow) {
        $_SESSION['flash_calendar_configuration'] = 'Calendar configuration was not found.';
        redirect('/attendance/calendar-configuration.php');
    }
    $selectedOrgs = cc_ids(explode(',', (string)$editRow['org']));
}

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 calendar configurations.';
        if ($id === 0 && empty($acl['can_add'])) $errors[] = 'You do not have permission to add calendar configurations.';

        $salaryType = max(0, (int)($_POST['salary_type'] ?? 0));
        $month = max(0, (int)($_POST['month'] ?? 0));
        $year = max(0, (int)($_POST['year'] ?? 0));
        $orgIds = cc_ids($_POST['org'] ?? []);
        $daysCalculation = (int)($_POST['days_calculation'] ?? 0);
        $otRateWoff = (int)($_POST['otrate_woff'] ?? 0);
        $totalMonthDays = (int)($_POST['total_month_days'] ?? 0);
        $mwdayWoff = (int)($_POST['mwday_woff'] ?? 0);
        $maxWorkingDays = (int)($_POST['max_working_days'] ?? 0);
        $minWorkingDays = (int)($_POST['min_working_days'] ?? 0);
        $allowanceDay = (float)($_POST['allowance_day'] ?? -1);
        $maxWorkingHrs = (int)($_POST['max_working_hrs'] ?? 0);
        $minWorkingHrs = (int)($_POST['min_working_hrs'] ?? 0);
        $stdWeeklyOff = (int)($editRow['std_weeklyoff'] ?? 0);
        $minPaidOffDays = (int)($editRow['min_paidoff_days'] ?? 0);

        if (!cc_valid_id($con, 'jos_app_salarytype', $salaryType)) $errors[] = 'Select a valid salary type.';
        if (!cc_valid_id($con, 'jos_app_mmonth', $month)) $errors[] = 'Select a valid month.';
        if (!cc_valid_id($con, 'jos_app_year', $year)) $errors[] = 'Select a valid year.';
        if (!cc_valid_ids($con, 'jos_app_payrolllocation', $orgIds, 'AND status=1')) $errors[] = 'Select at least one valid payroll location.';
        if (!in_array($daysCalculation, [0,1], true)) $errors[] = 'Select a valid total-days calculation type.';
        if (!in_array($mwdayWoff, [0,1,2], true)) $errors[] = 'Select a valid maximum-working-days mode.';
        if ($totalMonthDays < 1 || $totalMonthDays > 31) $errors[] = 'Total month days must be between 1 and 31.';
        if ($minWorkingDays < 0 || $minWorkingDays > 31) $errors[] = 'Minimum working days must be between 0 and 31.';
        if ($minWorkingHrs < 0 || $minWorkingHrs > 744) $errors[] = 'Minimum working hours must be between 0 and 744.';
        if ($allowanceDay < 0 || $allowanceDay > 31) $errors[] = 'Attendance allowance days must be between 0 and 31.';
        if ($salaryType !== 1) $otRateWoff = 0;
        if (!in_array($otRateWoff, [0,1], true)) $errors[] = 'Select a valid weekly-off OT option.';
        if ($mwdayWoff !== 0) {
            $maxWorkingDays = 0;
            $maxWorkingHrs = 0;
        } else {
            if ($daysCalculation === 1) $maxWorkingDays = 30;
            if ($maxWorkingDays < 0 || $maxWorkingDays > 31) $errors[] = 'Maximum working days must be between 0 and 31.';
            if ($maxWorkingHrs < 0 || $maxWorkingHrs > 744) $errors[] = 'Maximum working hours must be between 0 and 744.';
            if ($minWorkingDays > $maxWorkingDays) $errors[] = 'Minimum working days cannot exceed maximum working days.';
            if ($minWorkingHrs > $maxWorkingHrs) $errors[] = 'Minimum working hours cannot exceed maximum working hours.';
        }

        $org = implode(',', $orgIds);
        $stmt = cc_stmt($con, 'SELECT id FROM jos_app_calender_config WHERE salary_type=? AND month=? AND year=? AND org=? AND id<>? LIMIT 1');
        $stmt->bind_param('iiisi', $salaryType, $month, $year, $org, $id);
        $stmt->execute();
        if ($stmt->get_result()->fetch_assoc()) $errors[] = 'An identical configuration already exists for this salary type, month, year and payroll-location selection.';
        $stmt->close();

        if (!$errors) {
            $con->begin_transaction();
            try {
                if ($id > 0) {
                    $stmt = cc_stmt($con, 'UPDATE jos_app_calender_config SET month=?,year=?,org=?,salary_type=?,total_month_days=?,mwday_woff=?,std_weeklyoff=?,max_working_days=?,min_working_days=?,min_paidoff_days=?,allowance_day=?,max_working_hrs=?,min_working_hrs=?,otrate_woff=?,days_calculation=? WHERE id=?');
                    $stmt->bind_param('iisiiiiiiidiiiii', $month, $year, $org, $salaryType, $totalMonthDays, $mwdayWoff, $stdWeeklyOff, $maxWorkingDays, $minWorkingDays, $minPaidOffDays, $allowanceDay, $maxWorkingHrs, $minWorkingHrs, $otRateWoff, $daysCalculation, $id);
                    if (!$stmt->execute()) throw new RuntimeException('Unable to update calendar configuration.');
                    $stmt->close();
                } else {
                    $stmt = cc_stmt($con, 'INSERT INTO jos_app_calender_config (month,year,org,salary_type,total_month_days,mwday_woff,std_weeklyoff,max_working_days,min_working_days,min_paidoff_days,allowance_day,max_working_hrs,min_working_hrs,otrate_woff,days_calculation) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)');
                    $stmt->bind_param('iisiiiiiiidiiii', $month, $year, $org, $salaryType, $totalMonthDays, $mwdayWoff, $stdWeeklyOff, $maxWorkingDays, $minWorkingDays, $minPaidOffDays, $allowanceDay, $maxWorkingHrs, $minWorkingHrs, $otRateWoff, $daysCalculation);
                    if (!$stmt->execute()) throw new RuntimeException('Unable to add calendar configuration.');
                    $id = (int)$con->insert_id;
                    $stmt->close();
                }
                cc_write_history($con, $id);
                $con->commit();
                audit_log($editId > 0 ? 'calendar_configuration.update' : 'calendar_configuration.create', 'jos_app_calender_config', (string)$id, $salaryMap[$salaryType] ?? '');
                $_SESSION['flash_calendar_configuration'] = $editId > 0 ? 'Calendar configuration updated successfully.' : 'Calendar configuration added successfully.';
                redirect('/attendance/calendar-configuration.php');
            } catch (Throwable $e) {
                $con->rollback();
                $errors[] = 'Unable to save the calendar configuration. No changes were committed.';
            }
        }
        $isForm = true;
        $editId = $id;
        $selectedOrgs = $orgIds;
        $editRow = compact('id','salaryType','month','year','org','totalMonthDays','mwdayWoff','stdWeeklyOff','maxWorkingDays','minWorkingDays','minPaidOffDays','allowanceDay','maxWorkingHrs','minWorkingHrs','otRateWoff','daysCalculation');
        $editRow = [
            'id'=>$id,'salary_type'=>$salaryType,'month'=>$month,'year'=>$year,'org'=>$org,
            'total_month_days'=>$totalMonthDays,'mwday_woff'=>$mwdayWoff,'std_weeklyoff'=>$stdWeeklyOff,
            'max_working_days'=>$maxWorkingDays,'min_working_days'=>$minWorkingDays,'min_paidoff_days'=>$minPaidOffDays,
            'allowance_day'=>$allowanceDay,'max_working_hrs'=>$maxWorkingHrs,'min_working_hrs'=>$minWorkingHrs,
            'otrate_woff'=>$otRateWoff,'days_calculation'=>$daysCalculation
        ];
    } elseif ($action === 'delete') {
        if (empty($acl['can_delete'])) $errors[] = 'You do not have permission to delete calendar configurations.';
        $id = max(0, (int)($_POST['id'] ?? 0));
        if ($id <= 0) $errors[] = 'Invalid calendar configuration selected.';
        if (!$errors) {
            $stmt = cc_stmt($con, 'SELECT salary_type,month,year FROM jos_app_calender_config WHERE id=? LIMIT 1');
            $stmt->bind_param('i', $id); $stmt->execute();
            $record = $stmt->get_result()->fetch_assoc(); $stmt->close();
            if (!$record) $errors[] = 'Calendar configuration was not found.';
        }
        if (!$errors) {
            $con->begin_transaction();
            try {
                $tableCheck = $con->query("SHOW TABLES LIKE 'jos_app_halfday_config'");
                if ($tableCheck && $tableCheck->num_rows > 0) {
                    $stmt = cc_stmt($con, 'DELETE FROM jos_app_halfday_config WHERE configid=?');
                    $stmt->bind_param('i', $id); $stmt->execute(); $stmt->close();
                }
                if ($tableCheck) $tableCheck->free();
                $stmt = cc_stmt($con, 'DELETE FROM jos_app_calender_config WHERE id=?');
                $stmt->bind_param('i', $id); $stmt->execute(); $stmt->close();
                $con->commit();
                audit_log('calendar_configuration.delete', 'jos_app_calender_config', (string)$id, json_encode($record));
                $_SESSION['flash_calendar_configuration'] = 'Calendar configuration deleted successfully.';
                redirect('/attendance/calendar-configuration.php');
            } catch (Throwable $e) {
                $con->rollback();
                $errors[] = 'Unable to delete the calendar configuration.';
            }
        }
    }
}

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

if (!$isForm) {
    $where = ['1=1']; $types = ''; $params = [];
    foreach ([['salary_type',$filterSalary],['month',$filterMonth],['year',$filterYear]] as $filter) {
        if ($filter[1] > 0) { $where[] = $filter[0] . '=?'; $types .= 'i'; $params[] = $filter[1]; }
    }
    if ($filterOrg > 0) { $where[] = 'FIND_IN_SET(?,org)'; $types .= 'i'; $params[] = $filterOrg; }
    $whereSql = implode(' AND ', $where);
    $stmt = cc_stmt($con, 'SELECT COUNT(*) AS total FROM jos_app_calender_config 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;
    $listTypes = $types . 'ii'; $listParams = $params; $listParams[] = $perPage; $listParams[] = $offset;
    $stmt = cc_stmt($con, 'SELECT * FROM jos_app_calender_config WHERE ' . $whereSql . ' ORDER BY year DESC,month DESC,salary_type,id DESC LIMIT ? 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';
console_header('Calendar 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">Calendar Configuration</span></div><h1 class="text-2xl font-bold text-slate-900">Calendar Configuration</h1><p class="mt-1 text-sm text-slate-500">Configure monthly attendance, working-day and weekly-off rules.</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="calendar-form" class="space-y-3"><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-3 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-days"></i></span><div><h2 class="font-bold text-slate-800"><?= (int)$value('id',0)>0?'Edit Configuration':'New Configuration' ?></h2><p class="text-xs text-slate-400">Fields marked with * are required.</p></div></div><a href="/attendance/calendar-configuration.php" class="rounded-lg border border-slate-200 bg-white px-4 py-2 text-sm font-bold text-slate-600 hover:bg-slate-50"><i class="fa-solid fa-arrow-left mr-2"></i>Back to List</a></div>
    <div class="grid gap-3 md:grid-cols-2 xl:grid-cols-4">
      <label class="text-sm font-semibold text-slate-700">Salary Type *<select name="salary_type" id="salary-type" required class="<?= $input ?>"><option value="">Select Salary Type</option><?php foreach($salaryTypes as $option): ?><option value="<?= (int)$option['id'] ?>" <?= (int)$value('salary_type')===(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" id="total-month-days" type="number" min="1" max="31" required value="<?= h((string)$value('total_month_days')) ?>" class="<?= $input ?>"></label>
      <div class="relative text-sm font-semibold text-slate-700 md:col-span-2 xl:col-span-4" id="payroll-picker">Payroll Locations *
        <button type="button" id="payroll-picker-toggle" class="<?= $input ?> flex min-h-[38px] items-center justify-between gap-3 text-left font-normal"><span id="payroll-picker-summary" class="truncate text-slate-500">Select payroll locations</span><i class="fa-solid fa-chevron-down text-xs text-slate-400"></i></button>
        <div id="payroll-picker-panel" class="absolute left-0 right-0 top-full z-50 mt-1 hidden overflow-hidden rounded-xl border border-slate-200 bg-white shadow-xl">
          <div class="border-b border-slate-100 p-2"><input type="search" id="payroll-picker-search" placeholder="Search payroll location..." autocomplete="off" class="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm font-normal outline-none focus:border-brand-500"></div>
          <div id="payroll-picker-options" class="max-h-44 overflow-y-auto p-2"><?php foreach($payrollLocations as $option): ?><label class="payroll-option flex cursor-pointer items-center gap-3 rounded-lg px-3 py-2 text-sm font-normal text-slate-700 hover:bg-brand-50" data-name="<?= h(strtolower((string)$option['name'])) ?>"><input type="checkbox" name="org[]" value="<?= (int)$option['id'] ?>" <?= in_array((int)$option['id'],$selectedOrgs,true)?'checked':'' ?> class="rounded border-slate-300 text-brand-600"><span><?= h($option['name']) ?></span></label><?php endforeach; ?><div id="payroll-picker-empty" class="hidden px-3 py-4 text-center text-xs text-slate-400">No payroll location found.</div></div>
        </div>
      </div>
    </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-violet-50 text-violet-600"><i class="fa-solid fa-business-time"></i></span><div><h2 class="font-bold text-slate-800">Attendance & Weekly-Off Rules</h2><p class="text-xs text-slate-400">Control monthly attendance limits and calculation behavior.</p></div></div>
    <div class="grid gap-3 md:grid-cols-2 xl:grid-cols-4">
      <label class="text-sm font-semibold text-slate-700">Total Days Calculation<select name="days_calculation" id="days-calculation" class="<?= $input ?>"><option value="0" <?= (int)$value('days_calculation')===0?'selected':'' ?>>Regular</option><option value="1" <?= (int)$value('days_calculation')===1?'selected':'' ?>>Fixed 30 days for each month</option></select></label>
      <label class="text-sm font-semibold text-slate-700">Maximum Working Days On<select name="mwday_woff" id="max-days-mode" class="<?= $input ?>"><option value="0" <?= (int)$value('mwday_woff')===0?'selected':'' ?>>Manual Days / Hours</option><option value="1" <?= (int)$value('mwday_woff')===1?'selected':'' ?>>Weekly Off</option><option value="2" <?= (int)$value('mwday_woff')===2?'selected':'' ?>>Weekly Off + Public Holiday</option></select></label>
      <label id="ot-rate-field" class="text-sm font-semibold text-slate-700">OT Rate with Weekly Off<select name="otrate_woff" class="<?= $input ?>"><option value="0" <?= (int)$value('otrate_woff')===0?'selected':'' ?>>Yes</option><option value="1" <?= (int)$value('otrate_woff')===1?'selected':'' ?>>No</option></select></label>
      <label class="text-sm font-semibold text-slate-700">Attendance Allowance Days *<input name="allowance_day" type="number" min="0" max="31" step="0.01" required value="<?= h((string)$value('allowance_day',0)) ?>" class="<?= $input ?>"></label>
      <label class="manual-maximum text-sm font-semibold text-slate-700">Maximum Working Days<input name="max_working_days" id="max-working-days" type="number" min="0" max="31" value="<?= h((string)$value('max_working_days',0)) ?>" class="<?= $input ?>"></label>
      <label class="text-sm font-semibold text-slate-700">Minimum Working Days<input name="min_working_days" type="number" min="0" max="31" value="<?= h((string)$value('min_working_days',0)) ?>" class="<?= $input ?>"></label>
      <label class="manual-maximum text-sm font-semibold text-slate-700">Maximum Working Hours<input name="max_working_hrs" type="number" min="0" max="744" value="<?= h((string)$value('max_working_hrs',0)) ?>" class="<?= $input ?>"></label>
      <label class="text-sm font-semibold text-slate-700">Minimum Working Hours<input name="min_working_hrs" type="number" min="0" max="744" value="<?= h((string)$value('min_working_hrs',0)) ?>" class="<?= $input ?>"></label>
    </div>
  </section>
  <div class="flex flex-wrap justify-end gap-2"><a href="/attendance/calendar-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 form=document.getElementById('calendar-form'),salary=document.getElementById('salary-type'),ot=document.getElementById('ot-rate-field'),mode=document.getElementById('max-days-mode'),manual=[...document.querySelectorAll('.manual-maximum')],calc=document.getElementById('days-calculation'),maxDays=document.getElementById('max-working-days'),total=document.getElementById('total-month-days'),picker=document.getElementById('payroll-picker'),toggle=document.getElementById('payroll-picker-toggle'),panel=document.getElementById('payroll-picker-panel'),search=document.getElementById('payroll-picker-search'),summary=document.getElementById('payroll-picker-summary'),options=[...document.querySelectorAll('.payroll-option')],empty=document.getElementById('payroll-picker-empty');const syncSalary=()=>ot.classList.toggle('hidden',salary.value!=='1');const syncMode=()=>manual.forEach(el=>el.classList.toggle('hidden',mode.value!=='0'));const syncCalc=()=>{if(calc.value==='1'&&mode.value==='0')maxDays.value='30';else if(calc.value==='0'&&mode.value==='0'&&!maxDays.value&&total.value)maxDays.value=total.value;};const syncPayroll=()=>{const checked=options.filter(o=>o.querySelector('input').checked);summary.classList.remove('text-red-600');summary.textContent=checked.length===0?'Select payroll locations':checked.length===1?checked[0].querySelector('span').textContent:checked.length+' payroll locations selected';summary.classList.toggle('text-slate-500',checked.length===0);};salary.addEventListener('change',syncSalary);mode.addEventListener('change',()=>{syncMode();syncCalc();});calc.addEventListener('change',syncCalc);total.addEventListener('input',syncCalc);toggle.addEventListener('click',()=>{panel.classList.toggle('hidden');if(!panel.classList.contains('hidden'))search.focus();});search.addEventListener('input',()=>{const term=search.value.trim().toLowerCase();let visible=0;options.forEach(option=>{const show=option.dataset.name.includes(term);option.classList.toggle('hidden',!show);if(show)visible++;});empty.classList.toggle('hidden',visible!==0);});options.forEach(option=>option.querySelector('input').addEventListener('change',syncPayroll));document.addEventListener('click',event=>{if(!picker.contains(event.target))panel.classList.add('hidden');});form.addEventListener('submit',event=>{if(!options.some(option=>option.querySelector('input').checked)){event.preventDefault();panel.classList.remove('hidden');summary.textContent='Select at least one payroll location';summary.classList.add('text-red-600');toggle.focus();}});syncSalary();syncMode();syncPayroll();})();</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">Calendar Configuration List</h2><p class="mt-1 text-xs font-medium text-slate-400">Manage monthly attendance and weekly-off rules.</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="salary_type" class="rounded-xl border border-slate-200 px-3 py-2.5 text-sm"><option value="0">All Salary Types</option><?php foreach($salaryTypes as $option): ?><option value="<?= (int)$option['id'] ?>" <?= $filterSalary===(int)$option['id']?'selected':'' ?>><?= h($option['name']) ?></option><?php endforeach; ?></select><select name="month" class="rounded-xl border border-slate-200 px-3 py-2.5 text-sm"><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="rounded-xl border border-slate-200 px-3 py-2.5 text-sm"><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="org" class="rounded-xl border border-slate-200 px-3 py-2.5 text-sm"><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><div class="flex gap-2"><button class="flex-1 rounded-xl bg-slate-900 px-4 py-2.5 text-sm font-bold text-white"><i class="fa-solid fa-filter mr-2"></i>Filter</button><a href="/attendance/calendar-configuration.php" class="rounded-xl border border-slate-200 px-4 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-[1200px] text-left text-sm"><thead class="bg-slate-50 text-[10px] uppercase tracking-wider text-slate-400"><tr><th class="px-5 py-4">Period</th><th class="px-5 py-4">Salary Type</th><th class="px-5 py-4">Payroll Locations</th><th class="px-5 py-4">Month Days</th><th class="px-5 py-4">Maximum</th><th class="px-5 py-4">Minimum</th><th class="px-5 py-4">Allowance</th><th class="px-5 py-4">Calculation</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="9" class="px-6 py-14 text-center font-semibold text-slate-400">No calendar configurations found.</td></tr><?php endif; ?>
  <?php foreach($rows as $row): $orgNames=[];foreach(cc_ids(explode(',',(string)$row['org'])) as $orgId)if(isset($payrollMap[$orgId]))$orgNames[]=$payrollMap[$orgId]; ?>
  <tr class="hover:bg-slate-50/70"><td class="px-5 py-4"><div class="font-bold text-slate-800"><?= h($monthMap[(int)$row['month']]??'Unknown') ?> <?= h($yearMap[(int)$row['year']]??(string)$row['year']) ?></div><div class="text-xs text-slate-400">Configuration #<?= (int)$row['id'] ?></div></td><td class="px-5 py-4 font-semibold text-slate-700"><?= h($salaryMap[(int)$row['salary_type']]??'Unknown') ?></td><td class="px-5 py-4"><div class="flex max-w-xs flex-wrap gap-1"><?php foreach($orgNames as $name): ?><span class="rounded-md bg-blue-50 px-2 py-1 text-[10px] font-bold text-blue-700"><?= h($name) ?></span><?php endforeach; ?></div></td><td class="px-5 py-4 font-bold text-slate-700"><?= (int)$row['total_month_days'] ?></td><td class="px-5 py-4"><?php if((int)$row['mwday_woff']===1): ?><span class="font-semibold text-violet-700">Weekly Off</span><?php elseif((int)$row['mwday_woff']===2): ?><span class="font-semibold text-violet-700">Weekly Off + PH</span><?php else: ?><div class="font-semibold">Days <?= (int)$row['max_working_days'] ?></div><div class="text-xs text-slate-400">Hours <?= (int)$row['max_working_hrs'] ?></div><?php endif; ?></td><td class="px-5 py-4"><div class="font-semibold">Days <?= (int)$row['min_working_days'] ?></div><div class="text-xs text-slate-400">Hours <?= (int)$row['min_working_hrs'] ?></div></td><td class="px-5 py-4 font-semibold"><?= h((string)$row['allowance_day']) ?> days</td><td class="px-5 py-4"><div class="font-semibold"><?= (int)$row['days_calculation']===1?'Fixed 30 Days':'Regular' ?></div><?php if((int)$row['salary_type']===1): ?><div class="text-xs text-slate-400">Weekly-off OT: <?= (int)$row['otrate_woff']===1?'No':'Yes' ?></div><?php endif; ?></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"><i class="fa-solid fa-pen"></i></a><?php endif; ?><?php if(!empty($acl['can_delete'])): ?><form method="post" onsubmit="return confirm('Delete this calendar configuration?');"><input type="hidden" name="_csrf" value="<?= h(csrf_token()) ?>"><input type="hidden" name="action" value="delete"><input type="hidden" name="id" value="<?= (int)$row['id'] ?>"><button class="rounded-lg border border-red-100 px-3 py-2 text-red-500 hover:bg-red-50"><i class="fa-solid fa-trash"></i></button></form><?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 if($page>1): ?><a class="rounded-lg border border-slate-200 px-4 py-2 font-semibold" href="?<?= h(http_build_query(['salary_type'=>$filterSalary,'month'=>$filterMonth,'year'=>$filterYear,'org'=>$filterOrg,'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(['salary_type'=>$filterSalary,'month'=>$filterMonth,'year'=>$filterYear,'org'=>$filterOrg,'page'=>$page+1])) ?>">Next</a><?php endif; ?></div></div><?php endif; ?>
</section>
<?php endif; ?>
<?php console_footer(); ?>
