<?php
/* ============================================================================
 *  staff/leave.php — paperless leave for staff.
 *  Annual-leave balance + request forms (Annual, Sick, Short-term hourly) +
 *  my requests with cancel. Bilingual EN/Lao · Flatpickr · dd/mm/yyyy.
 * ==========================================================================*/
session_start();
if (!isset($_SESSION["user_id"]) || empty($_SESSION["company_id"])) {
    header("Location: ../auth/login.php"); exit;
}
require_once '../config/database.php';
require_once '../config/notify.php';
require_once '../config/approvals.php';
date_default_timezone_set('Asia/Vientiane');

$userId    = (int)$_SESSION["user_id"];
$companyId = (int)$_SESSION["company_id"];
$year      = (int)date('Y');

/* Old ENUM columns can reject valid values ("Data truncated for column ...").
   Widen leave_type and status to VARCHAR so all values fit. Runs once. */
foreach (['leave_type' => "VARCHAR(20) NOT NULL DEFAULT 'annual'",
          'status'     => "VARCHAR(20) NOT NULL DEFAULT 'pending'"] as $col => $ddl) {
    try {
        $c = $pdo->query("SHOW COLUMNS FROM hr_leave LIKE ".$pdo->quote($col))->fetch(PDO::FETCH_ASSOC);
        if ($c && stripos((string)$c['Type'], 'varchar') === false) {
            $pdo->exec("ALTER TABLE hr_leave MODIFY COLUMN `$col` $ddl");
        }
    } catch (Throwable $e) {}
}

/* ── POST ── */
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $act = $_POST["action"] ?? '';
    try {
        if ($act === "request") {
            $type   = $_POST["leave_type"] ?? '';
            $reason = trim($_POST["reason"] ?? '');
            $allowed = ["annual","sick","short"];
            if (!in_array($type,$allowed)) throw new Exception("Invalid leave type.");
            $isOwner    = appr_is_owner($pdo, $companyId, $userId);   // owner requests auto-approve
            $initStatus = $isOwner ? "approved" : "pending";

            if ($type === "short") {
                $date = $_POST["sdate"] ?? '';
                $from = $_POST["from_time"] ?? '';
                $to   = $_POST["to_time"] ?? '';
                if (!preg_match('/^\d{4}-\d{2}-\d{2}$/',$date) || !$from || !$to) throw new Exception("Pick a date and from/to time.");
                if (strtotime($to) <= strtotime($from)) throw new Exception("End time must be after start time.");
                $hours = round((strtotime($to)-strtotime($from))/3600, 2);
                $pdo->prepare("INSERT INTO hr_leave (staff_id,company_id,leave_type,start_date,end_date,is_hourly,start_time,end_time,hours,days,reason,status,created_at)
                               VALUES (?,?,?,?,?,1,?,?,?,0,?, ?, NOW())")
                    ->execute([$userId,$companyId,$type,$date,$date,$from,$to,$hours,$reason,$initStatus]);
                $_SESSION["lv_flash"]=["ok","Short-term leave requested.","ສົ່ງຄຳຂໍລາໄລຍະສັ້ນແລ້ວ."];
            } else {
                $start = $_POST["start_date"] ?? '';
                $end   = $_POST["end_date"] ?? '';
                if (!preg_match('/^\d{4}-\d{2}-\d{2}$/',$start) || !preg_match('/^\d{4}-\d{2}-\d{2}$/',$end)) throw new Exception("Pick start and end dates.");
                if (strtotime($end) < strtotime($start)) throw new Exception("End date must be after start date.");
                $days = (int)floor((strtotime($end)-strtotime($start))/86400) + 1;

                if ($type === "annual") {
                    /* check remaining balance */
                    $ent = $pdo->prepare("SELECT annual_leave_days FROM company_staff WHERE user_id=? AND company_id=? LIMIT 1");
                    $ent->execute([$userId,$companyId]);
                    $entitle = $ent->fetchColumn();
                    $entitle = ($entitle === null || $entitle === false) ? 15 : (int)$entitle;
                    $usedQ = $pdo->prepare("SELECT COALESCE(SUM(days),0) FROM hr_leave WHERE staff_id=? AND company_id=? AND leave_type='annual' AND status='approved' AND YEAR(start_date)=?");
                    $usedQ->execute([$userId,$companyId,$year]);
                    $used = (int)$usedQ->fetchColumn();
                    if ($days > ($entitle - $used)) throw new Exception("Not enough annual leave left. Remaining: ".($entitle-$used)." day(s).");
                }
                $pdo->prepare("INSERT INTO hr_leave (staff_id,company_id,leave_type,start_date,end_date,is_hourly,days,reason,status,created_at)
                               VALUES (?,?,?,?,?,0,?,?, ?, NOW())")
                    ->execute([$userId,$companyId,$type,$start,$end,$days,$reason,$initStatus]);
                $_SESSION["lv_flash"]= $isOwner
                    ? ["ok","Leave recorded (auto-approved as owner).","ບັນທຶກລາພັກ (ອະນຸມັດອັດຕະໂນມັດ)."]
                    : ["ok","Leave requested.","ສົ່ງຄຳຂໍລາພັກແລ້ວ."];
            }
            /* alert the approver(s) — not needed for the owner's own auto-approved request */
            if (!$isOwner) {
                $who = $_SESSION["name"] ?? "A staff member";
                foreach (approvers_for_staff($pdo,$companyId,$userId) as $aid) {
                    notify_user($pdo,$aid,"🏖️ New leave request", $who." submitted a leave request.","company/hr_leave.php");
                }
            }
        }
        elseif ($act === "cancel") {
            $id = (int)($_POST["leave_id"] ?? 0);
            $pdo->prepare("DELETE FROM hr_leave WHERE id=? AND staff_id=? AND status='pending'")->execute([$id,$userId]);
            $_SESSION["lv_flash"]=["ok","Request cancelled.","ຍົກເລີກຄຳຂໍແລ້ວ."];
        }
    } catch (Throwable $e) {
        $_SESSION["lv_flash"]=["err","Error: ".$e->getMessage(),"ຜິດພາດ: ".$e->getMessage()];
    }
    header("Location: leave.php"); exit;
}

/* ── balance ── */
$ent = $pdo->prepare("SELECT annual_leave_days FROM company_staff WHERE user_id=? AND company_id=? LIMIT 1");
$ent->execute([$userId,$companyId]);
$entitle = $ent->fetchColumn();
$entitle = ($entitle === null || $entitle === false) ? 15 : (int)$entitle;
$usedQ = $pdo->prepare("SELECT COALESCE(SUM(days),0) FROM hr_leave WHERE staff_id=? AND company_id=? AND leave_type='annual' AND status='approved' AND YEAR(start_date)=?");
$usedQ->execute([$userId,$companyId,$year]);
$used = (int)$usedQ->fetchColumn();
$remain = max(0, $entitle - $used);

/* ── my requests ── */
$mine = $pdo->prepare("SELECT * FROM hr_leave WHERE staff_id=? AND company_id=? ORDER BY created_at DESC LIMIT 60");
$mine->execute([$userId,$companyId]);
$mine = $mine->fetchAll(PDO::FETCH_ASSOC);

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

$typeMeta = [
    'annual'=>['🏖️','Annual','ລາພັກປະຈຳປີ'],
    'sick'  =>['🤒','Sick','ລາປ່ວຍ'],
    'short' =>['⏱️','Short-term','ລາໄລຍະສັ້ນ'],
    'unpaid'=>['💸','Unpaid','ລາບໍ່ຮັບເງິນ'],
    'maternity'=>['🤱','Maternity','ລາເກີດລູກ'],
    'other' =>['📋','Other','ອື່ນໆ'],
];
function stColor($s){ return $s==='approved'?'green':($s==='rejected'?'red':($s==='pending'?'amber':'gray')); }
?>
<!DOCTYPE html>
<html lang="lo">
<head>
    <?php $pwaTheme='#0f766e'; include __DIR__.'/../config/pwa_head.php'; ?>
    <title>My Leave — <?= htmlspecialchars($_SESSION["company_name"]) ?></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;--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:calc(12px + env(safe-area-inset-top,0px)) 18px 12px;display:flex;justify-content:space-between;
            align-items:center;gap:12px;position:sticky;top:0;z-index:100;box-shadow:0 1px 6px rgba(15,23,42,.06);}
        .back-link{background:#f1f5f9;color:var(--text);border:1.5px solid var(--border);padding:7px 13px;border-radius:8px;text-decoration:none;font-size:13px;font-weight:700;}
        .lang-bar{display:flex;gap:7px;}
        .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;}
        .page{padding:18px 16px;max-width:560px;margin:auto;}
        h1{font-size:20px;font-weight:800;margin-bottom:14px;}
        .bal{display:grid;grid-template-columns:1fr 1fr 1fr;gap:10px;margin-bottom:18px;}
        .bcard{background:var(--surface);border:1px solid var(--border);border-radius:14px;padding:16px 10px;text-align:center;box-shadow:var(--shadow);}
        .bcard .v{font-size:26px;font-weight:800;line-height:1;}
        .bcard .l{font-size:11px;color:var(--muted);font-weight:600;margin-top:4px;}
        .bcard.tot .v{color:var(--text);}.bcard.used .v{color:var(--amber);}.bcard.left .v{color:var(--green);}
        .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);}
        .tabs{display:flex;gap:8px;margin-bottom:14px;}
        .tab{flex:1;padding:11px;border-radius:12px;border:1.5px solid var(--border);background:var(--surface);
            font-size:13px;font-weight:800;color:var(--muted);cursor:pointer;font-family:inherit;text-align:center;}
        .tab.active{background:var(--primary);border-color:var(--primary);color:#fff;}
        .formcard{background:var(--surface);border:1px solid var(--border);border-radius:16px;padding:18px;box-shadow:var(--shadow);margin-bottom:20px;}
        .fg{margin-bottom:14px;}
        .fg label{display:block;font-size:12px;font-weight:700;color:#374151;margin-bottom:5px;}
        .fg input,.fg textarea{width:100%;padding:10px 12px;border:1.5px solid var(--border);border-radius:10px;font-size:14px;font-family:inherit;}
        .frow{display:flex;gap:10px;}.frow .fg{flex:1;}
        .pane{display:none;}.pane.active{display:block;}
        .btn{width:100%;padding:14px;border:none;border-radius:12px;background:var(--primary);color:#fff;font-size:15px;font-weight:800;cursor:pointer;font-family:inherit;}
        .small{font-size:12px;color:var(--muted);margin-top:-6px;margin-bottom:12px;}
        .req{background:var(--surface);border:1px solid var(--border);border-radius:14px;padding:14px;margin-bottom:10px;box-shadow:var(--shadow);}
        .req .top{display:flex;justify-content:space-between;align-items:flex-start;gap:8px;}
        .req .ty{font-weight:800;font-size:14px;}
        .req .dt{font-size:13px;color:var(--text);margin-top:3px;}
        .req .rs{font-size:12px;color:var(--muted);margin-top:4px;}
        .tag{display:inline-block;padding:3px 10px;border-radius:999px;font-size:11px;font-weight:800;}
        .tag.green{background:var(--green-lt);color:#15803d;}.tag.red{background:var(--red-lt);color:#991b1b;}
        .tag.amber{background:var(--amber-lt);color:#92400e;}.tag.gray{background:#f1f5f9;color:var(--muted);}
        .cancel{margin-top:8px;background:var(--red-lt);color:var(--red);border:1.5px solid #fca5a5;border-radius:8px;padding:6px 12px;font-size:12px;font-weight:700;cursor:pointer;font-family:inherit;}
        .sec-title{font-size:12px;font-weight:800;color:var(--muted);text-transform:uppercase;letter-spacing:.5px;margin:6px 0 12px;}
        .empty{color:var(--muted);font-size:13px;text-align:center;padding:18px;}
    </style>
</head>
<body>

<div class="top-bar">
    <a class="back-link" href="../customer/company_home.php">← <span data-lo="ກັບຄືນ" data-en="Back">Back</span></a>
    <div class="lang-bar">
        <button class="lang-btn" id="btn-lo" onclick="setLang('lo')">🇱🇦 ລາວ</button>
        <button class="lang-btn" id="btn-en" onclick="setLang('en')">🇬🇧 EN</button>
    </div>
</div>

<div class="page">
    <h1 data-lo="ການລາພັກຂອງຂ້ອຍ" data-en="My Leave">My Leave</h1>

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

    <!-- balance -->
    <div class="bal">
        <div class="bcard tot"><div class="v"><?= $entitle ?></div><div class="l" data-lo="ລາພັກປະຈຳປີ" data-en="Annual total">Annual total</div></div>
        <div class="bcard used"><div class="v"><?= $used ?></div><div class="l" data-lo="ໃຊ້ໄປແລ້ວ" data-en="Used">Used</div></div>
        <div class="bcard left"><div class="v"><?= $remain ?></div><div class="l" data-lo="ຍັງເຫຼືອ" data-en="Remaining">Remaining</div></div>
    </div>
    <div class="small" style="text-align:center" data-lo="ປີ <?= $year ?> · ນັບສະເພາະລາພັກປະຈຳປີທີ່ອະນຸມັດແລ້ວ" data-en="Year <?= $year ?> · counts approved annual leave only">Year <?= $year ?> · approved annual leave only</div>

    <!-- request -->
    <div class="sec-title" data-lo="ສົ່ງຄຳຂໍລາພັກ" data-en="Request leave">Request leave</div>
    <div class="tabs">
        <button class="tab active" data-tab="annual" onclick="showTab('annual')">🏖️ <span data-lo="ປະຈຳປີ" data-en="Annual">Annual</span></button>
        <button class="tab" data-tab="sick" onclick="showTab('sick')">🤒 <span data-lo="ປ່ວຍ" data-en="Sick">Sick</span></button>
        <button class="tab" data-tab="short" onclick="showTab('short')">⏱️ <span data-lo="ສັ້ນ" data-en="Short">Short</span></button>
    </div>

    <div class="formcard">
        <!-- Annual -->
        <form method="POST" class="pane active" id="pane-annual">
            <input type="hidden" name="action" value="request">
            <input type="hidden" name="leave_type" value="annual">
            <div class="frow">
                <div class="fg"><label data-lo="ແຕ່ວັນທີ" data-en="From date">From date</label>
                    <input type="text" class="fp-date" placeholder="dd/mm/yyyy" required><input type="hidden" name="start_date"></div>
                <div class="fg"><label data-lo="ຫາວັນທີ" data-en="To date">To date</label>
                    <input type="text" class="fp-date" placeholder="dd/mm/yyyy" required><input type="hidden" name="end_date"></div>
            </div>
            <div class="small" data-lo="ຈະຫັກອອກຈາກລາພັກປະຈຳປີຂອງທ່ານ." data-en="This is deducted from your annual balance.">Deducted from your annual balance.</div>
            <div class="fg"><label data-lo="ເຫດຜົນ" data-en="Reason">Reason</label><textarea name="reason" rows="2" data-lo-placeholder="ເຫດຜົນ..." data-en-placeholder="Reason..."></textarea></div>
            <button class="btn" type="submit" data-lo="ສົ່ງຄຳຂໍ" data-en="Submit request">Submit request</button>
        </form>
        <!-- Sick -->
        <form method="POST" class="pane" id="pane-sick">
            <input type="hidden" name="action" value="request">
            <input type="hidden" name="leave_type" value="sick">
            <div class="frow">
                <div class="fg"><label data-lo="ແຕ່ວັນທີ" data-en="From date">From date</label>
                    <input type="text" class="fp-date" placeholder="dd/mm/yyyy" required><input type="hidden" name="start_date"></div>
                <div class="fg"><label data-lo="ຫາວັນທີ" data-en="To date">To date</label>
                    <input type="text" class="fp-date" placeholder="dd/mm/yyyy" required><input type="hidden" name="end_date"></div>
            </div>
            <div class="fg"><label data-lo="ເຫດຜົນ / ອາການ" data-en="Reason / symptoms">Reason / symptoms</label><textarea name="reason" rows="2"></textarea></div>
            <button class="btn" type="submit" data-lo="ສົ່ງຄຳຂໍ" data-en="Submit request">Submit request</button>
        </form>
        <!-- Short-term hourly -->
        <form method="POST" class="pane" id="pane-short">
            <input type="hidden" name="action" value="request">
            <input type="hidden" name="leave_type" value="short">
            <div class="fg"><label data-lo="ວັນທີ" data-en="Date">Date</label>
                <input type="text" class="fp-date" placeholder="dd/mm/yyyy" required><input type="hidden" name="sdate"></div>
            <div class="frow">
                <div class="fg"><label data-lo="ແຕ່ເວລາ" data-en="From time">From time</label><input type="text" class="fp-time" name="from_time" placeholder="09:00" required></div>
                <div class="fg"><label data-lo="ຫາເວລາ" data-en="To time">To time</label><input type="text" class="fp-time" name="to_time" placeholder="11:00" required></div>
            </div>
            <div class="fg"><label data-lo="ເຫດຜົນ" data-en="Reason">Reason</label><textarea name="reason" rows="2"></textarea></div>
            <button class="btn" type="submit" data-lo="ສົ່ງຄຳຂໍ" data-en="Submit request">Submit request</button>
        </form>
    </div>

    <!-- history -->
    <div class="sec-title" data-lo="ຄຳຂໍຂອງຂ້ອຍ" data-en="My requests">My requests</div>
    <?php if (!$mine): ?>
        <div class="empty" data-lo="ຍັງບໍ່ມີຄຳຂໍລາພັກ." data-en="No leave requests yet.">No leave requests yet.</div>
    <?php else: foreach ($mine as $l):
        $tm = $typeMeta[$l['leave_type']] ?? ['📋',ucfirst($l['leave_type']),$l['leave_type']];
        $st = $l['status']; $cls = stColor($st);
    ?>
        <div class="req">
            <div class="top">
                <div>
                    <div class="ty"><?= $tm[0] ?> <span data-lo="<?= $tm[2] ?>" data-en="<?= $tm[1] ?>"><?= $tm[1] ?></span></div>
                    <div class="dt">
                        <?php if ((int)($l['is_hourly']??0)): ?>
                            <?= date('d/m/Y',strtotime($l['start_date'])) ?> · <?= substr($l['start_time'],0,5) ?>–<?= substr($l['end_time'],0,5) ?>
                            (<?= rtrim(rtrim(number_format((float)$l['hours'],1),'0'),'.') ?>h)
                        <?php else: ?>
                            <?= date('d/m/Y',strtotime($l['start_date'])) ?> – <?= date('d/m/Y',strtotime($l['end_date'])) ?>
                            (<?= (int)$l['days'] ?> <span data-lo="ວັນ" data-en="d">d</span>)
                        <?php endif; ?>
                    </div>
                    <?php if (!empty($l['reason'])): ?><div class="rs"><?= htmlspecialchars($l['reason']) ?></div><?php endif; ?>
                </div>
                <span class="tag <?= $cls ?>"
                      data-lo="<?= $st==='approved'?'ອະນຸມັດ':($st==='rejected'?'ປະຕິເສດ':($st==='pending'?'ລໍຖ້າ':$st)) ?>"
                      data-en="<?= ucfirst($st) ?>"><?= ucfirst($st) ?></span>
            </div>
            <?php if ($st==='pending'): ?>
            <form method="POST" onsubmit="return confirm('Cancel this request?')">
                <input type="hidden" name="action" value="cancel">
                <input type="hidden" name="leave_id" value="<?= (int)$l['id'] ?>">
                <button class="cancel" type="submit" data-lo="ຍົກເລີກ" data-en="Cancel">Cancel</button>
            </form>
            <?php endif; ?>
        </div>
    <?php endforeach; endif; ?>
</div>

<script>
function showTab(t){
    document.querySelectorAll('.tab').forEach(b=>b.classList.toggle('active',b.dataset.tab===t));
    document.querySelectorAll('.pane').forEach(p=>p.classList.toggle('active',p.id==='pane-'+t));
}
document.addEventListener('DOMContentLoaded',function(){
    if (typeof flatpickr==='undefined') return;
    document.querySelectorAll('.fp-date').forEach(function(inp){
        const hidden = inp.nextElementSibling;
        flatpickr(inp,{dateFormat:'d/m/Y', onChange:function(sel,str,fp){ hidden.value = sel[0]?fp.formatDate(sel[0],'Y-m-d'):''; }});
    });
    document.querySelectorAll('.fp-time').forEach(function(inp){
        flatpickr(inp,{enableTime:true,noCalendar:true,dateFormat:'H:i',time_24hr:true,minuteIncrement:5});
    });
});
</script>

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