<?php
/* ============================================================================
 *  company/loans.php — manager view of staff loans / borrowed money.
 *  Approve / reject requests, and track paid vs. remaining for each loan.
 *  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';
require_once '../config/approvals.php';

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

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    try {
        $id  = (int)($_POST["loan_id"] ?? 0);
        $act = $_POST["action"] ?? '';
        $r = $pdo->prepare("SELECT staff_id, status FROM hr_loans WHERE id=? AND company_id=? LIMIT 1");
        $r->execute([$id, $companyId]); $req = $r->fetch(PDO::FETCH_ASSOC);
        if (!$req) { /* gone */ }
        elseif (appr_enabled($pdo, $companyId)) {
            $staff = (int)$req['staff_id'];
            $ctx = appr_ctx($pdo, $companyId, $me, $staff);
            if ($act === "reject" && appr_can_reject($req['status'], $ctx)) {
                $pdo->prepare("UPDATE hr_loans SET status='rejected', reviewed_by=? WHERE id=? AND company_id=?")->execute([$me,$id,$companyId]);
                notify_user($pdo,$staff,"❌ Loan rejected","Your borrow request was rejected.","staff/loan.php");
                $_SESSION["lm_flash"] = ["ok","Loan rejected.","ປະຕິເສດການກູ້ຢືມແລ້ວ."];
            } elseif ($act === "approve" && ($next = appr_next($req['status'], $ctx))) {
                if ($next === 'dept_ok') {
                    $pdo->prepare("UPDATE hr_loans SET status='dept_ok', dept_reviewed_by=?, dept_reviewed_at=NOW() WHERE id=? AND company_id=?")->execute([$me,$id,$companyId]);
                    if ($ctx['ops']) notify_user($pdo,$ctx['ops'],"💳 Loan needs final approval","A borrow request passed the department manager.","company/loans.php");
                    $_SESSION["lm_flash"] = ["ok","Approved — sent to the Operation Manager.","ອະນຸມັດແລ້ວ — ສົ່ງຫາຜູ້ຈັດການ."];
                } else {
                    $pdo->prepare("UPDATE hr_loans SET status='approved', remaining=amount, reviewed_by=?, mgr_reviewed_by=?, approved_at=NOW() WHERE id=? AND company_id=?")->execute([$me,$me,$id,$companyId]);
                    notify_user($pdo,$staff,"✅ Loan approved","Your borrow request was approved.","staff/loan.php");
                    $_SESSION["lm_flash"] = ["ok","Loan approved.","ອະນຸມັດການກູ້ຢືມແລ້ວ."];
                }
            } else {
                $_SESSION["lm_flash"] = ["err","You are not the approver for this request yet.","ທ່ານຍັງບໍ່ແມ່ນຜູ້ອະນຸມັດ."];
            }
        } else {
            /* one-step legacy */
            if ($act === "approve") {
                $pdo->prepare("UPDATE hr_loans SET status='approved', remaining=amount, reviewed_by=?, approved_at=NOW() WHERE id=? AND company_id=? AND status='pending'")->execute([$me,$id,$companyId]);
                notify_user($pdo,(int)$req['staff_id'],"✅ Loan approved","Your borrow request was approved.","staff/loan.php");
                $_SESSION["lm_flash"] = ["ok","Loan approved.","ອະນຸມັດການກູ້ຢືມແລ້ວ."];
            } elseif ($act === "reject") {
                $pdo->prepare("UPDATE hr_loans SET status='rejected', reviewed_by=? WHERE id=? AND company_id=? AND status='pending'")->execute([$me,$id,$companyId]);
                notify_user($pdo,(int)$req['staff_id'],"❌ Loan rejected","Your borrow request was rejected.","staff/loan.php");
                $_SESSION["lm_flash"] = ["ok","Loan rejected.","ປະຕິເສດການກູ້ຢືມແລ້ວ."];
            }
        }
    } catch (Throwable $e) {
        $_SESSION["lm_flash"] = ["err","Error: ".$e->getMessage(),"ຜິດພາດ: ".$e->getMessage()];
    }
    header("Location: loans.php".(isset($_POST['view'])?"?view=".urlencode($_POST['view']):"")); exit;
}

$view = $_GET["view"] ?? "pending";
$valid = ['pending','active','completed','rejected'];
if (!in_array($view, $valid, true)) $view = "pending";
$statusFilter = $view === 'active' ? 'approved' : $view;

if ($view === 'pending') {
    $rows = $pdo->prepare("
        SELECT l.*, u.name AS staff_name, cs.position
        FROM hr_loans l
        JOIN users u ON u.id = l.staff_id
        LEFT JOIN company_staff cs ON cs.user_id = l.staff_id AND cs.company_id = l.company_id
        WHERE l.company_id=? AND l.status IN ('pending','dept_ok')
        ORDER BY l.created_at DESC LIMIT 300");
    $rows->execute([$companyId]);
} else {
    $rows = $pdo->prepare("
        SELECT l.*, u.name AS staff_name, cs.position
        FROM hr_loans l
        JOIN users u ON u.id = l.staff_id
        LEFT JOIN company_staff cs ON cs.user_id = l.staff_id AND cs.company_id = l.company_id
        WHERE l.company_id=? AND l.status=?
        ORDER BY l.created_at DESC LIMIT 300");
    $rows->execute([$companyId, $statusFilter]);
}
$rows = $rows->fetchAll(PDO::FETCH_ASSOC);

/* counts + totals */
$cnt = ['pending'=>0,'approved'=>0,'completed'=>0,'rejected'=>0,'dept_ok'=>0];
$cs = $pdo->prepare("SELECT status, COUNT(*) c FROM hr_loans WHERE company_id=? GROUP BY status");
$cs->execute([$companyId]);
foreach ($cs->fetchAll(PDO::FETCH_ASSOC) as $r) if (isset($cnt[$r['status']])) $cnt[$r['status']]=(int)$r['c'];
$cnt['pending'] += $cnt['dept_ok'];   // pending tab = both in-progress stages
$totalOut = (float)$pdo->query("SELECT COALESCE(SUM(remaining),0) FROM hr_loans WHERE company_id={$companyId} AND status='approved' AND remaining>0")->fetchColumn();

$flash = $_SESSION["lm_flash"] ?? null; unset($_SESSION["lm_flash"]);
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) ?> — Staff Loans</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: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:920px;margin:auto;}
        h1{font-size:20px;font-weight:800;margin-bottom:4px;}
        .sub{font-size:13px;color:var(--muted);margin-bottom:14px;}
        .out{display:inline-block;background:linear-gradient(135deg,#042f2e,#0f766e);color:#fff;border-radius:12px;padding:12px 18px;margin-bottom:14px;}
        .out .l{font-size:11px;color:rgba(255,255,255,.75);text-transform:uppercase;letter-spacing:.4px;font-weight:700;}
        .out .v{font-size:22px;font-weight:800;}
        .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:16px;flex-wrap:wrap;}
        .tab{padding:9px 15px;border-radius:999px;border:1.5px solid var(--border);background:var(--surface);text-decoration:none;font-size:13px;font-weight:700;color:var(--muted);display:inline-flex;gap:7px;align-items:center;}
        .tab.active{background:var(--primary);border-color:var(--primary);color:#fff;}
        .tab .b{background:rgba(0,0,0,.12);padding:1px 8px;border-radius:999px;font-size:11px;}
        .tab.active .b{background:rgba(255,255,255,.25);}
        .card{background:var(--surface);border:1px solid var(--border);border-radius:14px;box-shadow:0 2px 14px rgba(15,23,42,.06);padding:16px;margin-bottom:12px;}
        .ch{display:flex;justify-content:space-between;align-items:flex-start;gap:10px;}
        .nm{font-weight:800;font-size:15px;}.po{font-size:12px;color:var(--muted);}
        .vals{display:flex;gap:18px;flex-wrap:wrap;margin-top:10px;font-size:13px;}
        .vals b{font-weight:800;}
        .paid{color:#15803d;}.left{color:var(--red);}
        .bar{height:8px;background:#eef2f6;border-radius:999px;overflow:hidden;margin-top:10px;max-width:320px;}
        .bar>span{display:block;height:100%;background:#16a34a;}
        .rs{font-size:12px;color:var(--muted);margin-top:8px;}
        .actions{display:flex;gap:8px;margin-top:12px;}
        .btn{padding:9px 16px;border-radius:9px;border:none;font-size:13px;font-weight:700;cursor:pointer;font-family:inherit;}
        .btn-ok{background:var(--green);color:#fff;}.btn-no{background:var(--red-lt);color:var(--red);border:1.5px solid #fca5a5;}
        .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.blue{background:var(--blue-lt);color:#1e40af;}.tag.red{background:var(--red-lt);color:#991b1b;}.tag.amber{background:var(--amber-lt);color:#92400e;}
        .empty{text-align:center;color:var(--muted);padding:30px;}
    </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="Staff Loans">ການກູ້ຢືມພະນັກງານ</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="Staff Loans">Staff Loans</h1>
    <p class="sub" data-lo="ອະນຸມັດການກູ້ຢືມ ແລ້ວລະບົບຫັກຈາກເງິນເດືອນທຸກຮອບໂດຍອັດຕະໂນມັດ."
       data-en="Approve a loan and the system auto-deducts the monthly amount from salary each cycle.">Approve a loan and it auto-deducts monthly.</p>

    <div class="out"><div class="l" data-lo="ຍອດກູ້ຄ້າງທັງໝົດ" data-en="Total outstanding">Total outstanding</div><div class="v">₭ <?= kip($totalOut) ?></div></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; ?>

    <div class="tabs">
        <a class="tab <?= $view==='pending'?'active':'' ?>" href="?view=pending"><span data-lo="ລໍຖ້າ" data-en="Pending">Pending</span><span class="b"><?= $cnt['pending'] ?></span></a>
        <a class="tab <?= $view==='active'?'active':'' ?>" href="?view=active"><span data-lo="ກຳລັງຊຳລະ" data-en="Repaying">Repaying</span><span class="b"><?= $cnt['approved'] ?></span></a>
        <a class="tab <?= $view==='completed'?'active':'' ?>" href="?view=completed"><span data-lo="ໝົດແລ້ວ" data-en="Completed">Completed</span><span class="b"><?= $cnt['completed'] ?></span></a>
        <a class="tab <?= $view==='rejected'?'active':'' ?>" href="?view=rejected"><span data-lo="ປະຕິເສດ" data-en="Rejected">Rejected</span><span class="b"><?= $cnt['rejected'] ?></span></a>
    </div>

    <?php if (!$rows): ?>
        <div class="empty" data-lo="ບໍ່ມີລາຍການ." data-en="Nothing here.">Nothing here.</div>
    <?php else: foreach ($rows 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;
        /* payment history for this loan */
        $hist=$pdo->prepare("SELECT period_start, amount FROM hr_loan_payments WHERE loan_id=? ORDER BY period_start DESC LIMIT 24");
        $hist->execute([(int)$l['id']]); $hist=$hist->fetchAll(PDO::FETCH_ASSOC);
        /* this staff's existing outstanding across OTHER active loans (for pending review) */
        $oth=$pdo->prepare("SELECT COALESCE(SUM(remaining),0) c, COUNT(*) n FROM hr_loans WHERE company_id=? AND staff_id=? AND status='approved' AND remaining>0 AND id<>?");
        $oth->execute([$companyId,(int)$l['staff_id'],(int)$l['id']]);
        $othR=$oth->fetch(PDO::FETCH_ASSOC);
    ?>
        <div class="card">
            <div class="ch">
                <div>
                    <div class="nm"><?= htmlspecialchars($l['staff_name']) ?></div>
                    <?php if (!empty($l['position'])): ?><div class="po"><?= htmlspecialchars($l['position']) ?></div><?php endif; ?>
                </div>
                <?php
                    $st=$l['status'];
                    $tag = $st==='approved'?['blue','ກຳລັງຊຳລະ','Repaying']:($st==='completed'?['green','ໝົດແລ້ວ','Completed']:($st==='rejected'?['red','ປະຕິເສດ','Rejected']:($st==='dept_ok'?['blue','ລໍຖ້າ: ຜູ້ຈັດການ','Waiting: Operation Mgr']:['amber','ລໍຖ້າ: ຫົວໜ້າພະແນກ','Waiting: Dept Mgr'])));
                ?>
                <span class="tag <?= $tag[0] ?>" data-lo="<?= $tag[1] ?>" data-en="<?= $tag[2] ?>"><?= $tag[2] ?></span>
            </div>

            <div class="vals">
                <span><span data-lo="ຈຳນວນ" data-en="Amount">Amount</span>: <b>₭ <?= kip($amount) ?></b></span>
                <span><span data-lo="ຕໍ່ເດືອນ" data-en="Monthly">Monthly</span>: <b>₭ <?= kip($l['monthly_payment']) ?></b></span>
                <?php if (in_array($st,['approved','completed'])): ?>
                    <span class="paid"><span data-lo="ຊຳລະແລ້ວ" data-en="Paid">Paid</span>: <b>₭ <?= kip($paid) ?></b></span>
                    <span class="left"><span data-lo="ຍັງເຫຼືອ" data-en="Left">Left</span>: <b>₭ <?= kip($rem) ?></b></span>
                <?php endif; ?>
            </div>
            <?php if (in_array($st,['approved','completed'])): ?>
                <div class="bar"><span style="width:<?= $pct ?>%"></span></div>
            <?php endif; ?>
            <?php if (!empty($l['reason'])): ?><div class="rs">📝 <?= htmlspecialchars($l['reason']) ?></div><?php endif; ?>

            <?php if ($st==='pending' && (float)$othR['c'] > 0): ?>
                <div class="rs" style="color:#92400e;font-weight:700;background:#fef3c7;border-radius:8px;padding:8px 11px;display:inline-block;margin-top:8px;"
                     data-lo="⚠ ພະນັກງານນີ້ຍັງຄ້າງ ₭<?= kip($othR['c']) ?> ໃນ <?= (int)$othR['n'] ?> ການກູ້."
                     data-en="⚠ This staff already owes ₭<?= kip($othR['c']) ?> across <?= (int)$othR['n'] ?> loan(s).">⚠ Already owes ₭<?= kip($othR['c']) ?> across <?= (int)$othR['n'] ?> loan(s).</div>
            <?php endif; ?>

            <?php if ($hist): ?>
                <div class="rs" style="margin-top:10px;">
                    <strong data-lo="ປະຫວັດການຊຳລະ" data-en="Payment history">Payment history</strong>
                    <?php foreach ($hist as $h): ?>
                        <div style="display:flex;justify-content:space-between;padding:3px 0;border-top:1px solid var(--border);">
                            <span><?= date('d/m/Y', strtotime($h['period_start'])) ?></span><span>− ₭ <?= kip($h['amount']) ?></span>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>

            <?php
            $twoStep = appr_enabled($pdo,$companyId);
            $rowCtx  = $twoStep ? appr_ctx($pdo,$companyId,$me,(int)$l['staff_id']) : null;
            $canApprove = in_array($st,['pending','dept_ok'],true) && ($twoStep ? (appr_next($st,$rowCtx)!==null) : $st==='pending');
            $canReject  = in_array($st,['pending','dept_ok'],true) && ($twoStep ? appr_can_reject($st,$rowCtx) : $st==='pending');
            $apLabel = ($twoStep && $st==='pending' && $rowCtx['isDept'] && $rowCtx['ops']>0 && !$rowCtx['isOps']) ? '✓ Approve (to Manager)' : '✓ Approve';
            ?>
            <?php if ($canApprove || $canReject): ?>
            <div class="actions">
                <?php if ($canApprove): ?>
                <form method="POST" style="display:inline"><input type="hidden" name="view" value="<?= htmlspecialchars($view) ?>"><input type="hidden" name="action" value="approve"><input type="hidden" name="loan_id" value="<?= (int)$l['id'] ?>">
                    <button class="btn btn-ok" type="submit"><?= $apLabel ?></button></form>
                <?php endif; ?>
                <?php if ($canReject): ?>
                <form method="POST" style="display:inline" onsubmit="return confirm('Reject this loan?')"><input type="hidden" name="view" value="<?= htmlspecialchars($view) ?>"><input type="hidden" name="action" value="reject"><input type="hidden" name="loan_id" value="<?= (int)$l['id'] ?>">
                    <button class="btn btn-no" type="submit" data-lo="✕ ປະຕິເສດ" data-en="✕ Reject">✕ Reject</button></form>
                <?php endif; ?>
            </div>
            <?php endif; ?>
        </div>
    <?php endforeach; endif; ?>
</div>

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