<?php
/* ============================================================================
 *  company/staff_attendance.php
 *  Phase A3 — Assign each staff a default shift + branch, mark exempt
 *  (no check-in) and off-site (no GPS) staff, and manage a date roster.
 *  Bilingual EN/Lao · Flatpickr · dd/mm/yyyy.
 * ==========================================================================*/
session_start();

if (!isset($_SESSION["user_id"]) || $_SESSION["role"] !== "company_admin") {
    header("Location: ../auth/login.php");
    exit;
}

require_once '../config/database.php';

$companyId   = (int)$_SESSION["company_id"];
$companyName = $_SESSION["company_name"] ?? "My Company";

/* ── Handle POST (PRG) ── */
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $action = $_POST["action"] ?? '';
    try {
        if ($action === "save_assignments") {
            $ids = array_map('intval', (array)($_POST["ids"] ?? []));
            $up = $pdo->prepare("
                INSERT INTO att_staff
                    (company_id, staff_id, default_shift_id, default_branch_id, checkin_required, geofence_required)
                VALUES (?,?,?,?,?,?)
                ON DUPLICATE KEY UPDATE
                    default_shift_id  = VALUES(default_shift_id),
                    default_branch_id = VALUES(default_branch_id),
                    checkin_required  = VALUES(checkin_required),
                    geofence_required = VALUES(geofence_required)
            ");
            foreach ($ids as $sid) {
                $shift  = ($_POST["shift"][$sid]  ?? '') !== '' ? (int)$_POST["shift"][$sid]  : null;
                $branch = ($_POST["branch"][$sid] ?? '') !== '' ? (int)$_POST["branch"][$sid] : null;
                $checkin = isset($_POST["checkin"][$sid]) ? 1 : 0;   // checked = needs check-in
                $geo     = isset($_POST["geo"][$sid])     ? 1 : 0;   // checked = on-site GPS required
                $up->execute([$companyId, $sid, $shift, $branch, $checkin, $geo]);
            }
            $_SESSION["sa_flash"] = ["ok", "Staff assignments saved.", "ບັນທຶກການມອບໝາຍແລ້ວ."];
        }
        elseif ($action === "add_roster") {
            $sid    = (int)($_POST["r_staff"] ?? 0);
            $date   = trim($_POST["r_date"] ?? '');
            $shift  = ($_POST["r_shift"]  ?? '') !== '' ? (int)$_POST["r_shift"]  : null;
            $branch = ($_POST["r_branch"] ?? '') !== '' ? (int)$_POST["r_branch"] : null;
            if (!$sid || !preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) throw new Exception("Pick a staff member and a date.");
            $pdo->prepare("
                INSERT INTO att_roster (company_id, staff_id, work_date, shift_id, branch_id)
                VALUES (?,?,?,?,?)
                ON DUPLICATE KEY UPDATE shift_id=VALUES(shift_id), branch_id=VALUES(branch_id)
            ")->execute([$companyId, $sid, $date, $shift, $branch]);
            $_SESSION["sa_flash"] = ["ok", "Roster entry saved.", "ບັນທຶກຕາຕະລາງວຽກແລ້ວ."];
        }
        elseif ($action === "del_roster") {
            $pdo->prepare("DELETE FROM att_roster WHERE id=? AND company_id=?")
                ->execute([(int)($_POST["roster_id"] ?? 0), $companyId]);
            $_SESSION["sa_flash"] = ["ok", "Roster entry removed.", "ລຶບຕາຕະລາງວຽກແລ້ວ."];
        }
    } catch (Throwable $e) {
        $_SESSION["sa_flash"] = ["err", "Error: ".$e->getMessage(), "ຜິດພາດ: ".$e->getMessage()];
    }
    header("Location: staff_attendance.php");
    exit;
}

/* ── Load ── */
$staff = $pdo->prepare("
    SELECT u.id, u.name, cs.position, cs.department
    FROM company_staff cs JOIN users u ON u.id = cs.user_id
    WHERE cs.company_id = ? AND u.status = 'active'
    ORDER BY u.name
");
$staff->execute([$companyId]);
$staff = $staff->fetchAll(PDO::FETCH_ASSOC);

$shifts = $pdo->prepare("SELECT id,name,start_time,end_time FROM att_shifts WHERE company_id=? AND is_active=1 ORDER BY start_time");
$shifts->execute([$companyId]);
$shifts = $shifts->fetchAll(PDO::FETCH_ASSOC);

$branches = $pdo->prepare("SELECT id,name FROM att_branches WHERE company_id=? AND is_active=1 ORDER BY name");
$branches->execute([$companyId]);
$branches = $branches->fetchAll(PDO::FETCH_ASSOC);

$as = $pdo->prepare("SELECT * FROM att_staff WHERE company_id=?");
$as->execute([$companyId]);
$assign = [];
foreach ($as->fetchAll(PDO::FETCH_ASSOC) as $r) $assign[(int)$r['staff_id']] = $r;

$roster = $pdo->prepare("
    SELECT r.*, u.name AS staff_name, s.name AS shift_name, b.name AS branch_name
    FROM att_roster r
    JOIN users u ON u.id = r.staff_id
    LEFT JOIN att_shifts   s ON s.id = r.shift_id
    LEFT JOIN att_branches b ON b.id = r.branch_id
    WHERE r.company_id = ? AND r.work_date >= CURDATE()
    ORDER BY r.work_date, u.name
    LIMIT 100
");
$roster->execute([$companyId]);
$roster = $roster->fetchAll(PDO::FETCH_ASSOC);

$flash = $_SESSION["sa_flash"] ?? null;
unset($_SESSION["sa_flash"]);

function shiftLabel($s){ return htmlspecialchars($s['name'].' ('.substr($s['start_time'],0,5).'–'.substr($s['end_time'],0,5).')'); }
?>
<!DOCTYPE html>
<html lang="lo">
<head>
    <?php $pwaTheme = '#0f766e'; include __DIR__ . '/../config/pwa_head.php'; ?>
    <title><?= htmlspecialchars($companyName) ?> — Staff Attendance Assignments</title>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Lao:wght@400;500;600;700;800&family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/flatpickr/4.6.13/flatpickr.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/flatpickr/4.6.13/flatpickr.min.js"></script>
    <script src="../assets/lang.js" defer></script>
    <style>
        *,*::before,*::after{box-sizing:border-box;margin:0;padding:0;}
        :root{--primary:#0f766e;--primary-dk:#084740;--green:#16a34a;--green-lt:#dcfce7;
            --amber:#d97706;--amber-lt:#fef3c7;--red:#dc2626;--red-lt:#fee2e2;
            --blue:#2563eb;--blue-lt:#dbeafe;--surface:#fff;--bg:#f0f4f8;
            --border:#e2e8f0;--text:#0f172a;--muted:#64748b;--radius:16px;--shadow:0 2px 14px rgba(15,23,42,.09);}
        body{font-family:"Noto Sans Lao","Inter",Arial,sans-serif;background:var(--bg);color:var(--text);min-height:100vh;}
        .top-bar{background:var(--surface);border-bottom:1px solid var(--border);padding:12px 24px;
            display:flex;justify-content:space-between;align-items:center;gap:16px;position:sticky;top:0;z-index:100;
            box-shadow:0 1px 6px rgba(15,23,42,.06);flex-wrap:wrap;}
        .brand{display:flex;align-items:center;gap:10px;}
        .brand-logo{width:34px;height:34px;background:linear-gradient(135deg,#084740,#0f766e);border-radius:9px;
            display:flex;align-items:center;justify-content:center;color:#fff;font-weight:800;font-size:14px;}
        .brand-name{font-size:14px;font-weight:700;}
        .brand-sub{font-size:11px;color:var(--muted);}
        .top-right{display:flex;align-items:center;gap:12px;}
        .lang-bar{display:flex;align-items:center;gap:6px;margin:0;}
        .lang-label{font-size:12px;color:var(--muted);font-weight:500;}
        .lang-btn{display:inline-flex;align-items:center;gap:4px;padding:4px 11px;border-radius:999px;
            border:1.5px solid var(--border);background:var(--surface);font-size:11px;font-weight:700;color:var(--muted);cursor:pointer;font-family:inherit;}
        .lang-btn.active{background:var(--primary);border-color:var(--primary);color:#fff;}
        .back-link{display:inline-flex;align-items:center;gap:5px;background:#f1f5f9;color:var(--text);
            border:1.5px solid var(--border);padding:6px 13px;border-radius:8px;text-decoration:none;font-size:12px;font-weight:700;}
        .page{padding:24px;max-width:1100px;margin:auto;}
        .hero{background:linear-gradient(135deg,#042f2e,#0f766e);border-radius:18px;padding:24px 28px;margin-bottom:22px;color:#fff;}
        .hero h1{font-size:23px;font-weight:800;margin-bottom:4px;}
        .hero p{font-size:13px;color:rgba(255,255,255,.8);}
        .card{background:var(--surface);border-radius:var(--radius);padding:22px 24px;box-shadow:var(--shadow);
            border:1px solid var(--border);margin-bottom:22px;}
        .card-head{display:flex;align-items:center;gap:10px;margin-bottom:6px;}
        .card-head .ic{width:40px;height:40px;border-radius:11px;display:flex;align-items:center;justify-content:center;font-size:20px;}
        .ic.teal{background:#ccfbf1;}.ic.blue{background:var(--blue-lt);}
        .card h2{font-size:17px;font-weight:800;}
        .card .hint{font-size:12px;color:var(--muted);margin-bottom:16px;line-height:1.5;}
        table{width:100%;border-collapse:collapse;font-size:13px;}
        th{text-align:left;font-size:11px;text-transform:uppercase;letter-spacing:.4px;color:var(--muted);
            padding:8px 10px;border-bottom:2px solid var(--border);}
        td{padding:9px 10px;border-bottom:1px solid var(--border);vertical-align:middle;}
        tr:last-child td{border-bottom:none;}
        .empty{color:var(--muted);font-size:13px;padding:14px 4px;}
        select,input[type=text]{width:100%;padding:8px 10px;border:1.5px solid var(--border);border-radius:8px;
            font-size:13px;font-family:inherit;background:#fff;min-width:120px;}
        select:focus,input:focus{outline:none;border-color:var(--primary);}
        .tick{display:flex;justify-content:center;}
        .tick input{width:18px;height:18px;cursor:pointer;}
        .staffname{font-weight:700;}
        .staffsub{font-size:11px;color:var(--muted);}
        .btn{padding:10px 16px;border-radius:9px;border:none;font-size:13px;font-weight:700;cursor:pointer;
            font-family:inherit;text-decoration:none;display:inline-flex;align-items:center;gap:6px;}
        .btn-primary{background:var(--primary);color:#fff;}
        .btn-del{background:var(--red-lt);color:var(--red);border:1.5px solid #fca5a5;padding:6px 11px;font-size:12px;}
        .form-actions{display:flex;gap:10px;margin-top:18px;flex-wrap:wrap;}
        .flash{padding:12px 16px;border-radius:10px;margin-bottom:18px;font-size:14px;font-weight:600;}
        .flash.ok{background:var(--green-lt);color:#15803d;}
        .flash.err{background:var(--red-lt);color:var(--red);}
        .legend{font-size:12px;color:var(--muted);margin-top:12px;line-height:1.7;}
        .legend b{color:var(--text);}
        .roster-add{display:flex;gap:12px;flex-wrap:wrap;align-items:flex-end;margin-bottom:18px;}
        .rg{flex:1;min-width:150px;}
        .rg label{display:block;font-size:12px;font-weight:700;color:#374151;margin-bottom:5px;}
        .warn{background:var(--amber-lt);color:#92400e;border-radius:10px;padding:12px 14px;font-size:13px;margin-bottom:16px;}
        @media(max-width:720px){.page{padding:14px;}.top-bar{padding:10px 14px;}.card{padding:16px 12px;}
            td,th{padding:7px 6px;}.tbl-wrap{overflow-x:auto;} table{min-width:680px;}}
    </style>
</head>
<body>

<div class="top-bar">
    <div class="brand">
        <div class="brand-logo">CO</div>
        <div>
            <div class="brand-name"><?= htmlspecialchars($companyName) ?></div>
            <div class="brand-sub" data-lo="ມອບໝາຍການເຂົ້າວຽກ" data-en="Attendance Assignments">ມອບໝາຍການເຂົ້າວຽກ</div>
        </div>
    </div>
    <div class="top-right">
        <div class="lang-bar">
            <span class="lang-label">ພາສາ:</span>
            <button class="lang-btn" id="btn-lo" onclick="setLang('lo')">🇱🇦 ລາວ</button>
            <button class="lang-btn" id="btn-en" onclick="setLang('en')">🇬🇧 EN</button>
        </div>
        <a class="back-link" href="dashboard.php">← <span data-lo="ກັບຄືນ" data-en="Back">ກັບຄືນ</span></a>
    </div>
</div>

<div class="page">

    <div class="hero">
        <h1 data-lo="ມອບໝາຍກະ ແລະ ສາຂາ ໃຫ້ພະນັກງານ" data-en="Assign Shifts & Branches to Staff">ມອບໝາຍກະ ແລະ ສາຂາ</h1>
        <p data-lo="ກຳນົດກະເລີ່ມຕົ້ນ, ສາຂາ ແລະ ໝາຍຄົນທີ່ບໍ່ຕ້ອງລົງເວລາ ຫຼື ລົງນອກສະຖານທີ່ໄດ້."
           data-en="Set each person's default shift and branch, and mark who is exempt from check-in or may check in off-site.">
           Set each person's default shift and branch.
        </p>
    </div>

    <?php if ($flash): ?>
        <div class="flash <?= $flash[0]==='ok'?'ok':'err' ?>" data-en="<?= htmlspecialchars($flash[1]) ?>" data-lo="<?= htmlspecialchars($flash[2]) ?>"><?= htmlspecialchars($flash[2]) ?></div>
    <?php endif; ?>

    <?php if (!$shifts || !$branches): ?>
        <div class="warn" data-lo="⚠️ ກະລຸນາສ້າງ ກະວຽກ ແລະ ສາຂາ ກ່ອນ ທີ່ໜ້າ ‘ຕັ້ງຄ່າການເຂົ້າວຽກ’."
             data-en="⚠️ Please create at least one shift and one branch first on the ‘Attendance Settings’ page.">
            ⚠️ Please create shifts and branches first on the Attendance Settings page.
        </div>
    <?php endif; ?>

    <!-- ════════ STAFF ASSIGNMENTS ════════ -->
    <div class="card">
        <div class="card-head">
            <div class="ic teal">👥</div>
            <h2 data-lo="ການມອບໝາຍພະນັກງານ" data-en="Staff Assignments">ການມອບໝາຍພະນັກງານ</h2>
        </div>
        <div class="hint" data-lo="ເລືອກກະ ແລະ ສາຂາ ສຳລັບແຕ່ລະຄົນ. ປິດ ‘ຕ້ອງລົງເວລາ’ ສຳລັບເຈົ້ານາຍ/ພະນັກງານພິເສດ. ປິດ ‘ຕ້ອງຢູ່ສະຖານທີ່ (GPS)’ ສຳລັບຄົນຂັບ/ຝ່າຍຂາຍທີ່ລົງນອກສະຖານທີ່ໄດ້."
             data-en="Pick a shift and branch per person. Turn OFF ‘Needs check-in’ for bosses/special staff. Turn OFF ‘On-site (GPS)’ for drivers/sales who may check in off-site.">
            Pick a shift and branch per person.
        </div>

        <form method="POST">
            <input type="hidden" name="action" value="save_assignments">
            <div class="tbl-wrap">
            <table>
                <thead><tr>
                    <th data-lo="ພະນັກງານ" data-en="Staff">Staff</th>
                    <th data-lo="ກະເລີ່ມຕົ້ນ" data-en="Default shift">Default shift</th>
                    <th data-lo="ສາຂາ" data-en="Branch">Branch</th>
                    <th style="text-align:center" data-lo="ຕ້ອງລົງເວລາ" data-en="Needs check-in">Needs check-in</th>
                    <th style="text-align:center" data-lo="ຢູ່ສະຖານທີ່ (GPS)" data-en="On-site (GPS)">On-site (GPS)</th>
                </tr></thead>
                <tbody>
                <?php if (!$staff): ?>
                    <tr><td colspan="5" class="empty" data-lo="ຍັງບໍ່ມີພະນັກງານ." data-en="No staff yet.">No staff yet.</td></tr>
                <?php else: foreach ($staff as $p):
                    $sid = (int)$p['id'];
                    $a   = $assign[$sid] ?? null;
                    $selShift  = $a['default_shift_id']  ?? '';
                    $selBranch = $a['default_branch_id'] ?? '';
                    $needChk = $a ? (int)$a['checkin_required']  : 1;   // default ON
                    $needGeo = $a ? (int)$a['geofence_required'] : 1;   // default ON
                ?>
                    <tr>
                        <td>
                            <input type="hidden" name="ids[]" value="<?= $sid ?>">
                            <div class="staffname"><?= htmlspecialchars($p['name']) ?></div>
                            <?php if ($p['position'] || $p['department']): ?>
                            <div class="staffsub"><?= htmlspecialchars(trim(($p['position']??'').' · '.($p['department']??''), ' ·')) ?></div>
                            <?php endif; ?>
                        </td>
                        <td>
                            <select name="shift[<?= $sid ?>]">
                                <option value="" data-lo="— ບໍ່ກຳນົດ —" data-en="— none —">— none —</option>
                                <?php foreach ($shifts as $s): ?>
                                    <option value="<?= (int)$s['id'] ?>" <?= ($selShift==$s['id'])?'selected':'' ?>><?= shiftLabel($s) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </td>
                        <td>
                            <select name="branch[<?= $sid ?>]">
                                <option value="" data-lo="— ບໍ່ກຳນົດ —" data-en="— none —">— none —</option>
                                <?php foreach ($branches as $b): ?>
                                    <option value="<?= (int)$b['id'] ?>" <?= ($selBranch==$b['id'])?'selected':'' ?>><?= htmlspecialchars($b['name']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </td>
                        <td><div class="tick"><input type="checkbox" name="checkin[<?= $sid ?>]" <?= $needChk?'checked':'' ?>></div></td>
                        <td><div class="tick"><input type="checkbox" name="geo[<?= $sid ?>]" <?= $needGeo?'checked':'' ?>></div></td>
                    </tr>
                <?php endforeach; endif; ?>
                </tbody>
            </table>
            </div>

            <div class="legend">
                <span data-lo="<b>ຕ້ອງລົງເວລາ</b> ປິດ = ເຈົ້ານາຍ/ພະນັກງານພິເສດ (ບໍ່ຕ້ອງລົງເຂົ້າ-ອອກ)."
                      data-en="<b>Needs check-in</b> off = boss / special staff (no check-in required).">
                    <b>Needs check-in</b> off = boss / special staff.
                </span><br>
                <span data-lo="<b>ຢູ່ສະຖານທີ່ (GPS)</b> ປິດ = ລົງເວລາຈາກບ່ອນໃດກໍໄດ້ (ຄົນຂັບ/ຝ່າຍຂາຍ)."
                      data-en="<b>On-site (GPS)</b> off = may check in from anywhere (drivers / sales)."><b>On-site (GPS)</b> off = may check in from anywhere.</span>
            </div>

            <?php if ($staff): ?>
            <div class="form-actions">
                <button type="submit" class="btn btn-primary" data-lo="💾 ບັນທຶກການມອບໝາຍ" data-en="💾 Save Assignments">💾 Save Assignments</button>
            </div>
            <?php endif; ?>
        </form>
    </div>

    <!-- ════════ ROSTER (date overrides) ════════ -->
    <div class="card">
        <div class="card-head">
            <div class="ic blue">📅</div>
            <h2 data-lo="ຕາຕະລາງວຽກ (ປ່ຽນກະຕາມວັນ)" data-en="Roster (per-date shift override)">ຕາຕະລາງວຽກ</h2>
        </div>
        <div class="hint" data-lo="ໃຊ້ສຳລັບກະໝູນວຽນ — ກຳນົດກະ/ສາຂາ ສະເພາະວັນ. ຖ້າບໍ່ກຳນົດ ລະບົບໃຊ້ກະເລີ່ມຕົ້ນຂ້າງເທິງ."
             data-en="For rotating schedules — set a shift/branch for a specific date. If none, the default above is used.">
            For rotating schedules — set a shift/branch for a specific date.
        </div>

        <form method="POST" class="roster-add">
            <input type="hidden" name="action" value="add_roster">
            <div class="rg">
                <label data-lo="ພະນັກງານ" data-en="Staff">Staff</label>
                <select name="r_staff" required>
                    <option value="" data-lo="— ເລືອກ —" data-en="— select —">— select —</option>
                    <?php foreach ($staff as $p): ?>
                        <option value="<?= (int)$p['id'] ?>"><?= htmlspecialchars($p['name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="rg">
                <label data-lo="ວັນທີ (ວ/ດ/ປ)" data-en="Date (dd/mm/yyyy)">Date (dd/mm/yyyy)</label>
                <input type="text" id="r_date_disp" placeholder="dd/mm/yyyy" autocomplete="off">
                <input type="hidden" name="r_date" id="r_date">
            </div>
            <div class="rg">
                <label data-lo="ກະ" data-en="Shift">Shift</label>
                <select name="r_shift">
                    <option value="" data-lo="— ບໍ່ກຳນົດ —" data-en="— none —">— none —</option>
                    <?php foreach ($shifts as $s): ?>
                        <option value="<?= (int)$s['id'] ?>"><?= shiftLabel($s) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="rg">
                <label data-lo="ສາຂາ" data-en="Branch">Branch</label>
                <select name="r_branch">
                    <option value="" data-lo="— ບໍ່ກຳນົດ —" data-en="— none —">— none —</option>
                    <?php foreach ($branches as $b): ?>
                        <option value="<?= (int)$b['id'] ?>"><?= htmlspecialchars($b['name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="rg" style="flex:0;min-width:auto;">
                <button type="submit" class="btn btn-primary" data-lo="➕ ເພີ່ມ" data-en="➕ Add">➕ Add</button>
            </div>
        </form>

        <div class="tbl-wrap">
        <table>
            <thead><tr>
                <th data-lo="ວັນທີ" data-en="Date">Date</th>
                <th data-lo="ພະນັກງານ" data-en="Staff">Staff</th>
                <th data-lo="ກະ" data-en="Shift">Shift</th>
                <th data-lo="ສາຂາ" data-en="Branch">Branch</th>
                <th></th>
            </tr></thead>
            <tbody>
            <?php if (!$roster): ?>
                <tr><td colspan="5" class="empty" data-lo="ບໍ່ມີຕາຕະລາງວຽກລ່ວງໜ້າ." data-en="No upcoming roster entries.">No upcoming roster entries.</td></tr>
            <?php else: foreach ($roster as $r): ?>
                <tr>
                    <td><strong><?= date('d/m/Y', strtotime($r['work_date'])) ?></strong></td>
                    <td><?= htmlspecialchars($r['staff_name']) ?></td>
                    <td><?= $r['shift_name']  ? htmlspecialchars($r['shift_name'])  : '<span class="empty">—</span>' ?></td>
                    <td><?= $r['branch_name'] ? htmlspecialchars($r['branch_name']) : '<span class="empty">—</span>' ?></td>
                    <td style="text-align:right">
                        <form method="POST" style="display:inline" onsubmit="return confirm('Remove this roster entry?')">
                            <input type="hidden" name="action" value="del_roster">
                            <input type="hidden" name="roster_id" value="<?= (int)$r['id'] ?>">
                            <button class="btn btn-del" type="submit" data-lo="ລຶບ" data-en="Remove">Remove</button>
                        </form>
                    </td>
                </tr>
            <?php endforeach; endif; ?>
            </tbody>
        </table>
        </div>
    </div>

    <div style="text-align:center;color:var(--muted);font-size:12px;padding:8px 0 24px;">
        <a href="attendance_settings.php" style="color:var(--primary);font-weight:700;text-decoration:none;"
           data-lo="← ກັບໄປໜ້າຕັ້ງຄ່າ (ສາຂາ / ກະ / ກົດລະບຽບ)" data-en="← Back to settings (branches / shifts / rules)">← Back to settings</a>
    </div>

</div>

<script>
/* Flatpickr date picker — shows dd/mm/yyyy, submits yyyy-mm-dd */
document.addEventListener("DOMContentLoaded", function(){
    if (typeof flatpickr === "undefined") return;
    const disp = document.getElementById("r_date_disp");
    const hid  = document.getElementById("r_date");
    if (disp) {
        flatpickr(disp, {
            dateFormat: "d/m/Y",
            minDate: "today",
            onChange: function(sel, str, fp){
                hid.value = sel[0] ? fp.formatDate(sel[0], "Y-m-d") : "";
            }
        });
    }
});
</script>

<?php require __DIR__ . '/../config/auto_update.php'; ?>
</body>
</html>