<?php
/* ============================================================================
 *  company/attendance_settings.php
 *  Company admin sets up: Branches (geofence), Shifts, and Attendance Rules.
 *  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";

/* ── Helpers ── */
function clean($v){ return trim((string)($v ?? '')); }
function numOrNull($v){ $v = trim((string)$v); return ($v === '') ? null : $v; }

/* ── Handle POST (Post / Redirect / Get) ── */
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $action = $_POST["action"] ?? '';
    try {
        /* ---- Branch ---- */
        if ($action === "save_branch") {
            $id     = (int)($_POST["branch_id"] ?? 0);
            $name   = clean($_POST["name"]);
            $lat    = numOrNull($_POST["lat"]);
            $lng    = numOrNull($_POST["lng"]);
            $radius = (int)($_POST["radius_m"] ?? 150);
            $active = isset($_POST["is_active"]) ? 1 : 0;
            if ($name === "") throw new Exception("Branch name is required.");
            if ($radius < 20) $radius = 20;

            if ($id > 0) {
                $st = $pdo->prepare("UPDATE att_branches SET name=?, lat=?, lng=?, radius_m=?, is_active=?
                                     WHERE id=? AND company_id=?");
                $st->execute([$name, $lat, $lng, $radius, $active, $id, $companyId]);
            } else {
                $st = $pdo->prepare("INSERT INTO att_branches (company_id, name, lat, lng, radius_m, is_active)
                                     VALUES (?,?,?,?,?,?)");
                $st->execute([$companyId, $name, $lat, $lng, $radius, $active]);
            }
            $_SESSION["att_flash"] = ["ok", "Branch saved.", "ບັນທຶກສາຂາແລ້ວ."];
        }
        elseif ($action === "delete_branch") {
            $id = (int)($_POST["branch_id"] ?? 0);
            $st = $pdo->prepare("DELETE FROM att_branches WHERE id=? AND company_id=?");
            $st->execute([$id, $companyId]);
            $_SESSION["att_flash"] = ["ok", "Branch deleted.", "ລຶບສາຂາແລ້ວ."];
        }
        /* ---- Shift ---- */
        elseif ($action === "save_shift") {
            $id     = (int)($_POST["shift_id"] ?? 0);
            $name   = clean($_POST["name"]);
            $start  = clean($_POST["start_time"]) ?: "08:00";
            $end    = clean($_POST["end_time"])   ?: "17:00";
            $grace  = (int)($_POST["grace_minutes"] ?? 0);
            $break  = (int)($_POST["break_minutes"] ?? 0);
            $otAfter= (int)($_POST["ot_after_minutes"] ?? 0);
            $cross  = isset($_POST["crosses_midnight"]) ? 1 : 0;
            $active = isset($_POST["is_active"]) ? 1 : 0;
            $wdays  = $_POST["weekdays"] ?? [];
            $wdays  = array_values(array_filter(array_map('intval',(array)$wdays), fn($d)=>$d>=1 && $d<=7));
            sort($wdays);
            $weekdays = implode(",", $wdays);
            $dayValue = isset($_POST["half_day"]) ? 0.5 : 1.0;
            if ($name === "") throw new Exception("Shift name is required.");

            if ($id > 0) {
                $st = $pdo->prepare("UPDATE att_shifts SET name=?, start_time=?, end_time=?, grace_minutes=?,
                                     break_minutes=?, ot_after_minutes=?, crosses_midnight=?, is_active=?,
                                     weekdays=?, day_value=?
                                     WHERE id=? AND company_id=?");
                $st->execute([$name,$start,$end,$grace,$break,$otAfter,$cross,$active,$weekdays,$dayValue,$id,$companyId]);
            } else {
                $st = $pdo->prepare("INSERT INTO att_shifts
                    (company_id, name, start_time, end_time, grace_minutes, break_minutes, ot_after_minutes, crosses_midnight, is_active, weekdays, day_value)
                    VALUES (?,?,?,?,?,?,?,?,?,?,?)");
                $st->execute([$companyId,$name,$start,$end,$grace,$break,$otAfter,$cross,$active,$weekdays,$dayValue]);
            }
            $_SESSION["att_flash"] = ["ok", "Shift saved.", "ບັນທຶກກະວຽກແລ້ວ."];
        }
        elseif ($action === "delete_shift") {
            $id = (int)($_POST["shift_id"] ?? 0);
            $st = $pdo->prepare("DELETE FROM att_shifts WHERE id=? AND company_id=?");
            $st->execute([$id, $companyId]);
            $_SESSION["att_flash"] = ["ok", "Shift deleted.", "ລຶບກະວຽກແລ້ວ."];
        }
        /* ---- Rules ---- */
        elseif ($action === "save_rules") {
            /* per-day working hours grid */
            $sched = [];
            $days  = [];
            $gGrace   = (int)($_POST["sched_grace"] ?? 5);
            $gOtAfter = (int)($_POST["sched_ot_after"] ?? 0);
            for ($n = 1; $n <= 7; $n++) {
                if (!isset($_POST["day_on"][$n])) continue;
                $amS = clean($_POST["day_am_start"][$n] ?? '') ?: '08:00';
                $amE = clean($_POST["day_am_end"][$n]   ?? '') ?: '12:00';
                $pmS = clean($_POST["day_pm_start"][$n] ?? '');
                $pmE = clean($_POST["day_pm_end"][$n]   ?? '');
                $half = isset($_POST["day_half"][$n]);
                if ($half) { $pmS = ''; $pmE = ''; }      // half day = morning session only
                $sched[$n] = ['am_start'=>$amS, 'am_end'=>$amE, 'pm_start'=>$pmS, 'pm_end'=>$pmE,
                              'value'=>$half ? 0.5 : 1.0];
                $days[] = $n;
            }
            sort($days);
            $workdays = implode(",", $days);
            $extra = json_encode(['schedule'=>$sched, 'grace'=>$gGrace, 'ot_after'=>$gOtAfter], JSON_UNESCAPED_UNICODE);

            $wdpm     = (int)($_POST["working_days_per_month"] ?? 26);
            $lateType = clean($_POST["late_deduction_type"]) ?: "per_minute";
            $lateVal  = (float)($_POST["late_deduction_value"] ?? 0);
            $absBasis = clean($_POST["absence_basis"]) ?: "daily_rate";
            $otMult   = (float)($_POST["ot_multiplier"] ?? 1.50);
            $minOt    = (int)($_POST["min_ot_minutes"] ?? 30);
            $roundMin = (int)($_POST["round_minutes"] ?? 0);
            $geoDef   = isset($_POST["geofence_default"]) ? 1 : 0;
            $cycleStart = (int)($_POST["cycle_start_day"] ?? 1);
            if ($cycleStart < 1) $cycleStart = 1; if ($cycleStart > 28) $cycleStart = 28;

            $st = $pdo->prepare("UPDATE att_rules SET workdays=?, working_days_per_month=?, late_deduction_type=?,
                                 late_deduction_value=?, absence_basis=?, ot_multiplier=?, min_ot_minutes=?,
                                 round_minutes=?, geofence_default=?, cycle_start_day=?, extra=? WHERE company_id=?");
            $st->execute([$workdays,$wdpm,$lateType,$lateVal,$absBasis,$otMult,$minOt,$roundMin,$geoDef,$cycleStart,$extra,$companyId]);
            $_SESSION["att_flash"] = ["ok", "Rules saved.", "ບັນທຶກກົດລະບຽບແລ້ວ."];
        }
    } catch (Throwable $e) {
        $_SESSION["att_flash"] = ["err", "Error: ".$e->getMessage(), "ຜິດພາດ: ".$e->getMessage()];
    }
    header("Location: attendance_settings.php");
    exit;
}

/* ── Load data ── */
$branches = $pdo->prepare("SELECT * FROM att_branches WHERE company_id=? ORDER BY id");
$branches->execute([$companyId]);
$branches = $branches->fetchAll(PDO::FETCH_ASSOC);

$shifts = $pdo->prepare("SELECT * FROM att_shifts WHERE company_id=? ORDER BY start_time");
$shifts->execute([$companyId]);
$shifts = $shifts->fetchAll(PDO::FETCH_ASSOC);

$rules = $pdo->prepare("SELECT * FROM att_rules WHERE company_id=? LIMIT 1");
$rules->execute([$companyId]);
$rules = $rules->fetch(PDO::FETCH_ASSOC);
if (!$rules) {
    $pdo->prepare("INSERT IGNORE INTO att_rules (company_id) VALUES (?)")->execute([$companyId]);
    $rules = $pdo->query("SELECT * FROM att_rules WHERE company_id={$companyId} LIMIT 1")->fetch(PDO::FETCH_ASSOC);
}
$ruleDays = array_filter(array_map('intval', explode(",", (string)($rules['workdays'] ?? '1,2,3,4,5'))));
$cycleStart = (int)($rules['cycle_start_day'] ?? 1);
if ($cycleStart < 1) $cycleStart = 1;

/* per-day schedule (from extra JSON) */
$schedule = []; $schedGrace = 5; $schedOtAfter = 0;
if (!empty($rules['extra'])) {
    $ex = json_decode($rules['extra'], true);
    if (is_array($ex)) {
        if (!empty($ex['schedule']) && is_array($ex['schedule'])) {
            foreach ($ex['schedule'] as $k=>$v) $schedule[(int)$k] = $v;
        }
        if (isset($ex['grace']))    $schedGrace   = (int)$ex['grace'];
        if (isset($ex['ot_after'])) $schedOtAfter = (int)$ex['ot_after'];
    }
}
/* default schedule if none saved yet: Mon–Fri split shift 08:30–12:00 / 13:30–17:00 */
if (!$schedule) {
    foreach ($ruleDays as $d) $schedule[$d] = ['am_start'=>'08:00','am_end'=>'12:00','pm_start'=>'13:00','pm_end'=>'17:00','value'=>1.0];
}
/* migrate any old single-session entries to am/pm shape */
foreach ($schedule as $d=>$v) {
    if (!isset($v['am_start'])) {
        $schedule[$d] = ['am_start'=>$v['start'] ?? '08:00','am_end'=>'12:00',
                         'pm_start'=>'13:00','pm_end'=>$v['end'] ?? '17:00','value'=>$v['value'] ?? 1.0];
    }
}

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

$DAYS = [1=>['Mon','ຈັນ'],2=>['Tue','ອັງຄານ'],3=>['Wed','ພຸດ'],4=>['Thu','ພະຫັດ'],5=>['Fri','ສຸກ'],6=>['Sat','ເສົາ'],7=>['Sun','ອາທິດ']];
?>
<!DOCTYPE html>
<html lang="lo">
<head>
    <?php $pwaTheme = '#0f766e'; include __DIR__ . '/../config/pwa_head.php'; ?>
    <title><?= htmlspecialchars($companyName) ?> — Attendance Settings</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;}
        .day-grid{display:flex;flex-direction:column;gap:8px;}
        .day-row{display:flex;align-items:center;gap:12px;padding:9px 12px;border:1.5px solid var(--border);
            border-radius:10px;flex-wrap:wrap;transition:background .15s,border-color .15s;}
        .day-row.off{background:#f8fafc;opacity:.65;}
        .day-toggle{display:flex;align-items:center;gap:8px;min-width:120px;cursor:pointer;font-weight:700;font-size:14px;}
        .day-toggle input{width:18px;height:18px;}
        .day-name{font-weight:700;}
        .day-times{display:flex;align-items:center;gap:12px;flex-wrap:wrap;}
        .ses{display:flex;align-items:center;gap:6px;}
        .seslabel{font-size:11px;font-weight:800;color:var(--muted);text-transform:uppercase;letter-spacing:.4px;min-width:150px;text-align:center;}
        .dayhead{border:none;padding-bottom:0;}
        .dayhead .day-toggle{min-width:120px;}
        .day-time{width:74px;padding:8px 8px;border:1.5px solid var(--border);border-radius:8px;font-size:15px;font-family:inherit;text-align:center;color:var(--text);font-weight:800;background:#fff;}
        .day-time::placeholder{color:#cbd5e1;font-weight:400;}
        .day-row.off .day-time{background:#eef2f6;color:var(--muted);font-weight:600;}
        .day-row.halfday .pm-ses{opacity:.35;pointer-events:none;}
        .dash{color:var(--muted);font-weight:700;}
        .day-half{display:inline-flex;align-items:center;gap:5px;font-size:12px;font-weight:700;color:#92400e;
            background:#fef3c7;padding:5px 10px;border-radius:999px;cursor:pointer;}
        .day-half input{width:15px;height:15px;}
        .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);}.ic.amber{background:var(--amber-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;margin-bottom:16px;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: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;}
        .pill{display:inline-block;padding:2px 9px;border-radius:999px;font-size:11px;font-weight:700;}
        .pill.on{background:var(--green-lt);color:#15803d;}
        .pill.off{background:#f1f5f9;color:var(--muted);}
        .row{display:flex;gap:14px;flex-wrap:wrap;}
        .fg{margin-bottom:14px;flex:1;min-width:150px;}
        .fg label{display:block;font-size:12px;font-weight:700;color:#374151;margin-bottom:5px;}
        .fg input,.fg select{width:100%;padding:10px 12px;border:1.5px solid var(--border);border-radius:9px;
            font-size:14px;font-family:inherit;background:#fff;}
        .fg input:focus,.fg select:focus{outline:none;border-color:var(--primary);}
        .checks{display:flex;flex-wrap:wrap;gap:8px;}
        .check{display:inline-flex;align-items:center;gap:6px;padding:7px 12px;border:1.5px solid var(--border);
            border-radius:9px;font-size:13px;font-weight:600;cursor:pointer;user-select:none;}
        .check input{width:auto;}
        .switch{display:inline-flex;align-items:center;gap:8px;font-size:13px;font-weight:600;cursor:pointer;}
        .switch input{width:18px;height:18px;}
        .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-ghost{background:#f1f5f9;color:var(--text);border:1.5px solid var(--border);}
        .btn-sm{padding:6px 11px;font-size:12px;}
        .btn-del{background:var(--red-lt);color:var(--red);border:1.5px solid #fca5a5;}
        .btn-loc{background:var(--blue-lt);color:var(--blue);border:1.5px solid #bfdbfe;}
        .form-actions{display:flex;gap:10px;margin-top:6px;align-items:center;flex-wrap:wrap;}
        .form-title{font-size:13px;font-weight:800;color:var(--primary);margin:18px 0 12px;
            padding-top:16px;border-top:1px dashed var(--border);}
        .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);}
        @media(max-width:640px){.page{padding:14px;}.top-bar{padding:10px 14px;}.card{padding:18px 16px;}
            td,th{padding:7px 6px;font-size:12px;}}
    </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 Settings">ຕັ້ງຄ່າການເຂົ້າວຽກ</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="Attendance Settings">ຕັ້ງຄ່າການເຂົ້າວຽກ</h1>
        <p data-lo="ກຳນົດສາຂາ (GPS), ກະວຽກ ແລະ ກົດລະບຽບ ສຳລັບລະບົບລົງເວລາ ແລະ ຄິດໄລ່ເງິນເດືອນ."
           data-en="Set up branches (GPS), shifts, and rules that power check-in and automatic payroll.">
           ກຳນົດສາຂາ (GPS), ກະວຽກ ແລະ ກົດລະບຽບ.
        </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; ?>

    <!-- ════════ BRANCHES ════════ -->
    <div class="card">
        <div class="card-head">
            <div class="ic teal">📍</div>
            <h2 data-lo="ສາຂາ / ສະຖານທີ່ (GPS)" data-en="Branches / Locations (GPS)">ສາຂາ / ສະຖານທີ່</h2>
        </div>
        <div class="hint" data-lo="ກຳນົດສະຖານທີ່ເຮັດວຽກ ແລະ ລັດສະໝີ GPS. ພະນັກງານຕ້ອງຢູ່ໃນລັດສະໝີຈຶ່ງລົງເວລາໄດ້ (ຍົກເວັ້ນຄົນທີ່ອະນຸຍາດໃຫ້ລົງນອກສະຖານທີ່)."
             data-en="Define work locations and a GPS radius. Staff must be inside the radius to check in (unless allowed to check in off-site).">
            Define work locations and a GPS radius.
        </div>

        <table>
            <thead><tr>
                <th data-lo="ຊື່" data-en="Name">Name</th>
                <th data-lo="ພິກັດ" data-en="Coordinates">Coordinates</th>
                <th data-lo="ລັດສະໝີ" data-en="Radius">Radius</th>
                <th data-lo="ສະຖານະ" data-en="Status">Status</th>
                <th></th>
            </tr></thead>
            <tbody>
            <?php if (!$branches): ?>
                <tr><td colspan="5" class="empty" data-lo="ຍັງບໍ່ມີສາຂາ — ເພີ່ມຂ້າງລຸ່ມ." data-en="No branches yet — add one below.">No branches yet — add one below.</td></tr>
            <?php else: foreach ($branches as $b): ?>
                <tr>
                    <td><strong><?= htmlspecialchars($b['name']) ?></strong></td>
                    <td><?= ($b['lat']!==null && $b['lng']!==null) ? htmlspecialchars($b['lat'].', '.$b['lng']) : '<span class="empty">—</span>' ?></td>
                    <td><?= (int)$b['radius_m'] ?> m</td>
                    <td><?= $b['is_active'] ? '<span class="pill on" data-lo="ໃຊ້ງານ" data-en="Active">Active</span>' : '<span class="pill off" data-lo="ປິດ" data-en="Off">Off</span>' ?></td>
                    <td style="white-space:nowrap;text-align:right;">
                        <button class="btn btn-ghost btn-sm" type="button"
                            onclick='editBranch(<?= json_encode($b, JSON_UNESCAPED_UNICODE|JSON_HEX_APOS|JSON_HEX_QUOT) ?>)'
                            data-lo="ແກ້ໄຂ" data-en="Edit">Edit</button>
                        <form method="POST" style="display:inline" onsubmit="return confirm('Delete this branch?')">
                            <input type="hidden" name="action" value="delete_branch">
                            <input type="hidden" name="branch_id" value="<?= (int)$b['id'] ?>">
                            <button class="btn btn-del btn-sm" type="submit" data-lo="ລຶບ" data-en="Delete">Delete</button>
                        </form>
                    </td>
                </tr>
            <?php endforeach; endif; ?>
            </tbody>
        </table>

        <form method="POST" id="branchForm">
            <input type="hidden" name="action" value="save_branch">
            <input type="hidden" name="branch_id" id="b_id" value="0">
            <div class="form-title"><span id="b_form_label" data-lo="ເພີ່ມສາຂາ" data-en="Add Branch">Add Branch</span></div>
            <div class="row">
                <div class="fg" style="flex:2;">
                    <label data-lo="ຊື່ສາຂາ" data-en="Branch name">Branch name</label>
                    <input type="text" name="name" id="b_name" required
                        data-lo-placeholder="ເຊັ່ນ: ສຳນັກງານໃຫຍ່" data-en-placeholder="e.g. Head Office">
                </div>
                <div class="fg">
                    <label data-lo="ລັດສະໝີ (ແມັດ)" data-en="Radius (m)">Radius (m)</label>
                    <input type="number" name="radius_m" id="b_radius" value="150" min="20" step="10">
                </div>
            </div>
            <div class="row">
                <div class="fg">
                    <label>Latitude</label>
                    <input type="text" name="lat" id="b_lat" placeholder="e.g. 17.9667">
                </div>
                <div class="fg">
                    <label>Longitude</label>
                    <input type="text" name="lng" id="b_lng" placeholder="e.g. 102.6000">
                </div>
                <div class="fg" style="flex:0;display:flex;align-items:flex-end;min-width:auto;">
                    <button type="button" class="btn btn-loc" onclick="useMyLocation()"
                        data-lo="📡 ໃຊ້ຕຳແໜ່ງປັດຈຸບັນ" data-en="📡 Use my location">📡 Use my location</button>
                </div>
            </div>
            <label class="switch" style="margin-bottom:8px;">
                <input type="checkbox" name="is_active" id="b_active" checked>
                <span data-lo="ໃຊ້ງານ" data-en="Active">Active</span>
            </label>
            <div class="form-actions">
                <button type="submit" class="btn btn-primary" data-lo="💾 ບັນທຶກສາຂາ" data-en="💾 Save Branch">💾 Save Branch</button>
                <button type="button" class="btn btn-ghost" onclick="resetBranch()" data-lo="ລ້າງ" data-en="Clear">Clear</button>
            </div>
        </form>
    </div>

    <!-- ════════ SHIFTS ════════ -->
    <div class="card">
        <div class="card-head">
            <div class="ic blue">🕐</div>
            <h2 data-lo="ກະວຽກ" data-en="Shifts">ກະວຽກ</h2>
        </div>
        <div class="hint" data-lo="ກຳນົດເວລາເຂົ້າ-ອອກ ສຳລັບແຕ່ລະກະ. ຮ້ານທີ່ມີຫຼາຍກະ (ເຊັ່ນ ຮ້ານກາເຟ) ສ້າງໄດ້ຫຼາຍກະ. ‘ເວລາຜ່ອນຜັນ’ ຄືນາທີທີ່ບໍ່ນັບວ່າມາຊ້າ."
             data-en="Set start/end times per shift. Businesses with multiple shifts (e.g. a coffee shop) can create several. ‘Grace’ is minutes not counted as late.">
            Set start/end times per shift.
        </div>

        <table>
            <thead><tr>
                <th data-lo="ຊື່ກະ" data-en="Shift">Shift</th>
                <th data-lo="ວັນ" data-en="Days">Days</th>
                <th data-lo="ເຂົ້າ" data-en="Start">Start</th>
                <th data-lo="ອອກ" data-en="End">End</th>
                <th data-lo="ຜ່ອນຜັນ" data-en="Grace">Grace</th>
                <th data-lo="ສະຖານະ" data-en="Status">Status</th>
                <th></th>
            </tr></thead>
            <tbody>
            <?php if (!$shifts): ?>
                <tr><td colspan="7" class="empty" data-lo="ຍັງບໍ່ມີກະວຽກ — ເພີ່ມຂ້າງລຸ່ມ." data-en="No shifts yet — add one below.">No shifts yet — add one below.</td></tr>
            <?php else: foreach ($shifts as $s):
                $sw = array_filter(array_map('intval', explode(',', (string)($s['weekdays'] ?? ''))));
                $swTxt = $sw ? implode(' ', array_map(fn($d)=>$DAYS[$d][0] ?? $d, $sw)) : '—';
                $isHalf = isset($s['day_value']) && (float)$s['day_value'] < 1;
            ?>
                <tr>
                    <td><strong><?= htmlspecialchars($s['name']) ?></strong>
                        <?= $s['crosses_midnight'] ? ' <span class="pill off" data-lo="ຂ້າມຄືນ" data-en="Overnight">Overnight</span>' : '' ?>
                        <?= $isHalf ? ' <span class="pill off" style="background:#fef3c7;color:#92400e" data-lo="ເຄິ່ງວັນ" data-en="Half day">Half day</span>' : '' ?></td>
                    <td style="font-size:12px;font-weight:700;"><?= htmlspecialchars($swTxt) ?></td>
                    <td><?= htmlspecialchars(substr($s['start_time'],0,5)) ?></td>
                    <td><?= htmlspecialchars(substr($s['end_time'],0,5)) ?></td>
                    <td><?= (int)$s['grace_minutes'] ?> <span style="color:var(--muted)" data-lo="ນທ" data-en="min">min</span></td>
                    <td><?= $s['is_active'] ? '<span class="pill on" data-lo="ໃຊ້ງານ" data-en="Active">Active</span>' : '<span class="pill off" data-lo="ປິດ" data-en="Off">Off</span>' ?></td>
                    <td style="white-space:nowrap;text-align:right;">
                        <button class="btn btn-ghost btn-sm" type="button"
                            onclick='editShift(<?= json_encode($s, JSON_UNESCAPED_UNICODE|JSON_HEX_APOS|JSON_HEX_QUOT) ?>)'
                            data-lo="ແກ້ໄຂ" data-en="Edit">Edit</button>
                        <form method="POST" style="display:inline" onsubmit="return confirm('Delete this shift?')">
                            <input type="hidden" name="action" value="delete_shift">
                            <input type="hidden" name="shift_id" value="<?= (int)$s['id'] ?>">
                            <button class="btn btn-del btn-sm" type="submit" data-lo="ລຶບ" data-en="Delete">Delete</button>
                        </form>
                    </td>
                </tr>
            <?php endforeach; endif; ?>
            </tbody>
        </table>

        <form method="POST" id="shiftForm">
            <input type="hidden" name="action" value="save_shift">
            <input type="hidden" name="shift_id" id="s_id" value="0">
            <div class="form-title"><span id="s_form_label" data-lo="ເພີ່ມກະວຽກ" data-en="Add Shift">Add Shift</span></div>
            <div class="row">
                <div class="fg" style="flex:2;">
                    <label data-lo="ຊື່ກະ" data-en="Shift name">Shift name</label>
                    <input type="text" name="name" id="s_name" required
                        data-lo-placeholder="ເຊັ່ນ: ກະເຊົ້າ" data-en-placeholder="e.g. Morning shift">
                </div>
                <div class="fg">
                    <label data-lo="ເວລາເຂົ້າ" data-en="Start time">Start time</label>
                    <input type="text" name="start_time" id="s_start" class="tp" value="08:00">
                </div>
                <div class="fg">
                    <label data-lo="ເວລາອອກ" data-en="End time">End time</label>
                    <input type="text" name="end_time" id="s_end" class="tp" value="17:00">
                </div>
            </div>
            <div class="row">
                <div class="fg">
                    <label data-lo="ຜ່ອນຜັນ (ນາທີ)" data-en="Grace (min)">Grace (min)</label>
                    <input type="number" name="grace_minutes" id="s_grace" value="5" min="0">
                </div>
                <div class="fg">
                    <label data-lo="ພັກ (ນາທີ)" data-en="Break (min)">Break (min)</label>
                    <input type="number" name="break_minutes" id="s_break" value="60" min="0">
                </div>
                <div class="fg">
                    <label data-lo="OT ຫຼັງ (ນາທີ)" data-en="OT after (min)">OT after (min)</label>
                    <input type="number" name="ot_after_minutes" id="s_ot" value="0" min="0">
                </div>
            </div>
            <div class="fg" style="min-width:100%;">
                <label data-lo="ໃຊ້ໃນວັນ" data-en="Applies on days">Applies on days</label>
                <div class="checks" id="s_weekdays">
                    <?php foreach ($DAYS as $n=>$d): ?>
                    <label class="check">
                        <input type="checkbox" name="weekdays[]" value="<?= $n ?>" class="s_wd">
                        <span data-lo="<?= $d[1] ?>" data-en="<?= $d[0] ?>"><?= $d[1] ?></span>
                    </label>
                    <?php endforeach; ?>
                </div>
            </div>
            <div class="row" style="align-items:center;">
                <label class="switch" style="margin-bottom:8px;">
                    <input type="checkbox" name="half_day" id="s_half">
                    <span data-lo="ເຄິ່ງວັນ (ນັບເປັນ 0.5 ວັນ ສຳລັບເງິນເດືອນ)" data-en="Half day (counts as 0.5 day for pay)">Half day (counts as 0.5 day)</span>
                </label>
                <label class="switch" style="margin-bottom:8px;">
                    <input type="checkbox" name="crosses_midnight" id="s_cross">
                    <span data-lo="ກະຂ້າມຄືນ" data-en="Overnight (ends next day)">Overnight (ends next day)</span>
                </label>
                <label class="switch" style="margin-bottom:8px;">
                    <input type="checkbox" name="is_active" id="s_active" checked>
                    <span data-lo="ໃຊ້ງານ" data-en="Active">Active</span>
                </label>
            </div>
            <div class="form-actions">
                <button type="submit" class="btn btn-primary" data-lo="💾 ບັນທຶກກະວຽກ" data-en="💾 Save Shift">💾 Save Shift</button>
                <button type="button" class="btn btn-ghost" onclick="resetShift()" data-lo="ລ້າງ" data-en="Clear">Clear</button>
            </div>
        </form>
    </div>

    <!-- ════════ RULES ════════ -->
    <div class="card">
        <div class="card-head">
            <div class="ic amber">⚙️</div>
            <h2 data-lo="ກົດລະບຽບເງິນເດືອນ" data-en="Payroll Rules">ກົດລະບຽບເງິນເດືອນ</h2>
        </div>
        <div class="hint" data-lo="ກົດເຫຼົ່ານີ້ໃຊ້ຄິດໄລ່ມາຊ້າ, ຂາດວຽກ ແລະ OT ໂດຍອັດຕະໂນມັດ."
             data-en="These rules drive automatic late, absence and overtime calculations.">
            These rules drive automatic late, absence and overtime calculations.
        </div>

        <form method="POST">
            <input type="hidden" name="action" value="save_rules">

            <div class="fg" style="min-width:100%;">
                <label data-lo="ເວລາເຮັດວຽກແຕ່ລະວັນ" data-en="Working hours by day">Working hours by day</label>
                <div class="hint" style="margin-bottom:10px;" data-lo="ຕິກວັນທີ່ເຮັດວຽກ ແລ້ວໃສ່ເວລາເຂົ້າ-ອອກ. ສຳລັບເສົາເຄິ່ງວັນ ໃຫ້ຕິກ ‘ເຄິ່ງວັນ’."
                     data-en="Tick the days you work and set start/end times. For a half-day Saturday, tick ‘Half’.">
                    Tick the days you work and set start/end times.
                </div>
                <div class="day-grid">
                    <div class="day-row dayhead">
                        <span class="day-toggle"></span>
                        <div class="day-times">
                            <span class="seslabel" data-lo="ເຊົ້າ" data-en="Morning">Morning</span>
                            <span class="seslabel" data-lo="ບ່າຍ" data-en="Afternoon">Afternoon</span>
                            <span></span>
                        </div>
                    </div>
                    <?php foreach ($DAYS as $n=>$d):
                        $on  = isset($schedule[$n]);
                        $s   = $on ? $schedule[$n] : [];
                        $amS = $s['am_start'] ?? '';   // show exactly what's saved
                        $amE = $s['am_end']   ?? '';   // empty = blank field (not a grey hint)
                        $pmS = $s['pm_start'] ?? '';
                        $pmE = $s['pm_end']   ?? '';
                        $half= $on && (float)($s['value'] ?? 1) < 1;
                    ?>
                    <div class="day-row<?= $on?'':' off' ?><?= $half?' halfday':'' ?>" id="dayrow-<?= $n ?>">
                        <label class="day-toggle">
                            <input type="checkbox" name="day_on[<?= $n ?>]" value="1" <?= $on?'checked':'' ?> onchange="toggleDay(<?= $n ?>,this.checked)">
                            <span class="day-name" data-lo="<?= $d[1] ?>" data-en="<?= $d[0] ?>"><?= $d[1] ?></span>
                        </label>
                        <div class="day-times">
                            <div class="ses">
                                <input type="text" class="tp day-time" name="day_am_start[<?= $n ?>]" value="<?= htmlspecialchars($amS) ?>" placeholder="--:--">
                                <span class="dash">–</span>
                                <input type="text" class="tp day-time" name="day_am_end[<?= $n ?>]" value="<?= htmlspecialchars($amE) ?>" placeholder="--:--">
                            </div>
                            <div class="ses pm-ses">
                                <input type="text" class="tp day-time" name="day_pm_start[<?= $n ?>]" value="<?= htmlspecialchars($half?'':$pmS) ?>" placeholder="--:--">
                                <span class="dash">–</span>
                                <input type="text" class="tp day-time" name="day_pm_end[<?= $n ?>]" value="<?= htmlspecialchars($half?'':$pmE) ?>" placeholder="--:--">
                            </div>
                            <label class="day-half">
                                <input type="checkbox" name="day_half[<?= $n ?>]" value="1" <?= $half?'checked':'' ?> onchange="toggleHalf(<?= $n ?>,this.checked)">
                                <span data-lo="ເຄິ່ງວັນ" data-en="Half">Half</span>
                            </label>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
                <div class="hint" style="margin-top:8px;" data-lo="‘ເຄິ່ງວັນ’ = ມີສະເພາະຮອບເຊົ້າ (ເຊັ່ນ ເສົາ 09:00–12:00). ພະນັກງານຈະລົງເວລາ 4 ຄັ້ງ/ວັນ: ເຂົ້າ-ອອກ ເຊົ້າ ແລະ ບ່າຍ."
                     data-en="‘Half’ = morning session only (e.g. Sat 09:00–12:00). Staff punch 4 times a day: morning in/out and afternoon in/out.">
                    Half = morning only. Staff punch 4 times a day.
                </div>
            </div>

            <div class="row">
                <div class="fg">
                    <label data-lo="ຜ່ອນຜັນ (ນາທີ)" data-en="Grace (min)">Grace (min)</label>
                    <input type="number" name="sched_grace" value="<?= (int)$schedGrace ?>" min="0">
                </div>
                <div class="fg">
                    <label data-lo="OT ເລີ່ມຫຼັງເລີກວຽກ (ນາທີ)" data-en="OT starts after end (min)">OT starts after end (min)</label>
                    <input type="number" name="sched_ot_after" value="<?= (int)$schedOtAfter ?>" min="0">
                </div>
                <div class="fg">
                    <label data-lo="ມື້ເລີ່ມຮອບເງິນເດືອນ" data-en="Payroll cycle start day">Payroll cycle start day</label>
                    <input type="number" name="cycle_start_day" value="<?= (int)$cycleStart ?>" min="1" max="28">
                    <div class="hint" data-lo="ເຊັ່ນ 22 = ຮອບແຕ່ວັນທີ 22 ຫາ 21 ຂອງເດືອນຕໍ່ໄປ. (1 = ຕົ້ນເດືອນ)"
                         data-en="e.g. 22 = cycle runs 22nd to 21st of next month. (1 = calendar month)">e.g. 22 = 22nd to 21st of next month.</div>
                </div>
            </div>

            <div class="row">
                <div class="fg">
                    <label data-lo="ວັນເຮັດວຽກຕໍ່ເດືອນ" data-en="Working days / month">Working days / month</label>
                    <input type="number" name="working_days_per_month" value="<?= (int)($rules['working_days_per_month'] ?? 26) ?>" min="1" max="31">
                </div>
                <div class="fg">
                    <label data-lo="ຫັກມາຊ້າແບບ" data-en="Late deduction type">Late deduction type</label>
                    <select name="late_deduction_type">
                        <?php $lt = $rules['late_deduction_type'] ?? 'per_minute'; ?>
                        <option value="per_minute" <?= $lt==='per_minute'?'selected':'' ?> data-lo="ຕໍ່ນາທີ" data-en="Per minute">Per minute</option>
                        <option value="fixed"      <?= $lt==='fixed'?'selected':'' ?> data-lo="ຈຳນວນຄົງທີ່ຕໍ່ຄັ້ງ" data-en="Fixed per incident">Fixed per incident</option>
                        <option value="none"       <?= $lt==='none'?'selected':'' ?> data-lo="ບໍ່ຫັກ" data-en="No deduction">No deduction</option>
                    </select>
                </div>
                <div class="fg">
                    <label data-lo="ມູນຄ່າຫັກ (₭)" data-en="Deduction value (₭)">Deduction value (₭)</label>
                    <input type="number" name="late_deduction_value" value="<?= htmlspecialchars($rules['late_deduction_value'] ?? '0') ?>" min="0" step="any">
                </div>
            </div>

            <div class="row">
                <div class="fg">
                    <label data-lo="ຄິດຂາດວຽກຈາກ" data-en="Absence based on">Absence based on</label>
                    <select name="absence_basis">
                        <?php $ab = $rules['absence_basis'] ?? 'daily_rate'; ?>
                        <option value="daily_rate" <?= $ab==='daily_rate'?'selected':'' ?> data-lo="ອັດຕາຕໍ່ວັນ (ເງິນເດືອນ ÷ ວັນເຮັດວຽກ)" data-en="Daily rate (salary ÷ working days)">Daily rate (salary ÷ working days)</option>
                        <option value="none"       <?= $ab==='none'?'selected':'' ?> data-lo="ບໍ່ຫັກ" data-en="No deduction">No deduction</option>
                    </select>
                </div>
                <div class="fg">
                    <label data-lo="ຕົວຄູນ OT" data-en="OT multiplier">OT multiplier</label>
                    <input type="number" name="ot_multiplier" value="<?= htmlspecialchars($rules['ot_multiplier'] ?? '1.50') ?>" min="1" step="0.05">
                </div>
                <div class="fg">
                    <label data-lo="OT ຂັ້ນຕ່ຳ (ນາທີ)" data-en="Min OT (min)">Min OT (min)</label>
                    <input type="number" name="min_ot_minutes" value="<?= (int)($rules['min_ot_minutes'] ?? 30) ?>" min="0">
                </div>
                <div class="fg">
                    <label data-lo="ປັດເສດເວລາ (ນາທີ)" data-en="Round to (min)">Round to (min)</label>
                    <input type="number" name="round_minutes" value="<?= (int)($rules['round_minutes'] ?? 0) ?>" min="0">
                </div>
            </div>

            <label class="switch" style="margin-bottom:14px;">
                <input type="checkbox" name="geofence_default" <?= !empty($rules['geofence_default'])?'checked':'' ?>>
                <span data-lo="ບັງຄັບ GPS ໂດຍຄ່າເລີ່ມຕົ້ນ (ພະນັກງານຕ້ອງຢູ່ໃນສາຂາ)" data-en="Require GPS by default (staff must be at a branch)">Require GPS by default</span>
            </label>

            <div class="form-actions">
                <button type="submit" class="btn btn-primary" data-lo="💾 ບັນທຶກກົດລະບຽບ" data-en="💾 Save Rules">💾 Save Rules</button>
            </div>
        </form>
    </div>

    <div style="text-align:center;color:var(--muted);font-size:12px;padding:8px 0 24px;">
        <span data-lo="ຕໍ່ໄປ: ມອບໝາຍກະ ແລະ ສາຂາ ໃຫ້ພະນັກງານ (ໜ້າຈັດການພະນັກງານ)."
              data-en="Next: assign shifts and branches to staff (on the staff page).">
            Next: assign shifts and branches to staff.
        </span>
    </div>

</div>

<script>
/* ── Flatpickr time pickers (24h, HH:MM) ── */
function initTimePickers(){
    if (typeof flatpickr === "undefined") return;
    document.querySelectorAll(".tp").forEach(el=>{
        if (el._fp) return;
        var nm = el.getAttribute("name") || "";
        /* open empty fields at a sensible hour: morning 08:00, afternoon 13:00 */
        var defH = /am_/.test(nm) ? 8 : (/pm_/.test(nm) ? 13 : 8);
        el._fp = flatpickr(el, { enableTime:true, noCalendar:true, dateFormat:"H:i", time_24hr:true,
                                 minuteIncrement:5, defaultHour:defH, defaultMinute:0 });
    });
}
document.addEventListener("DOMContentLoaded", initTimePickers);
initTimePickers();

/* ── Per-day working-hours grid ── */
function toggleDay(n, on){
    const row = document.getElementById("dayrow-"+n);
    if (row) row.classList.toggle("off", !on);
}
function toggleHalf(n, half){
    const row = document.getElementById("dayrow-"+n);
    if (row) row.classList.toggle("halfday", half);
}

/* ── Branch edit/reset ── */
function editBranch(b){
    document.getElementById("b_id").value     = b.id;
    document.getElementById("b_name").value   = b.name || "";
    document.getElementById("b_lat").value    = b.lat ?? "";
    document.getElementById("b_lng").value    = b.lng ?? "";
    document.getElementById("b_radius").value = b.radius_m ?? 150;
    document.getElementById("b_active").checked = (b.is_active == 1);
    const lbl = document.getElementById("b_form_label");
    lbl.dataset.en = "Edit Branch"; lbl.dataset.lo = "ແກ້ໄຂສາຂາ";
    lbl.textContent = (window._lang === "en") ? "Edit Branch" : "ແກ້ໄຂສາຂາ";
    document.getElementById("branchForm").scrollIntoView({behavior:"smooth", block:"center"});
}
function resetBranch(){
    document.getElementById("branchForm").reset();
    document.getElementById("b_id").value = 0;
    document.getElementById("b_active").checked = true;
    const lbl = document.getElementById("b_form_label");
    lbl.dataset.en = "Add Branch"; lbl.dataset.lo = "ເພີ່ມສາຂາ";
    lbl.textContent = (window._lang === "en") ? "Add Branch" : "ເພີ່ມສາຂາ";
}

/* ── Shift edit/reset ── */
function editShift(s){
    document.getElementById("s_id").value    = s.id;
    document.getElementById("s_name").value  = s.name || "";
    document.getElementById("s_start").value = (s.start_time||"08:00").substring(0,5);
    document.getElementById("s_end").value   = (s.end_time||"17:00").substring(0,5);
    document.getElementById("s_grace").value = s.grace_minutes ?? 0;
    document.getElementById("s_break").value = s.break_minutes ?? 0;
    document.getElementById("s_ot").value    = s.ot_after_minutes ?? 0;
    document.getElementById("s_cross").checked  = (s.crosses_midnight == 1);
    document.getElementById("s_active").checked = (s.is_active == 1);
    document.getElementById("s_half").checked   = (parseFloat(s.day_value) < 1);
    const wd = String(s.weekdays || "").split(",").filter(Boolean);
    document.querySelectorAll(".s_wd").forEach(c => { c.checked = wd.includes(c.value); });
    const lbl = document.getElementById("s_form_label");
    lbl.dataset.en = "Edit Shift"; lbl.dataset.lo = "ແກ້ໄຂກະວຽກ";
    lbl.textContent = (window._lang === "en") ? "Edit Shift" : "ແກ້ໄຂກະວຽກ";
    document.getElementById("shiftForm").scrollIntoView({behavior:"smooth", block:"center"});
}
function resetShift(){
    document.getElementById("shiftForm").reset();
    document.getElementById("s_id").value = 0;
    document.getElementById("s_active").checked = true;
    document.getElementById("s_half").checked = false;
    document.querySelectorAll(".s_wd").forEach(c => c.checked = false);
    const lbl = document.getElementById("s_form_label");
    lbl.dataset.en = "Add Shift"; lbl.dataset.lo = "ເພີ່ມກະວຽກ";
    lbl.textContent = (window._lang === "en") ? "Add Shift" : "ເພີ່ມກະວຽກ";
}

/* ── Geolocation ── */
function useMyLocation(){
    if (!navigator.geolocation){ alert("Geolocation not supported on this device."); return; }
    navigator.geolocation.getCurrentPosition(
        pos=>{
            document.getElementById("b_lat").value = pos.coords.latitude.toFixed(7);
            document.getElementById("b_lng").value = pos.coords.longitude.toFixed(7);
        },
        err=>{ alert("Could not get location: "+err.message+"\n(Requires HTTPS and location permission.)"); },
        { enableHighAccuracy:true, timeout:10000 }
    );
}
</script>

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