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

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

$pageLink = 'attendance/salary-custom-interval.php';
$acl = require_acl('can_view', $pageLink);
$errors = [];
$flash = $_SESSION['flash_salary_custom_interval'] ?? null;
unset($_SESSION['flash_salary_custom_interval']);

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

function sci_date(string $value): ?DateTimeImmutable
{
    $value = trim($value);
    foreach (['!Y-m-d' => 'Y-m-d', '!d-m-Y' => 'd-m-Y', '!d/m/Y' => 'd/m/Y'] as $format => $checkFormat) {
        $date = DateTimeImmutable::createFromFormat($format, $value);
        if ($date && $date->format($checkFormat) === $value) return $date;
    }
    return null;
}

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

if ($editId > 0) {
    $stmt = sci_stmt($con, 'SELECT id,fromdate,todate,total_month_days FROM jos_app_calender_customintervals WHERE id=? LIMIT 1');
    $stmt->bind_param('i', $editId);
    $stmt->execute();
    $editRow = $stmt->get_result()->fetch_assoc() ?: null;
    $stmt->close();
    if (!$editRow) {
        $_SESSION['flash_salary_custom_interval'] = 'Salary custom interval was not found.';
        redirect('/attendance/salary-custom-interval.php');
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = (string)($_POST['action'] ?? '');
    if (!verify_csrf($_POST['_csrf'] ?? null)) {
        $errors[] = 'Security token expired. Please refresh and try again.';
    } elseif ($action === 'save') {
        $id = max(0, (int)($_POST['id'] ?? 0));
        if ($id > 0 && empty($acl['can_edit'])) $errors[] = 'You do not have permission to edit salary custom intervals.';
        if ($id === 0 && empty($acl['can_add'])) $errors[] = 'You do not have permission to add salary custom intervals.';
        if ($id > 0 && !$errors) {
            $stmt = sci_stmt($con, 'SELECT id FROM jos_app_calender_customintervals WHERE id=? LIMIT 1');
            $stmt->bind_param('i', $id);
            $stmt->execute();
            if (!$stmt->get_result()->fetch_assoc()) $errors[] = 'Salary custom interval was not found.';
            $stmt->close();
        }

        $fromDate = sci_date((string)($_POST['fromdate'] ?? ''));
        $toDate = sci_date((string)($_POST['todate'] ?? ''));
        $totalDays = 0;
        if (!$fromDate) $errors[] = 'Select a valid From Date.';
        if (!$toDate) $errors[] = 'Select a valid To Date.';
        if ($fromDate && $toDate) {
            if ($toDate < $fromDate) {
                $errors[] = 'To Date cannot be earlier than From Date.';
            } else {
                $totalDays = (int)$fromDate->diff($toDate)->days + 1;
            }
        }
        if ($totalDays > 3660) $errors[] = 'The selected interval is too large.';

        $fromValue = $fromDate ? $fromDate->format('Y-m-d') : '';
        $toValue = $toDate ? $toDate->format('Y-m-d') : '';
        if (!$errors) {
            $stmt = sci_stmt($con, 'SELECT id FROM jos_app_calender_customintervals WHERE fromdate=? AND todate=? AND id<>? LIMIT 1');
            $stmt->bind_param('ssi', $fromValue, $toValue, $id);
            $stmt->execute();
            if ($stmt->get_result()->fetch_assoc()) $errors[] = 'This exact salary interval already exists.';
            $stmt->close();
        }

        if (!$errors) {
            if ($id > 0) {
                $stmt = sci_stmt($con, 'UPDATE jos_app_calender_customintervals SET fromdate=?,todate=?,total_month_days=? WHERE id=?');
                $stmt->bind_param('ssii', $fromValue, $toValue, $totalDays, $id);
                if (!$stmt->execute()) $errors[] = 'Unable to update the salary custom interval.';
                $stmt->close();
                $message = 'Salary custom interval updated successfully.';
                $event = 'salary_custom_interval.update';
            } else {
                $stmt = sci_stmt($con, 'INSERT INTO jos_app_calender_customintervals (fromdate,todate,total_month_days) VALUES (?,?,?)');
                $stmt->bind_param('ssi', $fromValue, $toValue, $totalDays);
                if (!$stmt->execute()) $errors[] = 'Unable to add the salary custom interval.';
                $id = (int)$con->insert_id;
                $stmt->close();
                $message = 'Salary custom interval added successfully.';
                $event = 'salary_custom_interval.create';
            }
            if (!$errors) {
                audit_log($event, 'jos_app_calender_customintervals', (string)$id, $fromValue . ' to ' . $toValue);
                $_SESSION['flash_salary_custom_interval'] = $message;
                redirect('/attendance/salary-custom-interval.php');
            }
        }

        $isForm = true;
        $editId = $id;
        $editRow = ['id'=>$id,'fromdate'=>$fromValue,'todate'=>$toValue,'total_month_days'=>$totalDays];
    }
}

$filterFromRaw = trim((string)($_GET['from'] ?? ''));
$filterToRaw = trim((string)($_GET['to'] ?? ''));
$filterFrom = sci_date($filterFromRaw);
$filterTo = sci_date($filterToRaw);
$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = 20;
$totalRows = 0;
$rows = [];
$pages = 1;

if (!$isForm) {
    $where = ['1=1']; $types = ''; $params = [];
    if ($filterFrom) { $where[] = 'todate>=?'; $types .= 's'; $params[] = $filterFrom->format('Y-m-d'); }
    if ($filterTo) { $where[] = 'fromdate<=?'; $types .= 's'; $params[] = $filterTo->format('Y-m-d'); }
    $whereSql = implode(' AND ', $where);
    $stmt = sci_stmt($con, 'SELECT COUNT(*) AS total FROM jos_app_calender_customintervals 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 = sci_stmt($con, 'SELECT id,fromdate,todate,total_month_days FROM jos_app_calender_customintervals WHERE ' . $whereSql . ' ORDER BY fromdate DESC,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.5 text-sm text-slate-800 outline-none focus:border-brand-500 focus:ring-2 focus:ring-brand-100';
console_header('Salary Custom Interval', $pageLink);
?>
<link rel="stylesheet" href="/assets/css/flatpickr.min.css">
<style>
.flatpickr-calendar{border-radius:14px;border:1px solid #e2e8f0;box-shadow:0 20px 45px rgba(15,23,42,.16);font-family:inherit}
.flatpickr-day.selected,.flatpickr-day.startRange,.flatpickr-day.endRange,.flatpickr-day.selected:hover{background:#2563eb;border-color:#2563eb}
.flatpickr-day.today{border-color:#2563eb}
.flatpickr-current-month .flatpickr-monthDropdown-months,.flatpickr-current-month input.cur-year{font-weight:700;color:#1e293b}
</style>
<div class="mb-5"><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">Salary Custom Interval</span></div><h1 class="text-2xl font-bold text-slate-900">Salary Custom Interval</h1><p class="mt-1 text-sm text-slate-500">Configure inclusive custom date ranges used for salary calculations.</p></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="interval-form"><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="w-full rounded-2xl border border-slate-100 bg-white p-5 shadow-sm">
    <div class="mb-5 flex flex-wrap items-center justify-between gap-3"><div class="flex items-center gap-3"><span class="flex h-10 w-10 items-center justify-center rounded-xl bg-brand-50 text-brand-600"><i class="fa-solid fa-calendar-plus"></i></span><div><h2 class="font-bold text-slate-800"><?= (int)$value('id',0)>0?'Edit Salary Custom Interval':'Add Salary Custom Interval' ?></h2><p class="text-xs text-slate-400">Total days are calculated inclusively and cannot be edited manually.</p></div></div><a href="/attendance/salary-custom-interval.php" class="rounded-lg border border-slate-200 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-4 md:grid-cols-3"><label class="text-sm font-semibold text-slate-700">From Date *<input type="text" name="fromdate" id="from-date" required value="<?= h((string)$value('fromdate',date('Y-m-d'))) ?>" class="<?= $input ?> js-flatpickr-date" placeholder="dd-mm-yyyy" autocomplete="off"></label><label class="text-sm font-semibold text-slate-700">To Date *<input type="text" name="todate" id="to-date" required value="<?= h((string)$value('todate',date('Y-m-d'))) ?>" class="<?= $input ?> js-flatpickr-date" placeholder="dd-mm-yyyy" autocomplete="off"></label><label class="text-sm font-semibold text-slate-700">Total Days<input type="number" id="total-days" readonly value="<?= h((string)$value('total_month_days',1)) ?>" class="<?= $input ?> bg-slate-50 font-bold text-brand-700"></label></div>
    <div id="date-error" class="mt-3 hidden rounded-lg bg-red-50 px-4 py-2 text-sm font-semibold text-red-600">To Date cannot be earlier than From Date.</div>
    <div class="mt-5 flex flex-wrap justify-end gap-2"><a href="/attendance/salary-custom-interval.php" class="rounded-lg border border-slate-200 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 Interval</button></div>
  </section>
</form>
<script src="/assets/js/flatpickr.min.js"></script>
<script>(()=>{const form=document.getElementById('interval-form'),from=document.getElementById('from-date'),to=document.getElementById('to-date'),total=document.getElementById('total-days'),error=document.getElementById('date-error');const calculate=()=>{if(!from.value||!to.value){total.value='';error.classList.add('hidden');return true;}const start=new Date(from.value+'T00:00:00'),end=new Date(to.value+'T00:00:00');if(end<start){total.value='';error.classList.remove('hidden');return false;}total.value=Math.round((end-start)/86400000)+1;error.classList.add('hidden');return true;};const pickerOptions={dateFormat:'Y-m-d',altInput:true,altFormat:'d-m-Y',allowInput:true,disableMobile:true,onChange:calculate,onClose:calculate};if(window.flatpickr){document.querySelectorAll('.js-flatpickr-date').forEach(input=>flatpickr(input,pickerOptions));}from.addEventListener('change',calculate);to.addEventListener('change',calculate);form.addEventListener('submit',event=>{if(!calculate())event.preventDefault();});calculate();})();</script>
<?php else: ?>
<section class="w-full 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">Salary Custom Interval List</h2><p class="mt-1 text-xs font-medium text-slate-400">Date ranges are ordered by the latest From Date.</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-[1fr_1fr_auto]"><label class="text-sm font-semibold text-slate-600">Range From<input type="text" name="from" value="<?= h($filterFrom ? $filterFrom->format('Y-m-d') : $filterFromRaw) ?>" class="<?= $input ?> js-flatpickr-date" placeholder="dd-mm-yyyy" autocomplete="off"></label><label class="text-sm font-semibold text-slate-600">Range To<input type="text" name="to" value="<?= h($filterTo ? $filterTo->format('Y-m-d') : $filterToRaw) ?>" class="<?= $input ?> js-flatpickr-date" placeholder="dd-mm-yyyy" autocomplete="off"></label><div class="flex items-end gap-2"><button class="rounded-lg 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/salary-custom-interval.php" class="rounded-lg 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-[720px] text-left text-sm"><thead class="bg-slate-50 text-[10px] uppercase tracking-wider text-slate-400"><tr><th class="px-6 py-4 w-24">Sr No</th><th class="px-6 py-4">From Date</th><th class="px-6 py-4">To Date</th><th class="px-6 py-4">Total Days</th><th class="px-6 py-4 text-right w-36">Actions</th></tr></thead><tbody class="divide-y divide-slate-100"><?php if(!$rows): ?><tr><td colspan="5" class="px-6 py-14 text-center font-semibold text-slate-400">No salary custom intervals found.</td></tr><?php endif; ?><?php foreach($rows as $index=>$row): ?><tr class="hover:bg-slate-50/70"><td class="px-6 py-4 font-semibold text-slate-500"><?= (($page-1)*$perPage)+$index+1 ?></td><td class="px-6 py-4"><div class="font-bold text-slate-800"><?= h(date('d M Y',strtotime((string)$row['fromdate']))) ?></div><div class="text-xs text-slate-400"><?= h($row['fromdate']) ?></div></td><td class="px-6 py-4"><div class="font-bold text-slate-800"><?= h(date('d M Y',strtotime((string)$row['todate']))) ?></div><div class="text-xs text-slate-400"><?= h($row['todate']) ?></div></td><td class="px-6 py-4"><span class="rounded-full bg-brand-50 px-3 py-1 text-xs font-bold text-brand-700"><?= (int)$row['total_month_days'] ?> days</span></td><td class="px-6 py-4 text-right"><?php if(!empty($acl['can_edit'])): ?><a href="?edit=<?= (int)$row['id'] ?>" class="inline-flex 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; ?></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 ?> intervals</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(['from'=>$filterFromRaw,'to'=>$filterToRaw,'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(['from'=>$filterFromRaw,'to'=>$filterToRaw,'page'=>$page+1])) ?>">Next</a><?php endif; ?></div></div><?php endif; ?>
</section>
<script src="/assets/js/flatpickr.min.js"></script>
<script>(()=>{if(!window.flatpickr)return;document.querySelectorAll('.js-flatpickr-date').forEach(input=>flatpickr(input,{dateFormat:'Y-m-d',altInput:true,altFormat:'d-m-Y',allowInput:true,disableMobile:true}));})();</script>
<?php endif; ?>
<?php console_footer(); ?>
