<?php
/**
 * TOPBD — SSLCommerz Payment Gateway & IPN Callback Verification Handler
 */

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

$txnId = trim($_GET['txn_id'] ?? $_POST['tran_id'] ?? '');
$valId = trim($_GET['val_id'] ?? $_POST['val_id'] ?? '');
$status = trim($_GET['status'] ?? $_POST['status'] ?? $_GET['action'] ?? '');

if (empty($txnId)) {
    header("Location: /?payment_status=error&message=" . urlencode("SSLCommerz transaction ID missing."));
    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;
}

// Handle Cancel / Fail from SSLCommerz Hosted Gateway
if ($status === 'cancel' || $status === 'FAILED' || $status === 'CANCELLED') {
    $cancelStmt = $db->prepare("UPDATE payments SET status = 'cancelled' WHERE transaction_id = ?");
    $cancelStmt->execute([$txnId]);
    header("Location: /?payment_status=cancelled");
    exit;
}

// If callback from live SSLCommerz with val_id or VALID status
if (!empty($valId) || $status === 'VALID' || $status === 'VALIDATED') {
    try {
        PaymentManager::verifyAndActivatePayment($txnId, ['val_id' => $valId, '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>SSLCommerz 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-blue-600/40 p-6 shadow-2xl space-y-5">
        <div class="flex items-center justify-between border-b border-blue-900/40 pb-4">
            <div class="flex items-center gap-3">
                <div class="w-10 h-10 rounded-xl bg-blue-600 flex items-center justify-center font-bold text-white text-lg shadow-lg shadow-blue-950/60">
                    SSL
                </div>
                <div>
                    <h2 class="font-bold text-base text-white">SSLCommerz Hosted Pay</h2>
                    <span class="text-xs text-blue-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-blue-950/80 text-blue-300 font-mono font-bold border border-blue-800/60">৳<?= number_format($pay['amount'], 0) ?></span>
        </div>

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

        <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">Accepted Methods:</span>
                <span class="text-white font-bold">VISA / MasterCard / MFS / Cards</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-blue-400 font-bold text-sm">৳<?= number_format($pay['amount'], 0) ?></span>
            </div>
        </div>

        <form method="POST" class="space-y-4">
            <div class="p-3 rounded-xl bg-[#0A0D0F] border border-[#222A33] text-xs text-slate-400 space-y-1">
                <div class="text-white font-semibold flex items-center gap-1.5">
                    <span>🛡️</span> SSLCommerz 256-bit Encrypted Check-out
                </div>
                <p class="text-[11px]">Sandbox environment with automated instant server-side verification.</p>
            </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-blue-600 hover:bg-blue-500 text-white font-bold text-xs shadow-lg shadow-blue-950/60 transition cursor-pointer">
                    Confirm & Verify ৳<?= number_format($pay['amount'], 0) ?>
                </button>
            </div>
        </form>
    </div>
</body>
</html>
