<?php
session_start();
require_once '../config/database.php';

if (!isset($_SESSION["user_id"]) || $_SESSION["role"] !== "partner") {
    header("Location: ../auth/login.php");
    exit;
}

$stmt = $pdo->prepare("SELECT * FROM partner_shops WHERE user_id = ? LIMIT 1");
$stmt->execute([$_SESSION["user_id"]]);
$shop = $stmt->fetch(PDO::FETCH_ASSOC);

$logo = "../uploads/logos/default-logo.png";
$qr_url = "";
$unreadPayments = 0;
$unreadMessages = [];

if ($shop) {
    if (!empty($shop["logo"])) {
        $logo = "../uploads/logos/" . $shop["logo"];
    }

    $qr_data = "https://7d-lao.com/seven-credit-system/public/shop.php?code=" . urlencode($shop["shop_code"]);
    $qr_url = "https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=" . urlencode($qr_data);

    $stmt = $pdo->prepare("
        SELECT COUNT(*) FROM transactions
        WHERE to_type = 'partner' AND to_id = ?
        AND from_type = 'customer' AND partner_read_at IS NULL
    ");
    $stmt->execute([$shop["id"]]);
    $unreadPayments = $stmt->fetchColumn();

    $stmt = $pdo->prepare("
        SELECT t.id, t.amount, t.created_at,
               t.from_type, t.transaction_type, t.remarks,
               c.full_name, c.phone
        FROM transactions t
        LEFT JOIN customers c ON c.id = t.from_id AND t.from_type = 'customer'
        WHERE t.to_type = 'partner'
          AND t.to_id = ?
          AND t.partner_read_at IS NULL
        ORDER BY t.created_at DESC LIMIT 30
    ");
    $stmt->execute([$shop["id"]]);
    $unreadMessages = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
?>
<!DOCTYPE html>
<html lang="lo">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Partner Dashboard</title>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Lao:wght@300;400;500;600;700;800&family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        * { box-sizing: border-box; margin: 0; padding: 0; }

        :root {
            --primary:    #1e3a5f;
            --mid:        #2563eb;
            --primary-lt: #dbeafe;
            --green:      #16a34a;
            --green-lt:   #dcfce7;
            --red:        #dc2626;
            --red-lt:     #fee2e2;
            --surface:    #ffffff;
            --bg:         #f0f4f8;
            --border:     #e2e8f0;
            --text:       #0f172a;
            --muted:      #64748b;
            --radius:     14px;
            --shadow:     0 2px 12px rgba(15,23,42,.08);
        }

        body {
            font-family: "Noto Sans Lao", "Inter", Arial, sans-serif;
            background: var(--bg);
            color: var(--text);
            padding: 24px 20px;
            min-height: 100vh;
        }

        .container { max-width: 1240px; margin: auto; }

        /* ── Language switcher ── */
        .lang-bar {
            display: flex;
            justify-content: flex-end;
            align-items: center;
            gap: 6px;
            margin-bottom: 14px;
        }

        .lang-label {
            font-size: 12px;
            color: var(--muted);
            font-weight: 500;
        }

        .lang-btn {
            display: inline-flex;
            align-items: center;
            gap: 5px;
            padding: 5px 12px;
            border-radius: 999px;
            border: 1.5px solid var(--border);
            background: var(--surface);
            font-size: 12px;
            font-weight: 700;
            color: var(--muted);
            cursor: pointer;
            font-family: inherit;
            transition: border-color .15s, color .15s, background .15s;
        }

        .lang-btn:hover {
            border-color: var(--mid);
            color: var(--mid);
        }

        .lang-btn.active {
            background: var(--mid);
            border-color: var(--mid);
            color: #fff;
        }

        .lang-flag { font-size: 14px; line-height: 1; }

        /* ── Header ── */
        .header {
            background: linear-gradient(135deg, #0f2444 0%, #1e3a5f 60%, #1d4ed8 100%);
            border-radius: 20px;
            padding: 28px 32px;
            margin-bottom: 24px;
            box-shadow: 0 8px 32px rgba(15,23,42,.18);
        }

        .header-content {
            display: flex;
            justify-content: space-between;
            align-items: center;
            gap: 24px;
        }

        .header-left { display: flex; align-items: center; gap: 20px; }

        .logo-box {
            width: 72px; height: 72px;
            background: rgba(255,255,255,.12);
            border: 2px solid rgba(255,255,255,.25);
            border-radius: 16px; overflow: hidden;
            flex-shrink: 0; padding: 8px;
        }

        .logo-box img { width: 100%; height: 100%; object-fit: contain; }

        .header-info h1 {
            font-size: 26px; font-weight: 800;
            color: #fff; line-height: 1.25;
        }

        .header-info .welcome {
            margin-top: 5px; font-size: 14px;
            color: rgba(255,255,255,.72); font-weight: 400;
        }

        .header-info .shop-code {
            display: inline-block; margin-top: 8px;
            background: rgba(255,255,255,.15);
            border: 1px solid rgba(255,255,255,.25);
            color: #fff; font-size: 12px; font-weight: 600;
            padding: 3px 10px; border-radius: 999px; letter-spacing: .5px;
        }

        .qr-box {
            background: rgba(255,255,255,.96);
            padding: 14px; border-radius: 16px;
            text-align: center; flex-shrink: 0;
            min-width: 148px;
            box-shadow: 0 4px 16px rgba(0,0,0,.15);
        }

        .qr-box img {
            width: 128px; height: 128px;
            display: block; margin: 0 auto 8px; border-radius: 8px;
        }

        .qr-box .qr-label {
            font-size: 12px; font-weight: 700;
            color: var(--primary); letter-spacing: .4px;
        }

        /* ── Layout ── */
        .dashboard-layout {
            display: grid;
            grid-template-columns: 1fr 320px;
            gap: 20px;
            align-items: start;
        }

        /* ── Balance card ── */
        .balance-card {
            background: var(--surface);
            border-radius: var(--radius);
            padding: 24px;
            box-shadow: var(--shadow);
            margin-bottom: 20px;
            border: 1px solid var(--border);
        }

        .balance-card .shop-title {
            font-size: 17px; font-weight: 700;
            color: var(--text); margin-bottom: 12px;
        }

        .balance-label {
            font-size: 11px; font-weight: 700;
            color: var(--muted); text-transform: uppercase;
            letter-spacing: .7px; margin-bottom: 6px;
        }

        .balance-amount {
            font-size: 38px; font-weight: 800;
            color: var(--mid); line-height: 1;
            letter-spacing: -1.5px; margin-bottom: 12px;
        }

        .balance-amount .currency {
            font-size: 18px; font-weight: 600;
            color: var(--muted); margin-right: 3px;
            letter-spacing: 0;
        }

        .status-badge {
            display: inline-flex; align-items: center;
            gap: 6px; padding: 5px 14px;
            border-radius: 999px; font-size: 13px; font-weight: 700;
        }

        .status-badge.active   { background: var(--green-lt); color: var(--green); }
        .status-badge.inactive { background: var(--red-lt);   color: var(--red); }

        .status-badge::before {
            content: ""; width: 7px; height: 7px;
            border-radius: 50%; background: currentColor;
        }

        /* ── Menu grid ── */
        .menu-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(195px, 1fr));
            gap: 14px;
        }

        .menu-card {
            background: var(--surface); border-radius: var(--radius);
            padding: 20px; box-shadow: var(--shadow);
            text-decoration: none; color: var(--text);
            border: 1px solid var(--border);
            transition: transform .18s, box-shadow .18s, border-color .18s;
            display: flex; flex-direction: column; gap: 8px;
        }

        .menu-card:hover {
            transform: translateY(-4px);
            box-shadow: 0 10px 28px rgba(15,23,42,.13);
            border-color: #93c5fd;
        }

        .menu-card .icon { font-size: 26px; line-height: 1; }
        .menu-card h3 { font-size: 14px; font-weight: 700; line-height: 1.3; }
        .menu-card p  { font-size: 12px; color: var(--muted); line-height: 1.5; }

        /* ── Notification panel ── */
        .notification-panel {
            background: var(--surface); border-radius: var(--radius);
            padding: 20px; box-shadow: var(--shadow);
            border: 1px solid var(--border);
            position: sticky; top: 20px;
        }

        .notif-header {
            display: flex; align-items: center;
            justify-content: space-between; margin-bottom: 14px;
        }

        .notif-header h3 { font-size: 15px; font-weight: 700; }

        .notif-badge {
            background: var(--green); color: #fff;
            font-size: 11px; font-weight: 800;
            padding: 3px 9px; border-radius: 999px;
            min-width: 24px; text-align: center;
        }

        .message-card {
            background: #f0fdf4; border: 1px solid #86efac;
            border-radius: 10px; padding: 12px 14px;
            margin-bottom: 10px; transition: opacity .3s;
        }

        .message-card label {
            display: flex; gap: 10px;
            cursor: pointer; align-items: flex-start;
        }

        .message-card input[type=checkbox] {
            margin-top: 3px; width: 16px; height: 16px;
            accent-color: var(--green); flex-shrink: 0;
        }

        .msg-name  { font-size: 14px; font-weight: 700; color: #14532d; }
        .msg-amount { font-size: 15px; font-weight: 800; color: var(--green); margin: 3px 0; }
        .msg-time  { font-size: 11px; color: var(--muted); }

        .empty-msg {
            text-align: center; padding: 24px 0;
            color: var(--muted); font-size: 13px;
        }

        .empty-msg .empty-icon { font-size: 30px; display: block; margin-bottom: 8px; }

        /* ── Logout ── */
        .logout-row { margin-top: 24px; text-align: right; }

        .logout-btn {
            display: inline-flex; align-items: center; gap: 6px;
            background: #fff; color: var(--red);
            border: 1.5px solid var(--red);
            padding: 10px 20px; border-radius: 10px;
            text-decoration: none; font-size: 14px; font-weight: 700;
            font-family: inherit; transition: background .15s, color .15s;
        }

        .logout-btn:hover { background: var(--red); color: #fff; }

        .warning-box {
            background: var(--red-lt); color: var(--red);
            padding: 18px 20px; border-radius: var(--radius);
            border: 1px solid #fca5a5; font-weight: 600;
        }

        @media (max-width: 900px) {
            body { padding: 14px; }
            .dashboard-layout { grid-template-columns: 1fr; }
            .notification-panel { position: static; }
            .header-content { flex-direction: column; align-items: flex-start; }
            .qr-box { width: 100%; }
            .header-info h1 { font-size: 22px; }
            .balance-amount { font-size: 30px; }
        }
    </style>
</head>
<body>
<div class="container">

    <!-- ── Language switcher ── -->
    <div class="lang-bar">
        <span class="lang-label" id="langLabel">ພາສາ / Language:</span>
        <button class="lang-btn active" id="btn-lo" onclick="setLang('lo')">
            <span class="lang-flag">🇱🇦</span> ລາວ
        </button>
        <button class="lang-btn" id="btn-en" onclick="setLang('en')">
            <span class="lang-flag">🇬🇧</span> English
        </button>
    </div>

    <!-- ── Header ── -->
    <div class="header">
        <div class="header-content">
            <div class="header-left">
                <div class="logo-box">
                    <img src="<?= htmlspecialchars($logo) ?>" alt="Shop Logo">
                </div>
                <div class="header-info">
                    <h1><?= $shop ? htmlspecialchars($shop["shop_name"]) : "Partner Dashboard" ?></h1>
                    <div class="welcome">
                        <span data-lo="ຍິນດີຕ້ອນຮັບ," data-en="Welcome,">ຍິນດີຕ້ອນຮັບ,</span>
                        <?= htmlspecialchars($_SESSION["name"]) ?>
                    </div>
                    <?php if ($shop): ?>
                        <span class="shop-code"><?= htmlspecialchars($shop["shop_code"]) ?></span>
                    <?php endif; ?>
                </div>
            </div>

            <?php if ($shop && $qr_url): ?>
                <div class="qr-box">
                    <img src="<?= htmlspecialchars($qr_url) ?>" alt="QR Code">
                    <div class="qr-label" data-lo="ສະແກນ &amp; ຈ່າຍ" data-en="Scan &amp; Pay">
                        ສະແກນ &amp; ຈ່າຍ
                    </div>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <?php if ($shop): ?>
    <div class="dashboard-layout">

        <!-- Left column -->
        <div>
            <div class="balance-card">
                <div class="shop-title"><?= htmlspecialchars($shop["shop_name"]) ?></div>
                <div class="balance-label"
                     data-lo="ຍອດເຄຣດິດປັດຈຸບັນ"
                     data-en="CURRENT CREDIT BALANCE">
                    ຍອດເຄຣດິດປັດຈຸບັນ
                </div>
                <div class="balance-amount">
                    <span class="currency">₭</span><?= number_format($shop["credit_balance"], 2) ?>
                </div>
                <span class="status-badge <?= htmlspecialchars($shop["status"]) ?>">
                    <?= ucfirst(htmlspecialchars($shop["status"])) ?>
                </span>
            </div>

            <div class="menu-grid">
                <a class="menu-card" href="payment_history.php">
                    <span class="icon">💳</span>
                    <h3 data-lo="ການຊຳລະຂອງລູກຄ້າ" data-en="Customer Payments">ການຊຳລະຂອງລູກຄ້າ</h3>
                    <p  data-lo="ເບິ່ງການຊຳລະທີ່ໄດ້ຮັບຈາກລູກຄ້າ" data-en="View payments received from customers.">ເບິ່ງການຊຳລະທີ່ໄດ້ຮັບຈາກລູກຄ້າ</p>
                </a>

                <a class="menu-card" href="topup_customer.php">
                    <span class="icon">⚡</span>
                    <h3 data-lo="ຕື່ມເງີນໃຫ້ລູກຄ້າ" data-en="Top Up Customer">ຕື່ມເງີນໃຫ້ລູກຄ້າ</h3>
                    <p  data-lo="ໂອນເຄຣດິດຈາກຮ້ານໄປຫາກະເປົາລູກຄ້າ" data-en="Transfer credit from your shop to a customer wallet.">ໂອນເຄຣດິດຈາກຮ້ານໄປຫາກະເປົາລູກຄ້າ</p>
                </a>

                <a class="menu-card" href="credit_request.php">
                    <span class="icon">📋</span>
                    <h3 data-lo="ສ້າງຄຳຮ້ອງຂໍເຄຣດິດ" data-en="Create Credit Request">ສ້າງຄຳຮ້ອງຂໍເຄຣດິດ</h3>
                    <p  data-lo="ຂໍຊື້ເຄຣດິດ ຫຼື ແລກເຄຣດິດເປັນເງິນສົດ" data-en="Request to buy credit or exchange credit to cash.">ຂໍຊື້ເຄຣດິດ ຫຼື ແລກເຄຣດິດເປັນເງິນສົດ</p>
                </a>

                <a class="menu-card" href="wallet_history.php">
                    <span class="icon">📊</span>
                    <h3 data-lo="ປະຫວັດການຕື່ມເງີນ" data-en="Top Up History">ປະຫວັດການຕື່ມເງີນ</h3>
                    <p  data-lo="ເບິ່ງທຸກທຸລະກຳຕື່ມກະເປົາລູກຄ້າ" data-en="View all customer wallet top-up transactions.">ເບິ່ງທຸກທຸລະກຳຕື່ມກະເປົາລູກຄ້າ</p>
                </a>

                <a class="menu-card" href="qr_code.php">
                    <span class="icon">📷</span>
                    <h3 data-lo="QR Code ຂອງຂ້ອຍ" data-en="My QR Code">QR Code ຂອງຂ້ອຍ</h3>
                    <p  data-lo="ສະແດງ QR Code ຂອງຮ້ານໃນໜ້າຈໍໃຫຍ່" data-en="Show your shop QR code on a larger screen.">ສະແດງ QR Code ຂອງຮ້ານໃນໜ້າຈໍໃຫຍ່</p>
                </a>

                <a class="menu-card" href="upload_logo.php">
                    <span class="icon">🖼️</span>
                    <h3 data-lo="ອັບໂຫຼດໂລໂກ້" data-en="Upload Logo">ອັບໂຫຼດໂລໂກ້</h3>
                    <p  data-lo="ອັບໂຫຼດ ຫຼື ແທນທີ່ໂລໂກ້ຮ້ານຂອງທ່ານ" data-en="Upload or replace your shop logo.">ອັບໂຫຼດ ຫຼື ແທນທີ່ໂລໂກ້ຮ້ານຂອງທ່ານ</p>
                </a>
            </div>
        </div>

        <!-- Right column: notifications -->
        <div class="notification-panel">
            <div class="notif-header">
                <h3>
                    💚 <span data-lo="ການຊຳລະໃໝ່" data-en="New Payments">ການຊຳລະໃໝ່</span>
                </h3>
                <span class="notif-badge" id="notificationCount"
                      style="<?= $unreadPayments > 0 ? '' : 'display:none;' ?>">
                    <?= $unreadPayments ?>
                </span>
            </div>

            <div id="notificationList">
                <?php if (count($unreadMessages) > 0): ?>
                    <?php foreach ($unreadMessages as $msg): ?>
                        <?php
                        $txType  = $msg["transaction_type"] ?? "";
                        $fromType = $msg["from_type"] ?? "customer";
                        if ($txType === "credit_request_approved") {
                            $cardBg     = "#f0fdf4"; $cardBorder = "#86efac";
                            $nameColor  = "#14532d"; $amtColor   = "#16a34a";
                            $icon       = "✅"; $prefix = "+";
                            $displayName = "Admin";
                        } elseif ($txType === "credit_request_rejected") {
                            $cardBg     = "#fff1f2"; $cardBorder = "#fca5a5";
                            $nameColor  = "#991b1b"; $amtColor   = "#dc2626";
                            $icon       = "❌"; $prefix = "";
                            $displayName = "Admin";
                        } else {
                            $cardBg     = "#f0fdf4"; $cardBorder = "#86efac";
                            $nameColor  = "#14532d"; $amtColor   = "#16a34a";
                            $icon       = "💳"; $prefix = "+";
                            $displayName = $msg["full_name"] ?? "ລູກຄ້າ";
                        }
                        /* Short remark for admin notifications */
                        $remark = "";
                        if ($fromType === "admin" && !empty($msg["remarks"])) {
                            $parts  = explode("/", $msg["remarks"]);
                            $remark = trim($parts[0] ?? $msg["remarks"]);
                            if (mb_strlen($remark) > 55) $remark = mb_substr($remark, 0, 55) . "…";
                        }
                        ?>
                        <div class="message-card" id="msg-<?= $msg["id"] ?>"
                             style="background:<?= $cardBg ?>;border:1px solid <?= $cardBorder ?>;">
                            <label>
                                <input type="checkbox" onchange="markMessageRead(<?= $msg["id"] ?>, event)">
                                <div style="flex:1;">
                                    <div class="msg-name" style="color:<?= $nameColor ?>;">
                                        <?= $icon ?> <?= htmlspecialchars($displayName) ?>
                                    </div>
                                    <?php if ($remark): ?>
                                        <div style="font-size:11px;color:#64748b;margin:2px 0;">
                                            <?= htmlspecialchars($remark) ?>
                                        </div>
                                    <?php endif; ?>
                                    <div class="msg-amount" style="color:<?= $amtColor ?>;">
                                        <?= $prefix ?>₭ <?= number_format($msg["amount"], 2) ?>
                                    </div>
                                    <div class="msg-time"><?= htmlspecialchars($msg["created_at"]) ?></div>
                                </div>
                            </label>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <div class="empty-msg" id="emptyMessage">
                        <span class="empty-icon">✅</span>
                        <span data-lo="ບໍ່ມີການຊຳລະໃໝ່" data-en="No new payments.">ບໍ່ມີການຊຳລະໃໝ່</span>
                    </div>
                <?php endif; ?>
            </div>
        </div>

    </div><!-- /dashboard-layout -->

    <?php else: ?>
        <div class="warning-box">
            ⚠️ <span data-lo="ບໍ່ມີຮ້ານຄ້າທີ່ເຊື່ອມຕໍ່ກັບບັນຊີນີ້" data-en="No partner shop connected to this account.">ບໍ່ມີຮ້ານຄ້າທີ່ເຊື່ອມຕໍ່ກັບບັນຊີນີ້</span>
        </div>
    <?php endif; ?>

    <div class="logout-row">
        <a class="logout-btn" href="../auth/logout.php">
            🚪 <span data-lo="ອອກຈາກລະບົບ" data-en="Logout">ອອກຈາກລະບົບ</span>
        </a>
    </div>

</div><!-- /container -->

<script>
/* ══════════════════════════════════════
   LANGUAGE SWITCHER
   Reads/writes localStorage so the choice
   persists across page refreshes.
══════════════════════════════════════ */
function setLang(lang) {
    localStorage.setItem("lang", lang);
    applyLang(lang);
}

function applyLang(lang) {
    /* Toggle button active state */
    document.getElementById("btn-lo").classList.toggle("active", lang === "lo");
    document.getElementById("btn-en").classList.toggle("active", lang === "en");

    /* Swap every element that has data-lo / data-en */
    document.querySelectorAll("[data-lo][data-en]").forEach(el => {
        el.innerHTML = el.dataset[lang] || el.innerHTML;
    });

    /* Notification customer name fallback text */
    window._currentLang = lang;
}

/* Apply saved preference on load */
(function() {
    const saved = localStorage.getItem("lang") || "lo";
    applyLang(saved);
})();


/* ══════════════════════════════════════
   NOTIFICATION LOGIC
══════════════════════════════════════ */
let locallyReadIds = new Set();

function escapeHtml(text) {
    if (!text) return "";
    return String(text)
        .replaceAll("&","&amp;").replaceAll("<","&lt;")
        .replaceAll(">","&gt;").replaceAll('"',"&quot;")
        .replaceAll("'","&#039;");
}

function formatAmount(amount) {
    return Number(amount || 0).toLocaleString("en-US", {
        minimumFractionDigits: 2, maximumFractionDigits: 2
    });
}

function markMessageRead(transactionId, event) {
    const checkbox = event.target;
    checkbox.disabled = true;
    const formData = new FormData();
    formData.append("transaction_id", transactionId);

    fetch("mark_notification_read.php", { method:"POST", body:formData, cache:"no-store" })
    .then(r => r.json())
    .then(data => {
        if (!data.success) {
            checkbox.disabled = false;
            checkbox.checked  = false;
            alert(data.message);
            return;
        }
        locallyReadIds.add(String(transactionId));
        const msg = document.getElementById("msg-" + transactionId);
        if (msg) {
            msg.style.opacity = "0";
            setTimeout(() => { msg.remove(); updateCount(); }, 320);
        } else {
            updateCount();
        }
        loadNewPayments();
    })
    .catch(() => {
        checkbox.disabled = false;
        checkbox.checked  = false;
    });
}

function emptyHTML() {
    const lang = window._currentLang || "lo";
    const text = lang === "en" ? "No new payments." : "ບໍ່ມີການຊຳລະໃໝ່";
    return `<div class="empty-msg" id="emptyMessage">
                <span class="empty-icon">✅</span>
                <span data-lo="ບໍ່ມີການຊຳລະໃໝ່" data-en="No new payments.">${text}</span>
            </div>`;
}

function updateCount() {
    const cards = document.querySelectorAll(".message-card");
    const badge = document.getElementById("notificationCount");
    const list  = document.getElementById("notificationList");
    if (!badge || !list) return;
    if (cards.length > 0) {
        badge.style.display = "inline-block";
        badge.textContent   = cards.length;
    } else {
        badge.style.display = "none";
        list.innerHTML = emptyHTML();
    }
}

function renderCard(payment) {
    const lang = window._currentLang || "lo";
    const type = payment.notif_type || "payment";

    let icon, bgColor, borderColor, nameColor, amtColor, prefix;

    if (type === "approved") {
        icon = "✅"; bgColor = "#f0fdf4"; borderColor = "#86efac";
        nameColor = "#14532d"; amtColor = "#16a34a"; prefix = "+";
    } else if (type === "rejected") {
        icon = "❌"; bgColor = "#fff1f2"; borderColor = "#fca5a5";
        nameColor = "#991b1b"; amtColor = "#dc2626"; prefix = "";
    } else {
        icon = "💳"; bgColor = "#f0fdf4"; borderColor = "#86efac";
        nameColor = "#14532d"; amtColor = "#16a34a"; prefix = "+";
    }

    const name = payment.full_name || (lang === "en" ? "Customer" : "ລູກຄ້າ");

    let remarkHTML = "";
    if (payment.remarks && (type === "approved" || type === "rejected")) {
        const parts  = payment.remarks.split("/");
        let remark   = (lang === "lo" ? parts[0] : (parts[1] || parts[0]))?.trim() || "";
        if (remark.length > 60) remark = remark.substring(0, 60) + "…";
        if (remark) remarkHTML = `<div style="font-size:11px;color:#64748b;margin:2px 0;">${escapeHtml(remark)}</div>`;
    }

    return `<div class="message-card" id="msg-${payment.id}"
                 style="background:${bgColor};border:1px solid ${borderColor};">
        <label>
            <input type="checkbox" onchange="markMessageRead(${payment.id}, event)">
            <div style="flex:1;">
                <div class="msg-name" style="color:${nameColor};">${icon} ${escapeHtml(name)}</div>
                ${remarkHTML}
                <div class="msg-amount" style="color:${amtColor};">${prefix}₭ ${formatAmount(payment.amount)}</div>
                <div class="msg-time">${escapeHtml(payment.created_at)}</div>
            </div>
        </label>
    </div>`;
}

function loadNewPayments() {
    fetch("check_new_payments.php", { cache:"no-store" })
    .then(r => r.json())
    .then(data => {
        if (!data.success) return;
        const badge = document.getElementById("notificationCount");
        const list  = document.getElementById("notificationList");
        if (!badge || !list) return;
        const payments = data.payments.filter(p => !locallyReadIds.has(String(p.id)));
        if (payments.length === 0) {
            badge.style.display = "none";
            list.innerHTML = emptyHTML();
            return;
        }
        badge.style.display = "inline-block";
        badge.textContent   = payments.length;
        list.innerHTML      = payments.map(renderCard).join("");
    })
    .catch(() => {});
}

loadNewPayments();
setInterval(loadNewPayments, 5000);
</script>

</body>
</html>