<?php
/**
 * TOPBD — DBBL Rocket 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['txn_id'] ?? '');
if (empty($txnId)) {
    header("Location: /?payment_status=error&message=" . urlencode("Missing Rocket 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;
}

$config = PaymentManager::getGatewayConfig('rocket');
$isLive = ($pay['mode'] === 'live');
$credentialsConfigured = !empty($config['merchant_id']) && !empty($config['app_key']) && !empty($config['api_url']);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    if ($action === 'confirm') {
        if ($isLive && !$credentialsConfigured) {
            $error = "Official DBBL Rocket merchant API credentials & gateway integration are required for Live payment processing.";
        } else {
            try {
                PaymentManager::verifyAndActivatePayment($txnId, $_POST);
                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>DBBL Rocket Payment — 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-purple-600/40 p-6 shadow-2xl space-y-5">
        <div class="flex items-center justify-between border-b border-purple-900/40 pb-4">
            <div class="flex items-center gap-3">
                <div class="w-10 h-10 rounded-xl bg-purple-600 flex items-center justify-center font-bold text-white text-lg shadow-lg shadow-purple-950/60">
                    🚀
                </div>
                <div>
                    <h2 class="font-bold text-base text-white">DBBL Rocket Pay</h2>
                    <span class="text-xs text-purple-400 font-mono"><?= $isLive ? 'LIVE PRODUCTION GATEWAY' : 'SANDBOX TEST GATEWAY' ?></span>
                </div>
            </div>
            <span class="text-xs px-2.5 py-1 rounded bg-purple-950/80 text-purple-300 font-mono font-bold border border-purple-800/60">৳<?= number_format($pay['amount'], 0) ?></span>
        </div>

        <?php if ($isLive && !$credentialsConfigured): ?>
            <div class="p-3.5 rounded-xl bg-amber-950/60 border border-amber-800/60 text-xs text-amber-300 space-y-1">
                <div class="font-bold flex items-center gap-1.5">
                    <span>⚠️</span>
                    <span>Official gateway credentials/API access are required.</span>
                </div>
                <p class="text-amber-200/80">DBBL Rocket Biller ID, Secret Token, and Gateway Endpoint must be configured in Admin Settings for Live verification.</p>
            </div>
        <?php endif; ?>

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

        <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">Rocket Biller ID:</span>
                <span class="text-white font-bold"><?= !empty($config['merchant_id']) ? e($config['merchant_id']) : 'TOPBD-DBBL' ?></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">Transaction ID:</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">Payable Amount:</span>
                <span class="text-purple-400 font-bold text-sm">৳<?= number_format($pay['amount'], 0) ?></span>
            </div>
        </div>

        <form method="POST" class="space-y-4">
            <?php if (!$isLive): ?>
                <div class="space-y-1.5">
                    <label class="block text-xs text-slate-300 font-medium">Rocket 12-Digit Test Account</label>
                    <input type="text" value="019000000009 (Sandbox Account)" class="w-full px-3.5 py-2.5 bg-[#0A0D0F] border border-[#222A33] rounded-xl text-white font-mono text-xs" readonly />
                </div>
            <?php else: ?>
                <div class="space-y-1.5">
                    <label class="block text-xs text-slate-300 font-medium">Rocket Transaction Reference / Trx ID</label>
                    <input type="text" name="rocket_trx_id" placeholder="Enter DBBL Rocket Transaction ID" class="w-full px-3.5 py-2.5 bg-[#0A0D0F] border border-[#222A33] rounded-xl text-white font-mono text-xs" required />
                </div>
            <?php endif; ?>

            <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-purple-600 hover:bg-purple-500 text-white font-bold text-xs shadow-lg shadow-purple-950/60 transition cursor-pointer">
                    <?= $isLive ? 'Verify with Rocket' : 'Simulate Test Payment' ?> ৳<?= number_format($pay['amount'], 0) ?>
                </button>
            </div>
        </form>
    </div>
</body>
</html>
