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

$token = trim($_GET["token"] ?? "");

if (!$token) {
    die("Invalid QR link.");
}

/* Load the session */
try {
    $stmt = $pdo->prepare("
        SELECT s.*, p.shop_name, p.credit_balance,
               c.full_name, c.customer_code, c.phone, c.balance AS customer_balance
        FROM qr_topup_sessions s
        JOIN partner_shops p ON p.id = s.partner_shop_id
        JOIN customers c     ON c.id = s.customer_id
        WHERE s.token = ?
        LIMIT 1
    ");
    $stmt->execute([$token]);
    $session = $stmt->fetch(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    die("QR system not ready: " . $e->getMessage());
}

if (!$session) {
    die("QR code not found.");
}

$status  = $session["status"];
$expired = strtotime($session["expires_at"]) < time();
$error   = "";
$success = false;

/* ── Process: customer confirms by visiting this page ── */
if ($status === "pending" && !$expired && isset($_GET["confirm"])) {
    try {
        $pdo->beginTransaction();

        /* Re-check partner credit */
        $shop = $pdo->prepare("SELECT credit_balance FROM partner_shops WHERE id = ? FOR UPDATE");
        $shop->execute([$session["partner_shop_id"]]);
        $shopRow = $shop->fetch(PDO::FETCH_ASSOC);

        if ($shopRow["credit_balance"] < $session["amount"]) {
            $pdo->rollBack();
            $error = "Partner does not have enough credit.";
        } else {
            $pdo->prepare("UPDATE partner_shops SET credit_balance = credit_balance - ? WHERE id = ?")
                ->execute([$session["amount"], $session["partner_shop_id"]]);

            $pdo->prepare("UPDATE customers SET balance = balance + ? WHERE id = ?")
                ->execute([$session["amount"], $session["customer_id"]]);

            $tx_code = "QTX" . time();
            $pdo->prepare("INSERT INTO wallet_transactions
                (transaction_code, customer_id, partner_shop_id, amount, transaction_type, remarks)
                VALUES (?, ?, ?, ?, 'topup', 'QR Top-up')")
                ->execute([$tx_code, $session["customer_id"], $session["partner_shop_id"], $session["amount"]]);

            /* Customer notification */
            $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([$session["partner_shop_id"], $session["customer_id"], $session["amount"]]);

            /* Mark session complete */
            $pdo->prepare("UPDATE qr_topup_sessions SET status='completed', completed_at=NOW() WHERE token=?")
                ->execute([$token]);

            $pdo->commit();
            require_once __DIR__ . '/../config/notify.php';
            notify_money_received($pdo, (int)$session["customer_id"], (float)$session["amount"], "a shop");
            $status  = "completed";
            $success = true;
        }
    } catch (Throwable $e) {
        $pdo->rollBack();
        $error = "Error: " . $e->getMessage();
    }
}

/* Mark expired in DB if needed */
if ($status === "pending" && $expired) {
    try {
        $pdo->prepare("UPDATE qr_topup_sessions SET status='expired' WHERE token=?")
            ->execute([$token]);
        $status = "expired";
    } catch (Throwable $e) {}
}
?>
<!DOCTYPE html>
<html lang="lo">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Confirm Top-Up</title>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Lao:wght@400;600;700;800&family=Inter:wght@400;600;700&display=swap" rel="stylesheet">
    <style>
        * { box-sizing: border-box; margin: 0; padding: 0; }

        body {
            font-family: "Noto Sans Lao", "Inter", Arial, sans-serif;
            background: linear-gradient(145deg, #0f2444 0%, #1e3a5f 50%, #1d4ed8 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }

        .card {
            background: #fff;
            border-radius: 24px;
            padding: 36px 32px;
            max-width: 420px;
            width: 100%;
            text-align: center;
            box-shadow: 0 24px 64px rgba(0,0,0,.28);
        }

        .logo { font-size: 48px; margin-bottom: 10px; }

        .shop-name {
            font-size: 15px; color: #64748b;
            font-weight: 600; margin-bottom: 20px;
        }

        .amount-box {
            background: #f0f9ff;
            border: 2px solid #bae6fd;
            border-radius: 16px;
            padding: 20px;
            margin-bottom: 22px;
        }

        .amount-label {
            font-size: 12px; font-weight: 700;
            color: #0369a1; text-transform: uppercase;
            letter-spacing: .6px; margin-bottom: 8px;
        }

        .amount-value {
            font-size: 38px; font-weight: 800;
            color: #1d4ed8; letter-spacing: -1px;
        }

        .amount-value .cur { font-size: 18px; color: #64748b; margin-right: 3px; }

        .customer-box {
            background: #f8faff;
            border: 1px solid #e2e8f0;
            border-radius: 12px;
            padding: 14px 16px;
            margin-bottom: 22px;
            text-align: left;
        }

        .customer-box .row {
            display: flex; justify-content: space-between;
            font-size: 13px; padding: 4px 0;
        }

        .customer-box .row .key { color: #64748b; font-weight: 600; }
        .customer-box .row .val { color: #0f172a; font-weight: 700; }

        /* Status displays */
        .status-block {
            border-radius: 14px;
            padding: 22px;
            margin-bottom: 18px;
        }

        .status-block .status-icon { font-size: 44px; margin-bottom: 10px; }
        .status-block .status-text { font-size: 18px; font-weight: 800; }
        .status-block .status-sub  { font-size: 13px; margin-top: 6px; color: #64748b; }

        .status-success { background: #f0fdf4; border: 2px solid #86efac; }
        .status-success .status-text { color: #16a34a; }

        .status-expired { background: #fff1f2; border: 2px solid #fca5a5; }
        .status-expired .status-text { color: #dc2626; }

        /* Confirm button */
        .confirm-btn {
            display: block; width: 100%;
            padding: 16px;
            background: #16a34a; color: #fff;
            border: none; border-radius: 12px;
            font-size: 17px; font-weight: 800;
            font-family: inherit; cursor: pointer;
            text-decoration: none;
            transition: background .15s, transform .1s;
            margin-bottom: 10px;
        }

        .confirm-btn:hover { background: #15803d; transform: translateY(-2px); }
        .confirm-btn:active { transform: translateY(0); }

        .cancel-link {
            font-size: 13px; color: #94a3b8;
            text-decoration: none; display: block;
        }

        .cancel-link:hover { color: #64748b; }

        .error-box {
            background: #fee2e2; border: 1px solid #fca5a5;
            border-radius: 10px; padding: 12px 14px;
            color: #991b1b; font-size: 14px; font-weight: 600;
            margin-bottom: 14px;
        }
    </style>
</head>
<body>
<div class="card">

    <div class="logo">⚡</div>
    <div class="shop-name"><?= htmlspecialchars($session["shop_name"]) ?></div>

    <?php if ($error): ?>
        <div class="error-box">⚠️ <?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <?php if ($status === "completed"): ?>
        <div class="status-block status-success">
            <div class="status-icon">✅</div>
            <div class="status-text">ຮັບເຄຣດິດສຳເລັດ!</div>
            <div class="status-text" style="font-size:15px;margin-top:4px;">Top-Up Successful!</div>
            <div class="status-sub">
                ₭<?= number_format($session["amount"], 2) ?> credited to your wallet.
            </div>
        </div>

        <div class="customer-box">
            <div class="row"><span class="key">Name</span><span class="val"><?= htmlspecialchars($session["full_name"]) ?></span></div>
            <div class="row"><span class="key">Amount</span><span class="val" style="color:#16a34a;">+₭<?= number_format($session["amount"], 2) ?></span></div>
        </div>

    <?php elseif ($status === "expired"): ?>
        <div class="status-block status-expired">
            <div class="status-icon">⏰</div>
            <div class="status-text">QR Expired</div>
            <div class="status-sub">This QR code has expired. Please ask for a new one.</div>
        </div>

    <?php else: /* pending — show confirm screen */ ?>

        <div class="amount-box">
            <div class="amount-label">ຈຳນວນເງີນ / Amount to Receive</div>
            <div class="amount-value">
                <span class="cur">₭</span><?= number_format($session["amount"], 2) ?>
            </div>
        </div>

        <div class="customer-box">
            <div class="row">
                <span class="key">ຊື່ / Name</span>
                <span class="val"><?= htmlspecialchars($session["full_name"]) ?></span>
            </div>
            <div class="row">
                <span class="key">Code</span>
                <span class="val"><?= htmlspecialchars($session["customer_code"]) ?></span>
            </div>
            <div class="row">
                <span class="key">Phone</span>
                <span class="val"><?= htmlspecialchars($session["phone"]) ?></span>
            </div>
            <div class="row">
                <span class="key">ຍອດປັດຈຸບັນ / Current Balance</span>
                <span class="val">₭<?= number_format($session["customer_balance"], 2) ?></span>
            </div>
        </div>

        <a class="confirm-btn" href="?token=<?= urlencode($token) ?>&confirm=1">
            ✅ ຢືນຢັນຮັບເຄຣດິດ / Confirm
        </a>
        <a class="cancel-link" href="#">Cancel</a>

    <?php endif; ?>

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