<?php
/**
 * TOPBD — bKash Payment Gateway Handler & Sandbox Portal
 */

require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/PaymentManager.php';

$txnId = trim($_GET['txn_id'] ?? $_POST['paymentID'] ?? '');
$paymentId = trim($_GET['paymentID'] ?? $_POST['paymentID'] ?? '');
$status = trim($_GET['status'] ?? $_POST['status'] ?? '');

if (empty($txnId)) {
    header("Location: /?payment_status=error&message=" . urlencode("Missing bKash transaction reference."));
    exit;
}

$db = get_db();
$stmt = $db->prepare("SELECT * FROM payments WHERE transaction_id = ? LIMIT 1");
$stmt->execute([$txnId]);
$pay = $stmt->fetch();

if (!$pay) {
    header("Location: /?payment_status=error&message=" . urlencode("Payment record not found."));
    exit;
}

// Check if customer cancelled from bKash callback
if ($status === 'cancel' || $status === 'failure') {
    $cancelStmt = $db->prepare("UPDATE payments SET status = 'cancelled' WHERE transaction_id = ?");
    $cancelStmt->execute([$txnId]);
    header("Location: /?payment_status=cancelled");
    exit;
}

// If callback with success status from live bKash
if ($status === 'success' && !empty($paymentId)) {
    try {
        $res = PaymentManager::verifyAndActivatePayment($txnId, ['paymentID' => $paymentId, 'status' => $status]);
        header("Location: /?payment_status=success&txn_id=" . urlencode($txnId));
        exit;
    } catch (Exception $e) {
        header("Location: /?payment_status=error&message=" . urlencode($e->getMessage()));
        exit;
    }
}

// If form posted from sandbox portal
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    if ($action === 'confirm') {
        try {
            PaymentManager::verifyAndActivatePayment($txnId, ['mode' => 'sandbox_confirm']);
            header("Location: /?payment_status=success&txn_id=" . urlencode($txnId));
            exit;
        } catch (Exception $e) {
            $error = $e->getMessage();
        }
    } else {
        $cancelStmt = $db->prepare("UPDATE payments SET status = 'cancelled' WHERE transaction_id = ?");
        $cancelStmt->execute([$txnId]);
        header("Location: /?payment_status=cancelled");
        exit;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>bKash Payment Gateway — TOPBD</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        body { background-color: #0A0D0F; color: #F0F4F8; font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; }
    </style>
</head>
<body class="min-h-screen flex items-center justify-center p-4">
    <div class="max-w-md w-full rounded-2xl bg-[#13181D] border border-pink-600/40 p-6 shadow-2xl space-y-5">
        <!-- Header -->
        <div class="flex items-center justify-between border-b border-pink-900/40 pb-4">
            <div class="flex items-center gap-3">
                <div class="w-10 h-10 rounded-xl bg-pink-600 flex items-center justify-center font-bold text-white text-lg shadow-lg shadow-pink-950/60">
                    bK
                </div>
                <div>
                    <h2 class="font-bold text-base text-white">bKash Payment Portal</h2>
                    <span class="text-xs text-pink-400 font-mono"><?= $pay['mode'] === 'live' ? 'LIVE PRODUCTION' : 'SANDBOX TEST GATEWAY' ?></span>
                </div>
            </div>
            <span class="text-xs px-2.5 py-1 rounded bg-pink-950/80 text-pink-300 font-mono font-bold border border-pink-800/60">৳<?= number_format($pay['amount'], 0) ?></span>
        </div>

        <?php if (!empty($_GET['error'])): ?>
            <div class="p-3 rounded-xl bg-amber-950/60 border border-amber-800/60 text-xs text-amber-300">
                ⚠️ Live API Credentials not yet configured in Admin Settings. Operating in safe test verification mode.
            </div>
        <?php endif; ?>

        <?php if (!empty($error)): ?>
            <div class="p-3 rounded-xl bg-rose-950/60 border border-rose-800/60 text-xs text-rose-300">
                ❌ <?= e($error) ?>
            </div>
        <?php endif; ?>

        <!-- Order Summary -->
        <div class="p-4 rounded-xl bg-[#0A0D0F] border border-[#222A33] space-y-2 text-xs font-mono">
            <div class="flex justify-between">
                <span class="text-slate-400">Merchant:</span>
                <span class="text-white font-bold">TOPBD Ranking Hub</span>
            </div>
            <div class="flex justify-between">
                <span class="text-slate-400">Target Listing:</span>
                <span class="text-emerald-400 font-bold truncate max-w-[180px]"><?= e($pay['listing_name']) ?></span>
            </div>
            <div class="flex justify-between">
                <span class="text-slate-400">Invoice Reference:</span>
                <span class="text-slate-300"><?= e($pay['transaction_id']) ?></span>
            </div>
            <div class="flex justify-between border-t border-[#222A33] pt-2">
                <span class="text-slate-400">Total Outbid Amount:</span>
                <span class="text-pink-400 font-bold text-sm">৳<?= number_format($pay['amount'], 0) ?></span>
            </div>
        </div>

        <!-- Payment Actions -->
        <form method="POST" class="space-y-4">
            <div class="space-y-1.5">
                <label class="block text-xs text-slate-300 font-medium">bKash Wallet Number</label>
                <input type="text" value="01700000000 (Sandbox Wallet)" class="w-full px-3.5 py-2.5 bg-[#0A0D0F] border border-[#222A33] rounded-xl text-white font-mono text-xs" readonly />
            </div>

            <div class="flex gap-3">
                <button type="submit" name="action" value="cancel" class="flex-1 py-2.5 rounded-xl bg-slate-800 hover:bg-slate-700 text-slate-300 font-bold text-xs transition cursor-pointer">
                    Cancel
                </button>
                <button type="submit" name="action" value="confirm" class="flex-1 py-2.5 rounded-xl bg-pink-600 hover:bg-pink-500 text-white font-bold text-xs shadow-lg shadow-pink-950/60 transition cursor-pointer">
                    Confirm & Verify ৳<?= number_format($pay['amount'], 0) ?>
                </button>
            </div>
        </form>
    </div>
</body>
</html>
