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

if (!$shop) {
    die("No partner shop connected to this account.");
}

/* ── AJAX: search customer by phone, Pay ID, or account code ── */
if (isset($_GET["action"]) && $_GET["action"] === "search_customer") {
    header("Content-Type: application/json");
    $q = trim($_GET["q"] ?? "");
    if ($q === "") { echo json_encode(["success" => false, "message" => "Empty search"]); exit; }

    /* pay_id may not exist yet on older databases — detect it so the query never errors */
    $hasPayId = (bool) $pdo->query("SHOW COLUMNS FROM customers LIKE 'pay_id'")->fetch();

    if ($hasPayId) {
        $stmt = $pdo->prepare("
            SELECT id, customer_code, pay_id, full_name, phone, balance, status
            FROM customers
            WHERE (phone = ? OR pay_id = ? OR customer_code = ?)
            AND status = 'active'
            LIMIT 1
        ");
        $stmt->execute([$q, $q, $q]);
    } else {
        $stmt = $pdo->prepare("
            SELECT id, customer_code, full_name, phone, balance, status
            FROM customers
            WHERE (phone = ? OR customer_code = ?)
            AND status = 'active'
            LIMIT 1
        ");
        $stmt->execute([$q, $q]);
    }
    $customer = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($customer) {
        echo json_encode(["success" => true, "customer" => $customer]);
    } else {
        echo json_encode(["success" => false, "message" => "Customer not found or inactive."]);
    }
    exit;
}

/* ── AJAX: generate QR topup session ── */
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST["action"]) && $_POST["action"] === "create_qr") {
    header("Content-Type: application/json");
    $customer_id = (int)($_POST["customer_id"] ?? 0);
    $amount      = floatval(str_replace(",", "", $_POST["amount"] ?? 0));

    if ($customer_id <= 0 || $amount <= 0) {
        echo json_encode(["success" => false, "message" => "Invalid input."]);
        exit;
    }
    if ($amount > $shop["credit_balance"]) {
        echo json_encode(["success" => false, "message" => "Not enough credit."]);
        exit;
    }

    /* Store a pending QR session — expires in 10 minutes */
    $token = bin2hex(random_bytes(16));
    $expires = date("Y-m-d H:i:s", time() + 600);

    try {
        /* Try to use a qr_topup_sessions table; create it if missing */
        $pdo->exec("
            CREATE TABLE IF NOT EXISTS qr_topup_sessions (
                id INT AUTO_INCREMENT PRIMARY KEY,
                token VARCHAR(64) NOT NULL UNIQUE,
                partner_shop_id INT NOT NULL,
                customer_id INT NOT NULL,
                amount DECIMAL(15,2) NOT NULL,
                status ENUM('pending','completed','expired') DEFAULT 'pending',
                created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                expires_at DATETIME NOT NULL,
                completed_at DATETIME NULL
            )
        ");

        $stmt = $pdo->prepare("
            INSERT INTO qr_topup_sessions (token, partner_shop_id, customer_id, amount, expires_at)
            VALUES (?, ?, ?, ?, ?)
        ");
        $stmt->execute([$token, $shop["id"], $customer_id, $amount, $expires]);

        /* QR points to a confirm page that processes the transfer */
        $qr_url_data = (isset($_SERVER["HTTPS"]) ? "https" : "http")
                     . "://" . $_SERVER["HTTP_HOST"]
                     . dirname($_SERVER["PHP_SELF"]) . "/confirm_qr_topup.php?token=" . $token;

        $qr_image = "https://api.qrserver.com/v1/create-qr-code/?size=280x280&data=" . urlencode($qr_url_data);

        echo json_encode([
            "success"   => true,
            "token"     => $token,
            "qr_image"  => $qr_image,
            "qr_url"    => $qr_url_data,
            "expires"   => $expires,
            "amount"    => $amount
        ]);
    } catch (Throwable $e) {
        echo json_encode(["success" => false, "message" => $e->getMessage()]);
    }
    exit;
}

/* ── AJAX: poll QR session status ── */
if (isset($_GET["action"]) && $_GET["action"] === "poll_qr") {
    header("Content-Type: application/json");
    $token = trim($_GET["token"] ?? "");
    if (!$token) { echo json_encode(["status" => "error"]); exit; }

    try {
        $stmt = $pdo->prepare("SELECT status FROM qr_topup_sessions WHERE token = ? AND partner_shop_id = ?");
        $stmt->execute([$token, $shop["id"]]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        echo json_encode(["status" => $row ? $row["status"] : "error"]);
    } catch (Throwable $e) {
        echo json_encode(["status" => "error"]);
    }
    exit;
}

/* ── NORMAL POST: direct top-up (no QR) ── */
$error   = "";
$success = "";

if ($_SERVER["REQUEST_METHOD"] === "POST" && !isset($_POST["action"])) {
    $customer_id = (int)($_POST["customer_id"] ?? 0);
    $amount      = floatval(str_replace(",", "", $_POST["amount"] ?? 0));

    $stmt = $pdo->prepare("SELECT * FROM customers WHERE id = ? AND status = 'active' LIMIT 1");
    $stmt->execute([$customer_id]);
    $customer = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$customer)           { $error = "Customer not found."; }
    elseif ($amount <= 0)     { $error = "Amount must be greater than zero."; }
    elseif ($amount > $shop["credit_balance"]) { $error = "Not enough credit."; }
    else {
        try {
            $pdo->beginTransaction();

            $pdo->prepare("UPDATE partner_shops SET credit_balance = credit_balance - ? WHERE id = ?")
                ->execute([$amount, $shop["id"]]);
            $pdo->prepare("UPDATE customers SET balance = balance + ? WHERE id = ?")
                ->execute([$amount, $customer["id"]]);

            $tx_code = "WTX" . time();
            $pdo->prepare("INSERT INTO wallet_transactions
                (transaction_code, customer_id, partner_shop_id, amount, transaction_type, remarks)
                VALUES (?, ?, ?, ?, ?, ?)")
                ->execute([$tx_code, $customer["id"], $shop["id"], $amount, "topup", "Partner top-up"]);

            $pdo->prepare("INSERT INTO transactions
                (from_type, from_id, to_type, to_id, amount, customer_read_at, created_at)
                VALUES ('partner', ?, 'customer', ?, ?, NULL, NOW())")
                ->execute([$shop["id"], $customer["id"], $amount]);

            $pdo->commit();
            require_once __DIR__ . '/../config/notify.php';
            notify_money_received($pdo, (int)$customer["id"], (float)$amount, $shop["shop_name"] ?? "a shop");
            $success = "Top-up of ₭ " . number_format($amount, 2) . " to " . $customer["full_name"] . " was successful.";

        } catch (Exception $e) {
            $pdo->rollBack();
            $error = "Error: " . $e->getMessage();
        }
    }
}

/* Refresh shop balance */
$stmt = $pdo->prepare("SELECT * FROM partner_shops WHERE id = ? LIMIT 1");
$stmt->execute([$shop["id"]]);
$shop = $stmt->fetch(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>Top Up Customer</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&display=swap" rel="stylesheet">
    <style>
        * { box-sizing: border-box; margin: 0; padding: 0; }

        :root {
            --primary: #2563eb;
            --primary-dark: #1e3a5f;
            --green: #16a34a;
            --green-lt: #dcfce7;
            --red: #dc2626;
            --red-lt: #fee2e2;
            --amber: #d97706;
            --amber-lt: #fef3c7;
            --surface: #fff;
            --bg: #f0f4f8;
            --border: #e2e8f0;
            --text: #0f172a;
            --muted: #64748b;
            --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);
            padding: 28px 20px;
            min-height: 100vh;
        }

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

        /* ── Balance header ── */
        .balance-header {
            background: linear-gradient(135deg, #0f2444 0%, #1e3a5f 55%, #1d4ed8 100%);
            border-radius: 18px;
            padding: 22px 28px;
            margin-bottom: 22px;
            color: #fff;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 14px;
            box-shadow: 0 6px 24px rgba(15,23,42,.18);
        }

        .balance-header .shop-name { font-size: 18px; font-weight: 700; margin-bottom: 4px; }
        .balance-header .bal-label { font-size: 11px; font-weight: 600; color: rgba(255,255,255,.65); letter-spacing: .6px; text-transform: uppercase; }
        .balance-header .bal-amount { font-size: 34px; font-weight: 800; letter-spacing: -1px; }
        .balance-header .bal-amount .cur { font-size: 16px; font-weight: 600; color: rgba(255,255,255,.7); margin-right: 3px; }
        .back-btn {
            background: rgba(255,255,255,.15); border: 1.5px solid rgba(255,255,255,.3);
            color: #fff; padding: 8px 16px; border-radius: 10px;
            text-decoration: none; font-size: 13px; font-weight: 600;
            transition: background .15s;
        }
        .back-btn:hover { background: rgba(255,255,255,.25); }

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

        .card h2 {
            font-size: 19px; font-weight: 700;
            color: var(--text); margin-bottom: 22px;
            display: flex; align-items: center; gap: 8px;
        }

        /* ── Form ── */
        .form-group { margin-bottom: 18px; }

        .form-group label {
            display: block; font-size: 13px;
            font-weight: 700; color: var(--muted);
            text-transform: uppercase; letter-spacing: .5px;
            margin-bottom: 7px;
        }

        .search-row {
            display: flex; gap: 8px;
        }

        .search-row input {
            flex: 1;
            padding: 11px 14px;
            border: 1.5px solid var(--border);
            border-radius: 10px;
            font-size: 15px;
            font-family: inherit;
            outline: none;
            transition: border-color .15s;
        }

        .search-row input:focus { border-color: var(--primary); }

        .search-btn {
            padding: 11px 20px;
            background: var(--primary-dark);
            color: #fff;
            border: none;
            border-radius: 10px;
            font-size: 14px;
            font-weight: 700;
            font-family: inherit;
            cursor: pointer;
            transition: background .15s;
            white-space: nowrap;
        }

        .search-btn:hover { background: #163054; }

        /* ── Scan QR (shop reads the customer's QR) ── */
        .scan-btn-full {
            width: 100%; margin-top: 8px; padding: 12px;
            background: var(--primary); color: #fff; border: none;
            border-radius: 10px; font-size: 15px; font-weight: 700;
            font-family: inherit; cursor: pointer;
            display: flex; align-items: center; justify-content: center; gap: 8px;
        }
        .scan-btn-full:active { opacity: .9; }
        #shopScanOverlay {
            display: none; position: fixed; inset: 0; z-index: 9999;
            background: rgba(0,0,0,.88); flex-direction: column;
            align-items: center; justify-content: center; padding: 16px;
        }
        #shopScanOverlay .sheet { width: 100%; max-width: 360px; }
        #shopReader { width: 100%; border-radius: 14px; overflow: hidden; background: #000; }
        #shopScanMsg { color: #fff; text-align: center; margin: 12px 0; font-size: 14px; }
        .scan-cancel {
            width: 100%; padding: 12px; border: none; border-radius: 10px;
            background: #fff; color: #111827; font-weight: 700; font-size: 15px;
            font-family: inherit; cursor: pointer;
        }

        /* ── Customer result card ── */
        .customer-found {
            display: none;
            background: #f0fdf4;
            border: 1.5px solid #86efac;
            border-radius: 12px;
            padding: 16px 18px;
            margin-top: 12px;
        }

        .customer-found .cust-name {
            font-size: 17px; font-weight: 800; color: #14532d;
        }

        .customer-found .cust-meta {
            font-size: 13px; color: #166534; margin-top: 4px;
        }

        .customer-found .cust-balance {
            font-size: 13px; color: var(--muted); margin-top: 4px;
        }

        .customer-not-found {
            display: none;
            background: var(--red-lt);
            border: 1.5px solid #fca5a5;
            border-radius: 12px;
            padding: 14px 16px;
            margin-top: 12px;
            color: var(--red);
            font-weight: 600;
            font-size: 14px;
        }

        /* ── Amount input ── */
        .amount-row { display: flex; gap: 8px; align-items: flex-end; flex-wrap: wrap; }

        .amount-input-wrap { flex: 1; min-width: 200px; }

        .amount-input-wrap input {
            width: 100%;
            padding: 12px 14px;
            border: 1.5px solid var(--border);
            border-radius: 10px;
            font-size: 22px;
            font-weight: 800;
            font-family: inherit;
            color: var(--primary);
            outline: none;
            transition: border-color .15s;
        }

        .amount-input-wrap input:focus { border-color: var(--primary); }

        /* Quick amount chips */
        .amount-chips {
            display: flex; flex-wrap: wrap; gap: 7px;
            margin-top: 10px;
        }

        .chip {
            padding: 6px 14px;
            border-radius: 999px;
            border: 1.5px solid var(--border);
            background: var(--surface);
            font-size: 13px; font-weight: 700;
            color: var(--muted); cursor: pointer;
            font-family: inherit;
            transition: border-color .15s, color .15s, background .15s;
        }

        .chip:hover, .chip.active {
            border-color: var(--primary);
            color: var(--primary);
            background: var(--primary-lt, #dbeafe);
        }

        /* ── Action buttons ── */
        .action-row {
            display: flex; gap: 10px; flex-wrap: wrap; margin-top: 22px;
        }

        .btn {
            padding: 12px 22px;
            border: none; border-radius: 10px;
            font-size: 14px; font-weight: 700;
            font-family: inherit; cursor: pointer;
            text-decoration: none; display: inline-flex;
            align-items: center; gap: 7px;
            transition: opacity .15s, transform .1s;
        }

        .btn:hover { opacity: .88; transform: translateY(-1px); }
        .btn:active { transform: translateY(0); }

        .btn-topup  { background: var(--green);   color: #fff; }
        .btn-qr     { background: var(--primary);  color: #fff; }
        .btn-gray   { background: #e5e7eb; color: #374151; }

        /* ── Alert boxes ── */
        .alert {
            border-radius: 10px; padding: 14px 16px;
            font-size: 14px; font-weight: 600; margin-bottom: 18px;
        }

        .alert-success { background: var(--green-lt); color: #166534; border: 1px solid #86efac; }
        .alert-error   { background: var(--red-lt);   color: #991b1b; border: 1px solid #fca5a5; }

        /* ── QR Modal overlay ── */
        .qr-overlay {
            display: none;
            position: fixed; inset: 0;
            background: rgba(15,23,42,.55);
            z-index: 1000;
            align-items: center;
            justify-content: center;
        }

        .qr-overlay.show { display: flex; }

        .qr-modal {
            background: var(--surface);
            border-radius: 20px;
            padding: 32px 28px;
            max-width: 400px; width: 92%;
            text-align: center;
            box-shadow: 0 20px 60px rgba(0,0,0,.25);
            position: relative;
            animation: popIn .22s ease;
        }

        @keyframes popIn {
            from { transform: scale(.88); opacity: 0; }
            to   { transform: scale(1);   opacity: 1; }
        }

        .qr-modal .modal-title {
            font-size: 18px; font-weight: 800;
            color: var(--text); margin-bottom: 4px;
        }

        .qr-modal .modal-amount {
            font-size: 32px; font-weight: 800;
            color: var(--primary); letter-spacing: -1px;
            margin: 8px 0 18px;
        }

        .qr-modal .modal-amount .cur { font-size: 16px; color: var(--muted); margin-right: 3px; }

        .qr-modal img.qr-img {
            width: 240px; height: 240px;
            border-radius: 12px;
            border: 3px solid var(--border);
            margin-bottom: 14px;
        }

        .qr-modal .modal-customer {
            font-size: 14px; color: var(--muted); margin-bottom: 6px;
        }

        .qr-modal .modal-status {
            font-size: 14px; font-weight: 700;
            padding: 8px 16px; border-radius: 999px;
            display: inline-block; margin-bottom: 14px;
        }

        .modal-status.pending   { background: var(--amber-lt); color: var(--amber); }
        .modal-status.completed { background: var(--green-lt);  color: var(--green); }
        .modal-status.expired   { background: var(--red-lt);    color: var(--red); }

        .qr-modal .timer {
            font-size: 12px; color: var(--muted); margin-bottom: 18px;
        }

        .qr-modal .close-modal {
            background: var(--bg); border: 1.5px solid var(--border);
            color: var(--muted); padding: 9px 20px;
            border-radius: 10px; cursor: pointer;
            font-size: 13px; font-weight: 700; font-family: inherit;
        }

        .qr-modal .close-modal:hover { border-color: var(--red); color: var(--red); }

        @media (max-width: 600px) {
            body { padding: 14px; }
            .balance-header { flex-direction: column; align-items: flex-start; }
        }
    </style>
</head>
<body>

<div class="container">

    <!-- Balance header -->
    <div class="balance-header">
        <div>
            <div class="shop-name"><?= htmlspecialchars($shop["shop_name"]) ?></div>
            <div class="bal-label">ຍອດເຄຣດິດທີ່ໃຊ້ໄດ້ / Available Credit</div>
            <div class="bal-amount">
                <span class="cur">₭</span><?= number_format($shop["credit_balance"], 2) ?>
            </div>
        </div>
        <a class="back-btn" href="dashboard.php">← Back</a>
    </div>

    <!-- Alerts -->
    <?php if ($error):   ?><div class="alert alert-error">⚠️ <?= htmlspecialchars($error) ?></div><?php endif; ?>
    <?php if ($success): ?><div class="alert alert-success">✅ <?= htmlspecialchars($success) ?></div><?php endif; ?>

    <div class="card">
        <h2>⚡ ຕື່ມເງີນໃຫ້ລູກຄ້າ / Top Up Customer Wallet</h2>

        <form id="topupForm" method="POST">
            <input type="hidden" name="customer_id" id="customer_id_input">

            <!-- Step 1: Find customer -->
            <div class="form-group">
                <label>1. ຄົ້ນຫາລູກຄ້າ / Find Customer</label>
                <div class="search-row">
                    <input type="text" id="searchInput" inputmode="numeric"
                           placeholder="Phone number or Pay ID (e.g. 1234567)"
                           autocomplete="off">
                    <button type="button" class="search-btn" onclick="searchCustomer()">
                        🔍 Search
                    </button>
                </div>
                <button type="button" class="scan-btn-full" onclick="openShopScanner()">
                    📷 ສະແກນ QR ລູກຄ້າ / Scan customer QR
                </button>

                <!-- Customer found -->
                <div class="customer-found" id="customerFound">
                    <div class="cust-name" id="custName"></div>
                    <div class="cust-meta" id="custMeta"></div>
                    <div class="cust-balance" id="custBalance"></div>
                </div>

                <!-- Not found -->
                <div class="customer-not-found" id="customerNotFound">
                    ❌ <span id="notFoundMsg">Customer not found.</span>
                </div>
            </div>

            <!-- Step 2: Amount -->
            <div class="form-group">
                <label>2. ຈຳນວນເງີນ / Amount (₭)</label>
                <div class="amount-row">
                    <div class="amount-input-wrap">
                        <input type="text" id="amountDisplay"
                               placeholder="0"
                               autocomplete="off">
                        <input type="hidden" name="amount" id="amountHidden">
                    </div>
                </div>

                <!-- Quick chips -->
                <div class="amount-chips">
                    <?php foreach ([10000, 20000, 50000, 100000, 200000, 500000] as $v): ?>
                        <button type="button" class="chip"
                                onclick="setAmount(<?= $v ?>)">
                            ₭<?= number_format($v) ?>
                        </button>
                    <?php endforeach; ?>
                </div>
            </div>

            <!-- Actions -->
            <div class="action-row">
                <button type="button" class="btn btn-qr" onclick="createQR()">
                    📷 Create QR
                </button>
                <button type="submit" class="btn btn-topup" onclick="prepareSubmit()">
                    ⚡ Top Up Directly
                </button>
            </div>
        </form>
    </div>

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

<!-- QR Modal -->
<div class="qr-overlay" id="qrOverlay">
    <div class="qr-modal">
        <div class="modal-title">📷 Scan to Receive Credit</div>
        <div class="modal-amount">
            <span class="cur">₭</span><span id="modalAmount">0</span>
        </div>
        <div class="modal-customer" id="modalCustomer"></div>

        <img class="qr-img" id="qrImage" src="" alt="QR Code">

        <div class="modal-status pending" id="qrStatus">⏳ Waiting for scan…</div>
        <div class="timer" id="qrTimer"></div>

        <button class="close-modal" onclick="closeQR()">✕ Close</button>
    </div>
</div>

<script>
/* ── State ── */
let foundCustomer  = null;
let qrToken        = null;
let qrPollInterval = null;
let qrExpires      = null;
let qrTimerInterval= null;

/* ── Search customer ── */
async function searchCustomer() {
    const q = document.getElementById("searchInput").value.trim();
    if (!q) return;

    document.getElementById("customerFound").style.display    = "none";
    document.getElementById("customerNotFound").style.display = "none";
    foundCustomer = null;
    document.getElementById("customer_id_input").value = "";

    const resp = await fetch(`?action=search_customer&q=${encodeURIComponent(q)}`);
    const data = await resp.json();

    if (data.success) {
        foundCustomer = data.customer;
        document.getElementById("customer_id_input").value = data.customer.id;

        document.getElementById("custName").textContent    = data.customer.full_name;
        document.getElementById("custMeta").textContent    =
            (data.customer.pay_id ? "Pay ID: " + data.customer.pay_id + "  |  " : "") +
            "Phone: " + data.customer.phone;
        document.getElementById("custBalance").textContent =
            "Current Balance: ₭" + Number(data.customer.balance).toLocaleString("en-US", {minimumFractionDigits:2});

        document.getElementById("customerFound").style.display    = "block";
    } else {
        document.getElementById("notFoundMsg").textContent        = data.message;
        document.getElementById("customerNotFound").style.display = "block";
    }
}

/* Allow pressing Enter in search box */
document.getElementById("searchInput").addEventListener("keydown", e => {
    if (e.key === "Enter") { e.preventDefault(); searchCustomer(); }
});

/* ── Quick amount chips ── */
function setAmount(val) {
    document.getElementById("amountDisplay").value = val.toLocaleString("en-US");
    document.querySelectorAll(".chip").forEach(c => c.classList.remove("active"));
    event.target.classList.add("active");
}

/* ── Amount formatting ── */
document.getElementById("amountDisplay").addEventListener("input", function () {
    let v = this.value.replace(/,/g, "").replace(/[^\d]/g, "");
    this.value = v ? Number(v).toLocaleString("en-US") : "";
    document.querySelectorAll(".chip").forEach(c => c.classList.remove("active"));
});

function getRawAmount() {
    return parseFloat(document.getElementById("amountDisplay").value.replace(/,/g,"")) || 0;
}

/* ── Validate before any action ── */
function validate() {
    if (!foundCustomer) {
        alert("Please search and select a customer first.");
        return false;
    }
    if (getRawAmount() <= 0) {
        alert("Please enter a valid amount.");
        return false;
    }
    return true;
}

/* ── Direct top-up submit ── */
function prepareSubmit() {
    if (!validate()) { event.preventDefault(); return; }
    document.getElementById("amountHidden").value = getRawAmount();
}

/* ── Create QR ── */
async function createQR() {
    if (!validate()) return;

    const amount = getRawAmount();

    const body = new FormData();
    body.append("action",      "create_qr");
    body.append("customer_id", foundCustomer.id);
    body.append("amount",      amount);

    const resp = await fetch("", { method: "POST", body });
    const data = await resp.json();

    if (!data.success) {
        alert("Error: " + data.message);
        return;
    }

    /* Show modal */
    qrToken   = data.token;
    qrExpires = new Date(data.expires).getTime();

    document.getElementById("modalAmount").textContent  = amount.toLocaleString("en-US", {minimumFractionDigits:2});
    document.getElementById("modalCustomer").textContent = "Customer: " + foundCustomer.full_name;
    document.getElementById("qrImage").src              = data.qr_image;
    document.getElementById("qrStatus").className       = "modal-status pending";
    document.getElementById("qrStatus").textContent     = "⏳ Waiting for scan…";

    document.getElementById("qrOverlay").classList.add("show");

    /* Start countdown timer */
    clearInterval(qrTimerInterval);
    qrTimerInterval = setInterval(updateTimer, 1000);
    updateTimer();

    /* Poll every 2.5s */
    clearInterval(qrPollInterval);
    qrPollInterval = setInterval(pollQR, 2500);
}

function updateTimer() {
    const remaining = Math.max(0, Math.floor((qrExpires - Date.now()) / 1000));
    const m = String(Math.floor(remaining / 60)).padStart(2, "0");
    const s = String(remaining % 60).padStart(2, "0");
    document.getElementById("qrTimer").textContent = "Expires in " + m + ":" + s;
    if (remaining === 0) {
        clearInterval(qrTimerInterval);
        document.getElementById("qrStatus").className   = "modal-status expired";
        document.getElementById("qrStatus").textContent = "⏰ QR Expired";
        clearInterval(qrPollInterval);
    }
}

async function pollQR() {
    const resp = await fetch(`?action=poll_qr&token=${encodeURIComponent(qrToken)}`);
    const data = await resp.json();

    if (data.status === "completed") {
        clearInterval(qrPollInterval);
        clearInterval(qrTimerInterval);
        document.getElementById("qrStatus").className   = "modal-status completed";
        document.getElementById("qrStatus").textContent = "✅ Payment Received!";
        document.getElementById("qrTimer").textContent  = "";
        /* Refresh page after 2.5s so balance updates */
        setTimeout(() => { window.location.reload(); }, 2500);
    } else if (data.status === "expired") {
        clearInterval(qrPollInterval);
        clearInterval(qrTimerInterval);
        document.getElementById("qrStatus").className   = "modal-status expired";
        document.getElementById("qrStatus").textContent = "⏰ QR Expired";
    }
}

function closeQR() {
    clearInterval(qrPollInterval);
    clearInterval(qrTimerInterval);
    document.getElementById("qrOverlay").classList.remove("show");
    qrToken = null;
}

/* Close overlay when clicking outside modal */
document.getElementById("qrOverlay").addEventListener("click", function(e) {
    if (e.target === this) closeQR();
});

/* ════ SCAN CUSTOMER QR (shop reads the customer's "My QR") ════ */
let shopQr = null;
let shopScanned = false;
function openShopScanner(){
    const ov = document.getElementById('shopScanOverlay');
    const msg = document.getElementById('shopScanMsg');
    if (typeof Html5Qrcode === 'undefined'){ alert('Scanner not loaded. Please check your connection and try again.'); return; }
    ov.style.display = 'flex';
    shopScanned = false;
    if (msg) msg.textContent = 'Point the camera at the customer’s QR';
    if (!shopQr) shopQr = new Html5Qrcode('shopReader');
    shopQr.start({ facingMode: 'environment' }, { fps: 10, qrbox: { width: 240, height: 240 } }, onShopScan)
        .catch(function(){
            if (msg) msg.textContent = 'Cannot open the camera. Allow camera access, or enter the Pay ID / phone manually.';
        });
}
function closeShopScanner(){
    const ov = document.getElementById('shopScanOverlay');
    const hide = function(){ ov.style.display = 'none'; };
    if (shopQr){ shopQr.stop().then(hide).catch(hide); } else { hide(); }
}
function onShopScan(decodedText){
    if (shopScanned) return;
    shopScanned = true;
    let raw = (decodedText || '').trim();
    let code = '';
    /* if the QR is a URL, read its ?to= / ?code= / ?u= parameter; else use the raw text */
    try { const u = new URL(raw); code = u.searchParams.get('to') || u.searchParams.get('code') || u.searchParams.get('u') || ''; } catch(e){}
    if (!code) code = raw;
    code = code.trim();
    const finish = function(){
        document.getElementById('shopScanOverlay').style.display = 'none';
        const inp = document.getElementById('searchInput');
        if (inp){ inp.value = code; }
        if (code) searchCustomer();
    };
    if (shopQr){ shopQr.stop().then(finish).catch(finish); } else { finish(); }
}
</script>

<!-- camera scanner overlay -->
<div id="shopScanOverlay">
    <div class="sheet">
        <div id="shopReader"></div>
        <p id="shopScanMsg">Point the camera at the customer&rsquo;s QR</p>
        <button type="button" class="scan-cancel" onclick="closeShopScanner()">Cancel</button>
    </div>
</div>
<script src="https://unpkg.com/html5-qrcode"></script>

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