<?php
/* ============================================================================
 *  staff/loan.php — staff borrow money / advance.
 *  Request an amount + a monthly repayment for approval. After approval it is
 *  auto-deducted from salary each cycle. Staff see paid vs. remaining + history.
 *  Bilingual EN/Lao.
 * ==========================================================================*/
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"];

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $act = $_POST["action"] ?? '';
    try {
        if ($act === "request") {
            $amount  = (float)str_replace(',', '', $_POST["amount"] ?? '0');
            $monthly = (float)str_replace(',', '', $_POST["monthly_payment"] ?? '0');
            $reason  = trim($_POST["reason"] ?? '');
            if ($amount <= 0)  throw new Exception("Enter the amount you want to borrow.");
            if ($monthly <= 0) throw new Exception("Enter how much to repay per month.");
            if ($monthly > $amount) throw new Exception("Monthly repayment can't be more than the total.");
            $isOwner    = appr_is_owner($pdo, $companyId, $userId);   // owner requests auto-approve
            $initStatus = $isOwner ? "approved" : "pending";
            $pdo->prepare("INSERT INTO hr_loans (company_id, staff_id, amount, monthly_payment, remaining, reason, status, created_at, approved_at)
                           VALUES (?,?,?,?,?,?, ?, NOW(), ".($isOwner?"NOW()":"NULL").")")
                ->execute([$companyId, $userId, $amount, $monthly, $amount, $reason, $initStatus]);
            $_SESSION["ln_flash"] = $isOwner
                ? ["ok","Loan recorded (auto-approved as owner).","ບັນທຶກການກູ້ (ອະນຸມັດອັດຕະໂນມັດ)."]
                : ["ok","Loan request sent for approval.","ສົ່ງຄຳຂໍກູ້ຢືມເພື່ອອະນຸມັດແລ້ວ."];
            if (!$isOwner) {
                $who = $_SESSION["name"] ?? "A staff member";
                foreach (approvers_for_staff($pdo,$companyId,$userId) as $aid) {
                    notify_user($pdo,$aid,"💳 New loan request", $who." requested ₭".number_format($amount,0)." to borrow.","company/loans.php");
                }
            }
        } elseif ($act === "cancel") {
            $pdo->prepare("DELETE FROM hr_loans WHERE id=? AND staff_id=? AND status='pending'")
                ->execute([(int)($_POST["loan_id"] ?? 0), $userId]);
            $_SESSION["ln_flash"] = ["ok","Request cancelled.","ຍົກເລີກຄຳຂໍແລ້ວ."];
        }
    } catch (Throwable $e) {
        $_SESSION["ln_flash"] = ["err","Error: ".$e->getMessage(),"ຜິດພາດ: ".$e->getMessage()];
    }
    header("Location: loan.php"); exit;
}

$loans = $pdo->prepare("SELECT * FROM hr_loans WHERE staff_id=? AND company_id=? ORDER BY created_at DESC");
$loans->execute([$userId, $companyId]);
$loans = $loans->fetchAll(PDO::FETCH_ASSOC);

$outstanding = 0;
foreach ($loans as $l) if ($l['status']==='approved') $outstanding += (float)$l['remaining'];

$flash = $_SESSION["ln_flash"] ?? null; unset($_SESSION["ln_flash"]);
function kip($n){ return number_format((float)$n, 0); }
function stColor($s){ return $s==='approved'?'green':($s==='rejected'?'red':($s==='completed'?'blue':($s==='pending'?'amber':'gray'))); }
?>
<!DOCTYPE html>
<html lang="lo">
<head>
    <?php $pwaTheme='#0f766e'; include __DIR__.'/../config/pwa_head.php'; ?>
    <title>Borrow Money</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;}
        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)) 16px 12px;display:flex;justify-content:space-between;
            align-items:center;gap:10px;position:sticky;top:0;z-index:100;box-shadow:0 1px 6px rgba(15,23,42,.06);}
        .back-link{display:inline-flex;align-items:center;gap:6px;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{max-width:560px;margin:auto;padding:16px;}
        h1{font-size:19px;font-weight:800;margin-bottom:12px;}
        .flash{padding:12px 16px;border-radius:10px;margin-bottom:14px;font-size:14px;font-weight:600;}
        .flash.ok{background:var(--green-lt);color:#15803d;}.flash.err{background:var(--red-lt);color:var(--red);}
        .out{background:linear-gradient(135deg,#042f2e,#0f766e);border-radius:16px;padding:18px;color:#fff;margin-bottom:16px;text-align:center;}
        .out .l{font-size:12px;color:rgba(255,255,255,.78);text-transform:uppercase;letter-spacing:.5px;font-weight:700;}
        .out .v{font-size:30px;font-weight:800;margin-top:4px;}
        .sec-title{font-size:12px;font-weight:800;color:var(--muted);text-transform:uppercase;letter-spacing:.5px;margin:6px 0 10px;}
        .formcard{background:var(--surface);border:1px solid var(--border);border-radius:16px;padding:18px;box-shadow:0 2px 14px rgba(15,23,42,.06);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:11px 12px;border:1.5px solid var(--border);border-radius:10px;font-size:15px;font-family:inherit;}
        .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;}
        .loan{background:var(--surface);border:1px solid var(--border);border-radius:14px;padding:14px;margin-bottom:12px;box-shadow:0 2px 14px rgba(15,23,42,.06);}
        .loan .top{display:flex;justify-content:space-between;align-items:flex-start;gap:8px;margin-bottom:8px;}
        .loan .amt{font-size:18px;font-weight:800;}
        .loan .rs{font-size:12px;color:var(--muted);margin-top:2px;}
        .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.blue{background:var(--blue-lt);color:#1e40af;}.tag.gray{background:#f1f5f9;color:var(--muted);}
        .meterrow{display:flex;justify-content:space-between;font-size:13px;margin:8px 0 4px;}
        .meterrow .paid{color:#15803d;font-weight:700;}.meterrow .left{color:var(--red);font-weight:700;}
        .bar{height:9px;background:#eef2f6;border-radius:999px;overflow:hidden;margin-bottom:8px;}
        .bar > span{display:block;height:100%;background:#16a34a;}
        .ln-meta{font-size:12px;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;}
        .hist{margin-top:8px;font-size:12px;color:var(--muted);}
        .hist .h{padding:3px 0;border-top:1px solid var(--border);display:flex;justify-content:space-between;}
        .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="Borrow Money">Borrow Money</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; ?>

    <div class="out">
        <div class="l" data-lo="ຍັງຄ້າງຊຳລະ" data-en="Outstanding balance">Outstanding balance</div>
        <div class="v">₭ <?= kip($outstanding) ?></div>
    </div>

    <div class="sec-title" data-lo="ຂໍກູ້ຢືມໃໝ່" data-en="Request a new loan">Request a new loan</div>
    <div class="formcard">
        <form method="POST">
            <input type="hidden" name="action" value="request">
            <div class="fg">
                <label data-lo="ຈຳນວນທີ່ຕ້ອງການກູ້ (₭)" data-en="Amount to borrow (₭)">Amount to borrow (₭)</label>
                <input type="text" inputmode="numeric" name="amount" oninput="fmt(this)" placeholder="e.g. 2,000,000" required>
            </div>
            <div class="fg">
                <label data-lo="ຊຳລະຕໍ່ເດືອນ (₭)" data-en="Repay per month (₭)">Repay per month (₭)</label>
                <input type="text" inputmode="numeric" name="monthly_payment" oninput="fmt(this)" placeholder="e.g. 500,000" required>
                <div class="small" data-lo="ຈະຫັກຈາກເງິນເດືອນທຸກຮອບ ຈົນກວ່າຈະໝົດ." data-en="Deducted from salary each cycle until fully paid.">Deducted from salary each cycle until fully paid.</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>

    <div class="sec-title" data-lo="ການກູ້ຢືມຂອງຂ້ອຍ" data-en="My loans">My loans</div>
    <?php if (!$loans): ?>
        <div class="empty" data-lo="ຍັງບໍ່ມີການກູ້ຢືມ." data-en="No loans yet.">No loans yet.</div>
    <?php else: foreach ($loans as $l):
        $amount=(float)$l['amount']; $rem=(float)$l['remaining'];
        $paid = max(0, $amount - $rem);
        $pct  = $amount>0 ? min(100, round($paid/$amount*100)) : 0;
        $st=$l['status']; $cls=stColor($st);
        $hist=$pdo->prepare("SELECT period_start, amount FROM hr_loan_payments WHERE loan_id=? ORDER BY period_start DESC LIMIT 12");
        $hist->execute([(int)$l['id']]); $hist=$hist->fetchAll(PDO::FETCH_ASSOC);
    ?>
        <div class="loan">
            <div class="top">
                <div>
                    <div class="amt">₭ <?= kip($amount) ?></div>
                    <div class="rs"><span data-lo="ຊຳລະ/ເດືອນ" data-en="Monthly">Monthly</span>: ₭ <?= kip($l['monthly_payment']) ?><?php if (!empty($l['reason'])): ?> · <?= htmlspecialchars($l['reason']) ?><?php endif; ?></div>
                </div>
                <span class="tag <?= $cls ?>"
                      data-lo="<?= $st==='approved'?'ກຳລັງຊຳລະ':($st==='rejected'?'ປະຕິເສດ':($st==='completed'?'ຊຳລະໝົດ':($st==='pending'?'ລໍຖ້າ':$st))) ?>"
                      data-en="<?= $st==='approved'?'Repaying':ucfirst($st) ?>"><?= $st==='approved'?'Repaying':ucfirst($st) ?></span>
            </div>

            <?php if (in_array($st,['approved','completed'])): ?>
                <div class="meterrow">
                    <span class="paid"><span data-lo="ຊຳລະແລ້ວ" data-en="Paid">Paid</span>: ₭ <?= kip($paid) ?></span>
                    <span class="left"><span data-lo="ຍັງເຫຼືອ" data-en="Left">Left</span>: ₭ <?= kip($rem) ?></span>
                </div>
                <div class="bar"><span style="width:<?= $pct ?>%"></span></div>
                <div class="ln-meta"><?= $pct ?>% <span data-lo="ຊຳລະແລ້ວ" data-en="paid">paid</span></div>

                <?php if ($hist): ?>
                <div class="hist">
                    <?php foreach ($hist as $h): ?>
                        <div class="h"><span><?= date('d/m/Y', strtotime($h['period_start'])) ?></span><span>− ₭ <?= kip($h['amount']) ?></span></div>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>
            <?php endif; ?>

            <?php if ($st==='pending'): ?>
            <form method="POST" onsubmit="return confirm('Cancel this loan request?')">
                <input type="hidden" name="action" value="cancel">
                <input type="hidden" name="loan_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 fmt(el){ var raw=el.value.replace(/[^\d]/g,''); el.value = raw ? Number(raw).toLocaleString('en-US') : ''; }
</script>

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