<?php
/* ============================================================================
 *  company/leave_balances.php
 *  Company admin views & sets each staff member's annual leave entitlement,
 *  and sees days used / remaining for the year.
 *  Bilingual EN/Lao.
 * ==========================================================================*/
session_start();
if (!isset($_SESSION["user_id"]) || $_SESSION["role"] !== "company_admin") {
    header("Location: ../auth/login.php"); exit;
}
require_once '../config/database.php';
date_default_timezone_set('Asia/Vientiane');

$companyId   = (int)$_SESSION["company_id"];
$companyName = $_SESSION["company_name"] ?? "My Company";
$year        = (int)($_GET["year"] ?? date('Y'));

/* ── Save ── */
if ($_SERVER["REQUEST_METHOD"] === "POST" && ($_POST["action"] ?? '')==="save") {
    try {
        $ids = array_map('intval', (array)($_POST["ids"] ?? []));
        $up  = $pdo->prepare("UPDATE company_staff SET annual_leave_days=? WHERE user_id=? AND company_id=?");
        foreach ($ids as $uid) {
            $d = isset($_POST["days"][$uid]) ? (int)$_POST["days"][$uid] : 15;
            if ($d < 0) $d = 0;
            $up->execute([$d, $uid, $companyId]);
        }
        $_SESSION["lb_flash"] = ["ok","Annual leave days saved.","ບັນທຶກວັນລາພັກປະຈຳປີແລ້ວ."];
    } catch (Throwable $e) {
        $_SESSION["lb_flash"] = ["err","Error: ".$e->getMessage(),"ຜິດພາດ: ".$e->getMessage()];
    }
    header("Location: leave_balances.php?year=$year"); exit;
}

/* ── Load staff + usage ── */
$staff = $pdo->prepare("
    SELECT u.id, u.name, cs.position, cs.department,
           COALESCE(cs.annual_leave_days, 15) AS entitle
    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);

/* used annual days (approved) per staff this year */
$usedMap = [];
$us = $pdo->prepare("SELECT staff_id, COALESCE(SUM(days),0) AS d FROM hr_leave
                     WHERE company_id=? AND leave_type='annual' AND status='approved' AND YEAR(start_date)=?
                     GROUP BY staff_id");
$us->execute([$companyId, $year]);
foreach ($us->fetchAll(PDO::FETCH_ASSOC) as $r) $usedMap[(int)$r['staff_id']] = (int)$r['d'];

$flash = $_SESSION["lb_flash"] ?? null; unset($_SESSION["lb_flash"]);
?>
<!DOCTYPE html>
<html lang="lo">
<head>
    <?php $pwaTheme='#0f766e'; include __DIR__.'/../config/pwa_head.php'; ?>
    <title><?= htmlspecialchars($companyName) ?> — Leave Balances</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;--amber:#d97706;--amber-lt:#fef3c7;--red:#dc2626;--red-lt:#fee2e2;
            --radius:14px;--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:14px;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:10px;}
        .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:22px 20px;max-width:900px;margin:auto;}
        h1{font-size:20px;font-weight:800;margin-bottom:6px;}
        .sub{font-size:13px;color:var(--muted);margin-bottom:16px;}
        .flash{padding:12px 16px;border-radius:10px;margin-bottom:16px;font-size:14px;font-weight:600;}
        .flash.ok{background:var(--green-lt);color:#15803d;}.flash.err{background:var(--red-lt);color:var(--red);}
        .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:14px;min-width:560px;}
        th{text-align:left;font-size:11px;text-transform:uppercase;letter-spacing:.3px;color:var(--muted);padding:11px 12px;border-bottom:2px solid var(--border);background:#f8fafc;}
        th.num,td.num{text-align:center;}
        td{padding:11px 12px;border-bottom:1px solid var(--border);vertical-align:middle;}
        tr:last-child td{border-bottom:none;}
        .nm{font-weight:700;}.sb{font-size:11px;color:var(--muted);}
        input[type=number]{width:80px;padding:8px 10px;border:1.5px solid var(--border);border-radius:8px;font-size:14px;font-family:inherit;text-align:center;}
        .used{color:var(--amber);font-weight:700;}.left{color:var(--green);font-weight:800;}
        .bar{display:flex;gap:10px;align-items:center;padding:14px;border-top:1px solid var(--border);background:#f8fafc;flex-wrap:wrap;}
        .btn{padding:11px 18px;border-radius:9px;border:none;background:var(--primary);color:#fff;font-size:14px;font-weight:800;cursor:pointer;font-family:inherit;}
        .yearsel{padding:8px 11px;border:1.5px solid var(--border);border-radius:9px;font-family:inherit;font-size:13px;background:#fff;}
        .empty{text-align:center;color:var(--muted);padding:26px;}
        @media(max-width:560px){.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="Leave Balances">ໂຄຕາລາພັກ</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">Back</span></a>
    </div>
</div>

<div class="page">
    <h1 data-lo="ໂຄຕາລາພັກປະຈຳປີ" data-en="Annual Leave Balances">Annual Leave Balances</h1>
    <p class="sub" data-lo="ກຳນົດຈຳນວນວັນລາພັກປະຈຳປີຂອງແຕ່ລະຄົນ (ປົກກະຕິ 15 ວັນ/ປີ). ‘ໃຊ້ໄປ’ ນັບສະເພາະລາພັກປະຈຳປີທີ່ອະນຸມັດແລ້ວ."
       data-en="Set each person's annual leave days (usually 15/year). ‘Used’ counts only approved annual leave.">
       Set each person's annual leave days; Used counts approved annual leave.</p>

    <form method="GET" style="margin-bottom:14px;">
        <label style="font-size:13px;font-weight:700;color:var(--muted);" data-lo="ປີ:" data-en="Year:">Year:</label>
        <select class="yearsel" 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>
    </form>

    <?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; ?>

    <form method="POST">
        <input type="hidden" name="action" value="save">
        <div class="card">
            <div class="tbl-wrap">
            <table>
                <thead><tr>
                    <th data-lo="ພະນັກງານ" data-en="Staff">Staff</th>
                    <th class="num" data-lo="ວັນ/ປີ" data-en="Days/year">Days/year</th>
                    <th class="num" data-lo="ໃຊ້ໄປ" data-en="Used">Used</th>
                    <th class="num" data-lo="ຍັງເຫຼືອ" data-en="Remaining">Remaining</th>
                </tr></thead>
                <tbody>
                <?php if (!$staff): ?>
                    <tr><td colspan="4" class="empty" data-lo="ບໍ່ມີພະນັກງານ." data-en="No staff.">No staff.</td></tr>
                <?php else: foreach ($staff as $p):
                    $uid=(int)$p['id']; $ent=(int)$p['entitle']; $usd=$usedMap[$uid]??0; $rem=max(0,$ent-$usd);
                ?>
                    <tr>
                        <td>
                            <input type="hidden" name="ids[]" value="<?= $uid ?>">
                            <div class="nm"><?= htmlspecialchars($p['name']) ?></div>
                            <?php if ($p['position']||$p['department']): ?><div class="sb"><?= htmlspecialchars(trim(($p['position']??'').' · '.($p['department']??''),' ·')) ?></div><?php endif; ?>
                        </td>
                        <td class="num"><input type="number" name="days[<?= $uid ?>]" value="<?= $ent ?>" min="0" max="60"></td>
                        <td class="num used"><?= $usd ?></td>
                        <td class="num left"><?= $rem ?></td>
                    </tr>
                <?php endforeach; endif; ?>
                </tbody>
            </table>
            </div>
            <?php if ($staff): ?>
            <div class="bar">
                <button class="btn" type="submit" data-lo="💾 ບັນທຶກ" data-en="💾 Save">💾 Save</button>
                <span class="sb" data-lo="ປ່ຽນແປງຈະນຳໃຊ້ກັບໂຄຕາຂອງພະນັກງານທັນທີ." data-en="Changes apply to staff balances immediately.">Changes apply immediately.</span>
            </div>
            <?php endif; ?>
        </div>
    </form>
</div>

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