<?php
/* ============================================================================
 *  company/payroll_generate.php — Phase C
 *  Auto-compute monthly payroll from attendance:
 *    • days present / absent, total late minutes, approved OT
 *    • daily rate  = base salary ÷ working days/month (from rules)
 *    • late deduction (per-minute or fixed) + absence deduction
 *    • OT pay = approved OT hours × each person's OT rate
 *  Writes DRAFT rows into hr_salary (never overwrites rows already marked Paid).
 *  Bilingual EN/Lao · 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';
require_once '../config/loans.php';
date_default_timezone_set('Asia/Vientiane');

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

$month = (int)($_GET["month"] ?? $_POST["month"] ?? date("n"));
$year  = (int)($_GET["year"]  ?? $_POST["year"]  ?? date("Y"));
if ($month < 1 || $month > 12) $month = (int)date("n");

/* ── Core computation (used for preview AND save) ── */
function computePayroll(PDO $pdo, int $companyId, int $month, int $year): array {
    /* rules */
    $st = $pdo->prepare("SELECT * FROM att_rules WHERE company_id=? LIMIT 1");
    $st->execute([$companyId]);
    $rules = $st->fetch(PDO::FETCH_ASSOC) ?: [];
    $W        = max(1, (int)($rules['working_days_per_month'] ?? 26));
    $workdays = array_filter(array_map('intval', explode(',', (string)($rules['workdays'] ?? '1,2,3,4,5'))));
    $absBasis = $rules['absence_basis'] ?? 'daily_rate';
    $cycleStart = max(1, (int)($rules['cycle_start_day'] ?? 1));
    $DIV = 22;          // daily rate = salary ÷ 22 (matches the staff My Salary page)
    $LATE_GRACE = 60;   // free lateness per cycle; over this = 1 day deducted

    /* payroll cycle period for this month (e.g. 22nd → 21st of next month) */
    if ($cycleStart <= 1) {
        $periodStart = sprintf('%04d-%02d-01', $year, $month);
        $periodEnd   = date('Y-m-t', strtotime($periodStart));
    } else {
        $periodStart = sprintf('%04d-%02d-%02d', $year, $month, $cycleStart);
        $periodEnd   = date('Y-m-d', strtotime($periodStart.' +1 month -1 day'));
    }
    $today  = date('Y-m-d');
    $cutoff = ($periodEnd < $today) ? $periodEnd : (($periodStart > $today) ? null : $today);

    /* weekday -> day value (1.0 full, 0.5 half).
       Prefer the per-day schedule set under Payroll Rules; fall back to shifts' weekdays. */
    $dayVal = [];
    if (!empty($rules['extra'])) {
        $ex = json_decode($rules['extra'], true);
        if (is_array($ex) && !empty($ex['schedule']) && is_array($ex['schedule'])) {
            foreach ($ex['schedule'] as $k=>$v) $dayVal[(int)$k] = (float)($v['value'] ?? 1);
        }
    }
    if (!$dayVal) {
        try {
            $sh = $pdo->prepare("SELECT weekdays, day_value FROM att_shifts WHERE company_id=? AND is_active=1");
            $sh->execute([$companyId]);
            foreach ($sh->fetchAll(PDO::FETCH_ASSOC) as $row) {
                $v = (float)($row['day_value'] ?? 1);
                foreach (array_filter(array_map('intval', explode(',', (string)($row['weekdays'] ?? '')))) as $iso) {
                    if (!isset($dayVal[$iso])) $dayVal[$iso] = $v;
                }
            }
        } catch (Throwable $e) {}
    }

    /* scheduled (elapsed) days this month, each carrying its day value */
    $scheduledDates = [];
    if ($cutoff !== null) {
        for ($d = strtotime($periodStart); $d <= strtotime($cutoff); $d += 86400) {
            $iso = (int)date('N', $d);              // 1=Mon .. 7=Sun
            if (isset($dayVal[$iso]))                 $scheduledDates[date('Y-m-d', $d)] = $dayVal[$iso];
            elseif (!$dayVal && in_array($iso, $workdays, true)) $scheduledDates[date('Y-m-d', $d)] = 1.0; // fallback if no shift weekdays set
        }
    }
    $S = array_sum($scheduledDates);   // day-equivalents (e.g. Mon–Fri=5 + Sat half=0.5)

    /* exempt map */
    $ex = $pdo->prepare("SELECT staff_id, checkin_required FROM att_staff WHERE company_id=?");
    $ex->execute([$companyId]);
    $exempt = [];
    foreach ($ex->fetchAll(PDO::FETCH_ASSOC) as $r) $exempt[(int)$r['staff_id']] = ((int)$r['checkin_required'] === 0);

    /* active staff */
    $staff = $pdo->prepare("SELECT u.id,u.name,cs.position 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);

    $out = [];
    foreach ($staff as $p) {
        $sid = (int)$p['id'];
        $isExempt = $exempt[$sid] ?? false;

        /* attendance rows for the month */
        $at = $pdo->prepare("SELECT work_date,status,late_minutes,ot_minutes,ot_status
                             FROM hr_attendance WHERE staff_id=? AND company_id=? AND work_date BETWEEN ? AND ?");
        $at->execute([$sid, $companyId, $periodStart, $periodEnd]);
        $lateTotal=0; $lateInc=0; $otAppr=0; $present=0; $attendedSched=[];
        foreach ($at->fetchAll(PDO::FETCH_ASSOC) as $a) {
            $present_status = in_array($a['status'], ['present','late','half_day'], true);
            if ($present_status) { $present++; if (isset($scheduledDates[$a['work_date']])) $attendedSched[$a['work_date']]=true; }
            $lateTotal += (int)$a['late_minutes'];
            if ((int)$a['late_minutes'] > 0) $lateInc++;
            if ($a['ot_status'] === 'approved') $otAppr += (int)$a['ot_minutes'];
        }

        /* approved leave days that fall on scheduled workdays */
        $leaveSet = [];
        try {
            $lv = $pdo->prepare("SELECT start_date,end_date FROM hr_leave WHERE staff_id=? AND company_id=? AND status='approved'");
            $lv->execute([$sid, $companyId]);
            foreach ($lv->fetchAll(PDO::FETCH_ASSOC) as $l) {
                $a = max($l['start_date'], $periodStart);
                $b = min($l['end_date'],   $periodEnd);
                for ($d = strtotime($a); $d <= strtotime($b); $d += 86400) {
                    $ds = date('Y-m-d', $d);
                    if (isset($scheduledDates[$ds])) $leaveSet[$ds] = true;
                }
            }
        } catch (Throwable $e) {}
        $leaveDays = count($leaveSet);

        /* absence in day-equivalents: scheduled days not attended and not on leave,
           each weighted by its day value (Saturday half-day counts 0.5) */
        $absentVal = 0.0; $absentCount = 0;
        if (!$isExempt) {
            foreach ($scheduledDates as $ds => $val) {
                if (!isset($attendedSched[$ds]) && !isset($leaveSet[$ds])) { $absentVal += $val; $absentCount++; }
            }
        }

        /* base + ot rate: this month's row if any, else carry from latest prior */
        $cur = $pdo->prepare("SELECT id,base_salary,ot_rate,paid_at FROM hr_salary WHERE staff_id=? AND company_id=? AND month=? AND year=? LIMIT 1");
        $cur->execute([$sid, $companyId, $month, $year]);
        $cur = $cur->fetch(PDO::FETCH_ASSOC);
        if ($cur) {
            $base = (float)$cur['base_salary']; $otRate=(float)$cur['ot_rate'];
            $existId = (int)$cur['id']; $paid = !empty($cur['paid_at']);
        } else {
            $pr = $pdo->prepare("SELECT base_salary,ot_rate FROM hr_salary WHERE staff_id=? AND company_id=? ORDER BY year DESC,month DESC LIMIT 1");
            $pr->execute([$sid, $companyId]);
            $pr = $pr->fetch(PDO::FETCH_ASSOC);
            /* prefer the editable base salary on the staff profile */
            $profileBase = 0;
            try {
                $cb = $pdo->prepare("SELECT base_salary FROM company_staff WHERE user_id=? AND company_id=? LIMIT 1");
                $cb->execute([$sid,$companyId]);
                $profileBase = (float)$cb->fetchColumn();
            } catch (Throwable $e) {}
            $base = $profileBase > 0 ? $profileBase : (float)($pr['base_salary'] ?? 0);
            $otRate=(float)($pr['ot_rate'] ?? 0);
            $existId = null; $paid = false;
        }

        $dailyRate = $base / $DIV;                       // salary ÷ 22
        if ($isExempt) { $lateTotal=0; $lateInc=0; }

        /* late deduction: total late over the cycle > 60 min => deduct one day */
        $lateDed = (!$isExempt && $lateTotal > $LATE_GRACE) ? round($dailyRate, 2) : 0;
        $absDed  = $absBasis==='daily_rate' ? $absentVal*$dailyRate : 0;

        $otHours = round($otAppr/60, 2);
        $totalOt = round($otHours*$otRate, 2);

        $allow = $pdo->prepare("SELECT COALESCE(SUM(amount),0) FROM hr_allowances WHERE staff_id=? AND company_id=? AND is_recurring=1");
        $allow->execute([$sid, $companyId]);
        $allowSum = (float)$allow->fetchColumn();

        /* loan repayment scheduled for this cycle */
        $loanDed = loan_period_deduction($pdo, $companyId, $sid, $periodStart);

        $deductions = round($lateDed + $absDed + $loanDed, 2);
        $net = round($base + $totalOt + $allowSum - $deductions, 2);

        $out[] = [
            'staff_id'=>$sid, 'name'=>$p['name'], 'position'=>$p['position'],
            'exempt'=>$isExempt, 'present'=>$present, 'absent'=>$absentCount, 'absent_val'=>$absentVal, 'leave'=>$leaveDays,
            'late_minutes'=>$lateTotal, 'ot_minutes'=>$otAppr, 'ot_hours'=>$otHours,
            'base'=>$base, 'ot_rate'=>$otRate, 'total_ot'=>$totalOt, 'allow'=>$allowSum,
            'late_ded'=>round($lateDed,2), 'abs_ded'=>round($absDed,2), 'loan_ded'=>round($loanDed,2),
            'deductions'=>$deductions, 'net'=>$net,
            'exist_id'=>$existId, 'paid'=>$paid,
        ];
    }

    return ['rows'=>$out, 'W'=>$W, 'divisor'=>$DIV, 'scheduled'=>$S, 'abs_basis'=>$absBasis,
            'period_start'=>$periodStart, 'period_end'=>$periodEnd];
}

/* ── POST: write drafts ── */
$saved = null;
if ($_SERVER["REQUEST_METHOD"] === "POST" && ($_POST['action'] ?? '') === 'generate') {
    $calc = computePayroll($pdo, $companyId, $month, $year);
    $written=0; $skipped=0;
    $now = date('Y-m-d H:i:s');
    $periodStartSave = $calc['period_start'];
    foreach ($calc['rows'] as $r) {
        if ($r['paid']) { $skipped++; continue; }   // never touch paid rows
        /* record this cycle's loan repayments (idempotent — once per loan/period) */
        loan_record_payments($pdo, $companyId, (int)$r['staff_id'], $periodStartSave);
        if ($r['exist_id']) {
            $pdo->prepare("UPDATE hr_salary SET base_salary=?, ot_hours=?, ot_rate=?, total_ot=?, total_allowances=?,
                            deductions=?, net_pay=?, days_present=?, days_absent=?, late_minutes=?, late_deduction=?,
                            absence_deduction=?, ot_minutes=?, auto_generated=1, generated_at=? WHERE id=?")
                ->execute([$r['base'],$r['ot_hours'],$r['ot_rate'],$r['total_ot'],$r['allow'],
                           $r['deductions'],$r['net'],$r['present'],$r['absent'],$r['late_minutes'],$r['late_ded'],
                           $r['abs_ded'],$r['ot_minutes'],$now,$r['exist_id']]);
        } else {
            $pdo->prepare("INSERT INTO hr_salary (staff_id,company_id,month,year,base_salary,ot_hours,ot_rate,total_ot,
                            total_allowances,deductions,net_pay,days_present,days_absent,late_minutes,late_deduction,
                            absence_deduction,ot_minutes,auto_generated,generated_at)
                            VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,1,?)")
                ->execute([$r['staff_id'],$companyId,$month,$year,$r['base'],$r['ot_hours'],$r['ot_rate'],$r['total_ot'],
                           $r['allow'],$r['deductions'],$r['net'],$r['present'],$r['absent'],$r['late_minutes'],
                           $r['late_ded'],$r['abs_ded'],$r['ot_minutes'],$now]);
        }
        $written++;
    }
    $saved = ['written'=>$written, 'skipped'=>$skipped];
}

/* ── Preview ── */
$calc = computePayroll($pdo, $companyId, $month, $year);
$rows = $calc['rows'];
$mn = ["","January","February","March","April","May","June","July","August","September","October","November","December"];
$mnLo = ["","ມັງກອນ","ກຸມພາ","ມີນາ","ເມສາ","ພຶດສະພາ","ມິຖຸນາ","ກໍລະກົດ","ສິງຫາ","ກັນຍາ","ຕຸລາ","ພະຈິກ","ທັນວາ"];
function kip($n){ return number_format((float)$n, 0); }
?>
<!DOCTYPE html>
<html lang="lo">
<head>
    <?php $pwaTheme = '#0f766e'; include __DIR__ . '/../config/pwa_head.php'; ?>
    <title><?= htmlspecialchars($companyName) ?> — Payroll Generation</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">
    <script src="../assets/lang.js" defer></script>
    <style>
        *,*::before,*::after{box-sizing:border-box;margin:0;padding:0;}
        :root{--primary:#0f766e;--surface:#fff;--bg:#f0f4f8;--border:#e2e8f0;--text:#0f172a;--muted:#64748b;
            --green:#16a34a;--green-lt:#dcfce7;--red:#dc2626;--red-lt:#fee2e2;--amber:#d97706;--amber-lt:#fef3c7;
            --blue:#2563eb;--blue-lt:#dbeafe;--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-btn{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{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:1180px;margin:auto;}
        .hero{background:linear-gradient(135deg,#042f2e,#0f766e);border-radius:18px;padding:22px 26px;margin-bottom:20px;color:#fff;}
        .hero h1{font-size:22px;font-weight:800;margin-bottom:4px;}
        .hero p{font-size:13px;color:rgba(255,255,255,.8);}
        .controls{display:flex;gap:10px;align-items:flex-end;flex-wrap:wrap;margin-bottom:18px;background:var(--surface);
            padding:16px 18px;border-radius:14px;border:1px solid var(--border);box-shadow:var(--shadow);}
        .cg label{display:block;font-size:12px;font-weight:700;color:#374151;margin-bottom:5px;}
        .cg select{padding:9px 12px;border:1.5px solid var(--border);border-radius:9px;font-size:14px;font-family:inherit;background:#fff;}
        .meta{font-size:12px;color:var(--muted);margin-left:auto;text-align:right;line-height:1.7;}
        .btn{padding:11px 18px;border-radius:9px;border:none;font-size:14px;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);}
        .flash{padding:13px 16px;border-radius:10px;margin-bottom:18px;font-size:14px;font-weight:600;background:var(--green-lt);color:#15803d;}
        .card{background:var(--surface);border-radius:var(--radius);box-shadow:var(--shadow);border:1px solid var(--border);overflow:hidden;}
        .tbl-wrap{overflow-x:auto;}
        table{width:100%;border-collapse:collapse;font-size:13px;min-width:920px;}
        th{text-align:right;font-size:11px;text-transform:uppercase;letter-spacing:.3px;color:var(--muted);
            padding:10px 12px;border-bottom:2px solid var(--border);background:#f8fafc;white-space:nowrap;}
        th:first-child,td:first-child{text-align:left;}
        td{padding:10px 12px;border-bottom:1px solid var(--border);text-align:right;white-space:nowrap;}
        tr:last-child td{border-bottom:none;}
        .staffname{font-weight:700;text-align:left;}
        .sub{font-size:11px;color:var(--muted);}
        .tag{display:inline-block;padding:2px 8px;border-radius:999px;font-size:10px;font-weight:800;}
        .tag.amber{background:var(--amber-lt);color:#92400e;}.tag.red{background:var(--red-lt);color:#991b1b;}
        .tag.green{background:var(--green-lt);color:#15803d;}.tag.gray{background:#f1f5f9;color:var(--muted);}
        .net{font-weight:800;color:#0f766e;}
        .ded{color:var(--red);}
        tfoot td{background:#f8fafc;font-weight:800;border-top:2px solid var(--border);}
        .note{font-size:12px;color:var(--muted);margin-top:12px;line-height:1.6;}
        .actions{display:flex;gap:10px;margin-top:18px;flex-wrap:wrap;align-items:center;}
        @media(max-width:640px){.page{padding:14px;}}
    </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="Payroll Generation">ສ້າງເງິນເດືອນ</div>
        </div>
    </div>
    <div class="top-right">
        <button class="lang-btn" id="btn-lo" onclick="setLang('lo')">🇱🇦 ລາວ</button>
        <button class="lang-btn" id="btn-en" onclick="setLang('en')">🇬🇧 EN</button>
        <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="Generate Payroll from Attendance">ສ້າງເງິນເດືອນຈາກການເຂົ້າວຽກ</h1>
        <p data-lo="ຄິດໄລ່ມາຊ້າ, ຂາດວຽກ ແລະ OT ທີ່ອະນຸມັດ ໂດຍອັດຕະໂນມັດ ແລ້ວສ້າງຮ່າງເງິນເດືອນໃຫ້ກວດກ່ອນຈ່າຍ."
           data-en="Auto-calculates late, absence and approved OT, then creates a salary draft for you to review before paying.">
           Creates a salary draft for you to review before paying.
        </p>
    </div>

    <?php if ($saved): ?>
        <div class="flash"
             data-en="✅ Saved <?= $saved['written'] ?> draft(s)<?= $saved['skipped']?", skipped {$saved['skipped']} already-paid":"" ?>. Review and pay them on the Salary page."
             data-lo="✅ ບັນທຶກຮ່າງ <?= $saved['written'] ?> ລາຍການ<?= $saved['skipped']?", ຂ້າມ {$saved['skipped']} ທີ່ຈ່າຍແລ້ວ":"" ?>. ກວດ ແລະ ຈ່າຍຢູ່ໜ້າເງິນເດືອນ.">
            ✅ Saved <?= $saved['written'] ?> draft(s).
        </div>
    <?php endif; ?>

    <form method="GET" class="controls">
        <div class="cg">
            <label data-lo="ເດືອນ" data-en="Month">Month</label>
            <select name="month" onchange="this.form.submit()">
                <?php for ($i=1;$i<=12;$i++): ?>
                    <option value="<?= $i ?>" <?= $i===$month?'selected':'' ?> data-en="<?= $mn[$i] ?>" data-lo="<?= $mnLo[$i] ?>"><?= $mn[$i] ?></option>
                <?php endfor; ?>
            </select>
        </div>
        <div class="cg">
            <label data-lo="ປີ" data-en="Year">Year</label>
            <select name="year" onchange="this.form.submit()">
                <?php for ($y=date('Y')-1;$y<=date('Y')+1;$y++): ?>
                    <option value="<?= $y ?>" <?= $y===$year?'selected':'' ?>><?= $y ?></option>
                <?php endfor; ?>
            </select>
        </div>
        <div class="meta">
            <span data-lo="ຮອບເງິນເດືອນ:" data-en="Payroll period:">Payroll period:</span>
            <strong><?= date('d/m/Y', strtotime($calc['period_start'])) ?> – <?= date('d/m/Y', strtotime($calc['period_end'])) ?></strong><br>
            <span data-lo="ອັດຕາຕໍ່ວັນ = ເງິນເດືອນ ÷" data-en="Daily rate = salary ÷">Daily rate = salary ÷</span>
            <strong><?= $calc['divisor'] ?></strong>
        </div>
    </form>

    <div class="card">
        <div class="tbl-wrap">
        <table>
            <thead><tr>
                <th data-lo="ພະນັກງານ" data-en="Staff">Staff</th>
                <th data-lo="ມາ" data-en="Present">Present</th>
                <th data-lo="ຂາດ" data-en="Absent">Absent</th>
                <th data-lo="ຊ້າ(ນທ)" data-en="Late(min)">Late(min)</th>
                <th data-lo="OT(ຊມ)" data-en="OT(hrs)">OT(hrs)</th>
                <th data-lo="ເງິນເດືອນ" data-en="Base">Base</th>
                <th data-lo="ເງິນ OT" data-en="OT pay">OT pay</th>
                <th data-lo="ຫັກ" data-en="Deduct">Deduct</th>
                <th data-lo="ສຸດທິ" data-en="Net">Net</th>
            </tr></thead>
            <tbody>
            <?php if (!$rows): ?>
                <tr><td colspan="9" style="text-align:center;color:var(--muted);padding:30px;" data-lo="ບໍ່ມີພະນັກງານ." data-en="No staff.">No staff.</td></tr>
            <?php else:
                $tBase=$tOt=$tDed=$tNet=0;
                foreach ($rows as $r):
                    $tBase+=$r['base']; $tOt+=$r['total_ot']; $tDed+=$r['deductions']; $tNet+=$r['net'];
            ?>
                <tr>
                    <td class="staffname">
                        <?= htmlspecialchars($r['name']) ?>
                        <?php if ($r['exempt']): ?><span class="tag amber" data-lo="ຍົກເວັ້ນ" data-en="Exempt">Exempt</span><?php endif; ?>
                        <?php if ($r['paid']): ?><span class="tag green" data-lo="ຈ່າຍແລ້ວ" data-en="Paid">Paid</span><?php endif; ?>
                        <?php if ($r['leave']>0): ?><span class="tag gray"><?= $r['leave'] ?> <span data-lo="ລາ" data-en="leave">leave</span></span><?php endif; ?>
                        <?php if ($r['base']<=0): ?><br><span class="sub" data-lo="⚠ ຍັງບໍ່ໄດ້ຕັ້ງເງິນເດືອນ" data-en="⚠ no base salary set yet">⚠ no base salary set yet</span><?php endif; ?>
                    </td>
                    <td><?= $r['present'] ?></td>
                    <td><?= $r['absent']>0 ? '<span class="tag red">'.$r['absent'].'</span>' : '0' ?></td>
                    <td><?= $r['late_minutes'] ?: '0' ?></td>
                    <td><?= $r['ot_hours']>0 ? $r['ot_hours'] : '0' ?></td>
                    <td><?= kip($r['base']) ?></td>
                    <td><?= $r['total_ot']>0 ? kip($r['total_ot']) : '—' ?></td>
                    <td class="<?= $r['deductions']>0?'ded':'' ?>"><?= $r['deductions']>0 ? '−'.kip($r['deductions']) : '0' ?></td>
                    <td class="net"><?= kip($r['net']) ?></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
            <tfoot><tr>
                <td data-lo="ລວມ" data-en="Total">Total</td>
                <td colspan="4"></td>
                <td><?= kip($tBase) ?></td>
                <td><?= kip($tOt) ?></td>
                <td class="ded"><?= $tDed>0?'−'.kip($tDed):'0' ?></td>
                <td class="net"><?= kip($tNet) ?></td>
            </tr></tfoot>
            <?php endif; ?>
        </table>
        </div>
    </div>

    <div class="note">
        <span data-lo="ການຄິດໄລ່ (ຮອບ <?= date('d/m', strtotime($calc['period_start'])) ?>–<?= date('d/m', strtotime($calc['period_end'])) ?>): ອັດຕາຕໍ່ວັນ = ເງິນເດືອນ ÷ <?= $calc['divisor'] ?>. ມາຊ້າລວມເກີນ 60 ນທ → ຫັກ 1 ວັນ. ຫັກຂາດວຽກ = ວັນຂາດ × ອັດຕາຕໍ່ວັນ. OT = ຊມ OT ທີ່ອະນຸມັດ × ອັດຕາ OT. ຄົນຍົກເວັ້ນບໍ່ຖືກຫັກ."
              data-en="How it works (cycle <?= date('d/m', strtotime($calc['period_start'])) ?>–<?= date('d/m', strtotime($calc['period_end'])) ?>): daily rate = base ÷ <?= $calc['divisor'] ?>. Total late over 60 min → deduct 1 day. Absence = absent days × daily rate. OT = approved OT hours × OT rate. Exempt staff are not deducted.">
            How it works: daily rate = base ÷ <?= $calc['divisor'] ?>; total late over 60 min → deduct 1 day; absence = absent days × daily rate; OT = approved OT hours × OT rate.
        </span>
    </div>

    <?php if ($rows): ?>
    <form method="POST" class="actions" onsubmit="return confirm('Save these payroll drafts? Rows already marked Paid are skipped.');">
        <input type="hidden" name="action" value="generate">
        <input type="hidden" name="month" value="<?= $month ?>">
        <input type="hidden" name="year" value="<?= $year ?>">
        <button type="submit" class="btn btn-primary" data-lo="💾 ບັນທຶກຮ່າງເງິນເດືອນ" data-en="💾 Save payroll drafts">💾 Save payroll drafts</button>
        <a class="btn btn-ghost" href="hr_salary.php?month=<?= $month ?>&year=<?= $year ?>" data-lo="ໄປໜ້າເງິນເດືອນ →" data-en="Open Salary page →">Open Salary page →</a>
        <span class="sub" data-lo="ຮ່າງຈະບໍ່ທັບແຖວທີ່ໝາຍ ‘ຈ່າຍແລ້ວ’." data-en="Drafts never overwrite rows marked Paid.">Drafts never overwrite Paid rows.</span>
    </form>
    <?php endif; ?>

</div>

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