<?php
// Initialize session safely
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/../../config/config.php';

// Must be logged in
if (!isset($_SESSION['user_id'])) {
    header("Location: ../login-register.php?redirect=user/billing.php");
    exit();
}

$user_id = $_SESSION['user_id'];

// CSRF token
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

$error_msg = '';
$success_msg = '';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'] ?? '')) {
        die("Security Error: Invalid CSRF Token.");
    }

    $plan_id = filter_input(INPUT_POST, 'plan_id', FILTER_VALIDATE_INT);
    $gateway = trim($_POST['gateway'] ?? '');

    if (!$plan_id) {
        $error_msg = "Invalid subscription plan selected.";
    } else {
        $plan_stmt = $pdo->prepare("SELECT id, plan_name, price, duration_days FROM subscription_plans WHERE id = ? AND status = 'active'");
        $plan_stmt->execute([$plan_id]);
        $selected_plan = $plan_stmt->fetch(PDO::FETCH_ASSOC);

        if (!$selected_plan) {
            $error_msg = "The selected subscription plan is no longer available.";
        } else {
            $_SESSION['invoice_data'] = [
                'user_id'   => $user_id,
                'plan_id'   => $selected_plan['id'],
                'amount'    => $selected_plan['price'],
                'plan_name' => $selected_plan['plan_name'],
                'duration'  => $selected_plan['duration_days']
            ];

            if ($gateway === 'paystack') {
                header("Location: gateways/paystack-checkout.php");
                exit();
            } elseif ($gateway === 'stripe') {
                header("Location: gateways/stripe-checkout.php");
                exit();
            } elseif ($gateway === 'nowpayments') {
                header("Location: gateways/nowpayments-checkout.php");
                exit();
            } elseif ($gateway === 'crypto') {
                // Manual crypto processing...
                $tx_hash = trim($_POST['tx_hash'] ?? '');
                if (empty($tx_hash) || !preg_match('/^[a-zA-Z0-9]{8,128}$/', $tx_hash)) {
                    $error_msg = "A valid transaction hash is required.";
                } elseif (!isset($_FILES['receipt']) || $_FILES['receipt']['error'] !== UPLOAD_ERR_OK) {
                    $error_msg = "Receipt proof is required.";
                } else {
                    $upload_dir = __DIR__ . '/../../uploads/receipts';
                    if (!is_dir($upload_dir)) mkdir($upload_dir, 0755, true);

                    $file_ext = strtolower(pathinfo($_FILES['receipt']['name'], PATHINFO_EXTENSION));
                    $allowed_exts = ['jpg', 'jpeg', 'png', 'pdf'];

                    if (!in_array($file_ext, $allowed_exts)) {
                        $error_msg = "Invalid file type. Only JPG, PNG, or PDF allowed.";
                    } else {
                        $new_filename = 'receipt_' . $user_id . '_' . time() . '.' . $file_ext;
                        $destination = $upload_dir . '/' . $new_filename;

                        if (move_uploaded_file($_FILES['receipt']['tmp_name'], $destination)) {
                            $receipt_path = 'uploads/receipts/' . $new_filename;
                            $stmt = $pdo->prepare("INSERT INTO transactions (user_id, plan_id, amount_paid, payment_method, receipt_path, tx_hash, status) VALUES (?, ?, ?, 'Manual Cryptocurrency', ?, ?, 'pending')");
                            $stmt->execute([$user_id, $selected_plan['id'], $selected_plan['price'], $receipt_path, $tx_hash]);
                            $success_msg = "Payment proof submitted. Admin will verify shortly.";
                        } else {
                            $error_msg = "File upload failed. Please try again.";
                        }
                    }
                }
            } else {
                $error_msg = "Please select a valid payment method.";
            }
        }
    }
}

// Fetch plans
$active_plans = [];
try {
    $stmt = $pdo->query("SELECT * FROM subscription_plans WHERE status = 'active' ORDER BY price ASC");
    $active_plans = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {}

// Fetch gateway statuses
$active_gateways = [];
try {
    $stmt = $pdo->query("SELECT key_name, key_value FROM payment_settings WHERE key_name IN ('paystack_status', 'stripe_status', 'nowpayments_status')");
    $gateways_status = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
    if (($gateways_status['paystack_status'] ?? '') === 'active') $active_gateways['paystack'] = 'Paystack';
    if (($gateways_status['stripe_status'] ?? '') === 'active') $active_gateways['stripe'] = 'Stripe';
    if (($gateways_status['nowpayments_status'] ?? '') === 'active') $active_gateways['nowpayments'] = 'NowPayments';
} catch (PDOException $e) {}

// Crypto addresses
$crypto_addresses = [];
try {
    $stmt = $pdo->query("SELECT key_name, key_value FROM payment_settings WHERE key_name IN ('manual_btc_address', 'manual_usdt_trc20')");
    $crypto_addresses = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
} catch (PDOException $e) {}

// Fetch exchange rate
$rate_stmt = $pdo->query("SELECT key_value FROM payment_settings WHERE key_name = 'usd_ngn_rate'");
$rate = $rate_stmt->fetchColumn() ?: 1500.00;

// Check step
$step = (isset($_GET['plan_id']) && ctype_digit($_GET['plan_id'])) ? 2 : 1;
$checkout_plan = null;
if ($step === 2) {
    $plan_id = intval($_GET['plan_id']);
    $p_stmt = $pdo->prepare("SELECT id, plan_name, price, duration_days FROM subscription_plans WHERE id = ? AND status = 'active'");
    $p_stmt->execute([$plan_id]);
    $checkout_plan = $p_stmt->fetch(PDO::FETCH_ASSOC);
    if (!$checkout_plan) {
        header("Location: billing.php");
        exit();
    }
}
?>
<!DOCTYPE html>
<html lang="en" class="dark">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Billing & Subscriptions - tipspac</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
    <style>
        ::-webkit-scrollbar { width: 6px; }
        ::-webkit-scrollbar-track { background: #020617; }
        ::-webkit-scrollbar-thumb { background: #1e293b; border-radius: 10px; }
        ::-webkit-scrollbar-thumb:hover { background: #334155; }
        [x-cloak] { display: none !important; }
        body {
            background: #020617;
            background-image: radial-gradient(circle at 10% 20%, rgba(16, 185, 129, 0.05) 0%, transparent 40%),
                              radial-gradient(circle at 90% 80%, rgba(59, 130, 246, 0.05) 0%, transparent 40%);
        }
    </style>
</head>
<body class="text-slate-300 font-sans antialiased min-h-screen relative overflow-x-hidden flex flex-col md:flex-row">

    <div class="fixed inset-0 z-0 pointer-events-none opacity-20 bg-cover bg-center bg-no-repeat" style="background-image: url('https://images.unsplash.com/photo-1579952363873-27f3bade9f55?q=80&w=2000&auto=format&fit=crop');"></div>
    <div class="fixed inset-0 z-0 bg-gradient-to-t from-[#020617] via-[#020617]/90 to-[#020617]/80 pointer-events-none"></div>

    <?php require_once __DIR__ . '/includes/sidebar.php'; ?>

    <div class="relative z-10 flex flex-col min-h-screen flex-1 md:pl-64 transition-all duration-300 w-full">
        
        <!-- Mobile header -->
        <header class="md:hidden w-full border-b border-slate-800/60 bg-slate-950/80 backdrop-blur-md h-16 flex items-center justify-between px-4 sticky top-0 z-30">
            <div class="text-white font-black tracking-tighter text-lg flex items-center space-x-2">
                <span class="w-2 h-2 rounded-full bg-emerald-500 animate-pulse"></span>
                <span>tipspac <span class="text-emerald-400">Pro</span></span>
            </div>
            <button onclick="document.getElementById('sidebar').classList.toggle('-translate-x-full'); document.getElementById('sidebarOverlay').classList.toggle('hidden');" class="text-slate-300 hover:text-white p-2 focus:outline-none">
                <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16"></path></svg>
            </button>
        </header>

        <main class="w-full max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-8 space-y-8">
            
            <!-- Header -->
            <div>
                <div class="inline-flex items-center space-x-2 mb-2">
                    <span class="bg-slate-800 text-slate-400 border border-slate-700 px-2.5 py-0.5 rounded text-[9px] font-black uppercase tracking-widest">🛡️ Billing System</span>
                </div>
                <h1 class="text-3xl md:text-5xl font-black text-white tracking-tight">Subscription <span class="text-emerald-400">Ledger</span></h1>
                <p class="text-xs text-slate-400 mt-2 max-w-xl">Choose your plan and pay in USD or NGN. All prices include VAT.</p>
            </div>

            <!-- Messages -->
            <?php if(!empty($success_msg)): ?>
                <div class="bg-emerald-500/10 border border-emerald-500/30 text-emerald-400 p-4 rounded-2xl text-xs font-bold tracking-wide shadow-sm flex items-center">
                    ✅ <?php echo $success_msg; ?>
                </div>
            <?php endif; ?>
            <?php if(!empty($error_msg)): ?>
                <div class="bg-rose-500/10 border border-rose-500/30 text-rose-400 p-4 rounded-2xl text-xs font-bold tracking-wide shadow-sm flex items-center">
                    ❌ <?php echo $error_msg; ?>
                </div>
            <?php endif; ?>

            <?php if ($step === 1): ?>
                <!-- Step 1: Choose Plan -->
                <div class="pt-4">
                    <h3 class="text-xl md:text-2xl font-black text-white tracking-tight mb-6">Select Your Membership</h3>
                    
                    <?php if(empty($active_plans)): ?>
                        <div class="bg-slate-900/40 border border-slate-800 rounded-3xl p-12 text-center">
                            <span class="text-slate-500 text-xs font-bold uppercase tracking-widest">No plans available</span>
                        </div>
                    <?php else: ?>
                        <div class="grid grid-cols-1 md:grid-cols-3 gap-8">
                            <?php foreach($active_plans as $plan): 
                                // Determine NGN price: use price_ngn if exists, else calculate
                                $price_ngn = $plan['price_ngn'] ?? ($plan['price'] * $rate);
                            ?>
                                <div class="bg-slate-900/50 backdrop-blur-lg border border-slate-800 hover:border-emerald-500/50 rounded-3xl p-6 flex flex-col justify-between relative transition-all duration-300 group">
                                    <?php if ($plan['is_popular']): ?>
                                        <div class="absolute -top-3 left-1/2 transform -translate-x-1/2 bg-gradient-to-r from-emerald-500 to-teal-500 text-white font-black text-[9px] tracking-widest uppercase px-3 py-1 rounded-full shadow-lg">
                                            Most Popular
                                        </div>
                                    <?php endif; ?>

                                    <div>
                                        <span class="text-xs font-black tracking-widest uppercase text-slate-400 mb-2 block text-center"><?= htmlspecialchars($plan['plan_name']); ?></span>
                                        
                                        <!-- USD Price -->
                                        <div class="flex items-center justify-center space-x-1 mb-2 border-b border-slate-800/60 pb-4">
                                            <span class="text-4xl font-black text-white tracking-tight group-hover:text-emerald-400 transition-colors">$<?= number_format($plan['price'], 2); ?></span>
                                            <span class="text-xs text-slate-500 font-bold mt-2">/ <?= intval($plan['duration_days']); ?>d</span>
                                        </div>
                                        <!-- NGN Price -->
                                        <div class="text-center text-sm font-bold text-amber-400 mb-4">
                                            ₦<?= number_format($price_ngn, 0); ?> <span class="text-[9px] text-slate-500 font-normal">(NGN)</span>
                                        </div>
                                        
                                        <ul class="text-left space-y-3 mb-6 h-40">
                                            <?php 
                                            $features = explode("\n", $plan['features']);
                                            foreach(array_filter(array_map('trim', $features)) as $feature):
                                            ?>
                                                <li class="flex items-start text-[11px] text-slate-300 font-medium">
                                                    <svg class="w-4 h-4 text-emerald-400 mr-2.5 shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path></svg>
                                                    <span><?= htmlspecialchars($feature); ?></span>
                                                </li>
                                            <?php endforeach; ?>
                                        </ul>
                                    </div>

                                    <a href="billing.php?plan_id=<?= $plan['id']; ?>" class="w-full text-center bg-slate-800 hover:bg-gradient-to-r hover:from-emerald-500 hover:to-teal-500 border border-slate-700 hover:border-transparent text-white font-black py-4 rounded-xl text-[10px] uppercase tracking-widest transition-all shadow-sm mt-4">
                                        Select Plan
                                    </a>
                                </div>
                            <?php endforeach; ?>
                        </div>
                        <!-- Exchange rate note -->
                        <div class="text-center text-[9px] text-slate-500 mt-4">
                            💱 1 USD = ₦<?= number_format($rate, 2) ?> (NGN prices updated automatically)
                        </div>
                    <?php endif; ?>
                </div>

            <?php elseif ($step === 2): ?>
                <!-- Step 2: Checkout – same as before, but we also show NGN in summary -->
                <div class="pt-4" x-data="checkoutProcessState()">
                    <div class="flex items-center justify-between mb-8">
                        <div>
                            <h3 class="text-xl md:text-2xl font-black text-white tracking-tight">Secure Checkout</h3>
                            <p class="text-[10px] text-slate-400 mt-1">Plan: <strong class="text-emerald-400"><?= htmlspecialchars($checkout_plan['plan_name']); ?></strong></p>
                        </div>
                        <a href="billing.php" class="bg-slate-800 hover:bg-slate-700 border border-slate-700 text-white font-black text-[9px] uppercase tracking-widest px-5 py-2.5 rounded-xl transition">← Change Plan</a>
                    </div>

                    <form action="billing.php" method="POST" enctype="multipart/form-data" class="grid grid-cols-1 lg:grid-cols-12 gap-8 items-start">
                        <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
                        <input type="hidden" name="plan_id" value="<?php echo $checkout_plan['id']; ?>">

                        <div class="lg:col-span-7 xl:col-span-8 space-y-6">
                            <div class="bg-slate-900/40 backdrop-blur-xl border border-slate-800 rounded-3xl p-6 md:p-8 shadow-2xl">
                                <h4 class="text-base font-black text-white tracking-wider uppercase mb-6 flex items-center">
                                    <span class="w-1.5 h-1.5 bg-emerald-500 rounded-full mr-3 animate-pulse"></span> Choose Payment Method
                                </h4>

                                <?php if (empty($active_gateways)): ?>
                                    <div class="bg-rose-500/10 border border-rose-500/20 text-rose-400 p-4 rounded-2xl text-xs font-bold text-center mb-4">
                                        ⚠️ No automated gateways are enabled. Please contact support.
                                    </div>
                                <?php else: ?>
                                    <!-- Paystack (NGN) -->
                                    <?php if (isset($active_gateways['paystack'])): ?>
                                        <div class="relative mb-4 flex items-center justify-between p-4 rounded-2xl border-2 transition-all duration-300 cursor-pointer group shadow-sm"
                                             :class="gateway === 'paystack' ? 'border-emerald-500 bg-emerald-500/5' : 'border-slate-800 bg-slate-950/40 hover:border-slate-700'"
                                             @click="gateway = 'paystack'">
                                            <input type="radio" name="gateway" value="paystack" class="hidden" x-model="gateway">
                                            <div class="flex items-center space-x-4">
                                                <div class="w-12 h-12 bg-slate-900 border border-slate-700 rounded-xl flex items-center justify-center text-lg shrink-0 text-cyan-400 shadow-inner">
                                                    💳
                                                </div>
                                                <div>
                                                    <h5 class="font-bold text-sm text-white">Paystack (NGN)</h5>
                                                    <p class="text-[10px] text-slate-400 mt-0.5">Pay in Nigerian Naira. Card & bank transfers.</p>
                                                    <span class="text-[8px] text-amber-400">≈ ₦<?= number_format($checkout_plan['price'] * $rate, 0); ?></span>
                                                </div>
                                            </div>
                                            <div class="w-5 h-5 rounded-full border-2 flex items-center justify-center transition-colors shrink-0"
                                                 :class="gateway === 'paystack' ? 'border-emerald-500 bg-emerald-500' : 'border-slate-700'">
                                                <div class="w-1.5 h-1.5 rounded-full bg-white" x-show="gateway === 'paystack'" x-cloak></div>
                                            </div>
                                        </div>
                                    <?php endif; ?>

                                    <!-- Stripe (USD) -->
                                    <?php if (isset($active_gateways['stripe'])): ?>
                                        <div class="relative mb-4 flex items-center justify-between p-4 rounded-2xl border-2 transition-all duration-300 cursor-pointer group shadow-sm"
                                             :class="gateway === 'stripe' ? 'border-emerald-500 bg-emerald-500/5' : 'border-slate-800 bg-slate-950/40 hover:border-slate-700'"
                                             @click="gateway = 'stripe'">
                                            <input type="radio" name="gateway" value="stripe" class="hidden" x-model="gateway">
                                            <div class="flex items-center space-x-4">
                                                <div class="w-12 h-12 bg-slate-900 border border-slate-700 rounded-xl flex items-center justify-center text-lg shrink-0 text-cyan-400 shadow-inner">
                                                    🏦
                                                </div>
                                                <div>
                                                    <h5 class="font-bold text-sm text-white">Stripe (USD)</h5>
                                                    <p class="text-[10px] text-slate-400 mt-0.5">Global credit card payments in USD.</p>
                                                </div>
                                            </div>
                                            <div class="w-5 h-5 rounded-full border-2 flex items-center justify-center transition-colors shrink-0"
                                                 :class="gateway === 'stripe' ? 'border-emerald-500 bg-emerald-500' : 'border-slate-700'">
                                                <div class="w-1.5 h-1.5 rounded-full bg-white" x-show="gateway === 'stripe'" x-cloak></div>
                                            </div>
                                        </div>
                                    <?php endif; ?>

                                    <!-- NowPayments (USD) -->
                                    <?php if (isset($active_gateways['nowpayments'])): ?>
                                        <div class="relative mb-4 flex items-center justify-between p-4 rounded-2xl border-2 transition-all duration-300 cursor-pointer group shadow-sm"
                                             :class="gateway === 'nowpayments' ? 'border-emerald-500 bg-emerald-500/5' : 'border-slate-800 bg-slate-950/40 hover:border-slate-700'"
                                             @click="gateway = 'nowpayments'">
                                            <input type="radio" name="gateway" value="nowpayments" class="hidden" x-model="gateway">
                                            <div class="flex items-center space-x-4">
                                                <div class="w-12 h-12 bg-slate-900 border border-slate-700 rounded-xl flex items-center justify-center text-lg shrink-0 text-cyan-400 shadow-inner">
                                                    🌐
                                                </div>
                                                <div>
                                                    <h5 class="font-bold text-sm text-white">NowPayments (USD)</h5>
                                                    <p class="text-[10px] text-slate-400 mt-0.5">Automated crypto payments in USD.</p>
                                                </div>
                                            </div>
                                            <div class="w-5 h-5 rounded-full border-2 flex items-center justify-center transition-colors shrink-0"
                                                 :class="gateway === 'nowpayments' ? 'border-emerald-500 bg-emerald-500' : 'border-slate-700'">
                                                <div class="w-1.5 h-1.5 rounded-full bg-white" x-show="gateway === 'nowpayments'" x-cloak></div>
                                            </div>
                                        </div>
                                    <?php endif; ?>
                                <?php endif; ?>

                                <!-- Manual Crypto (USD) -->
                                <div class="relative flex items-center justify-between p-4 rounded-2xl border-2 transition-all duration-300 cursor-pointer group shadow-sm"
                                     :class="gateway === 'crypto' ? 'border-emerald-500 bg-emerald-500/5' : 'border-slate-800 bg-slate-950/40 hover:border-slate-700'"
                                     @click="gateway = 'crypto'">
                                    <input type="radio" name="gateway" value="crypto" class="hidden" x-model="gateway">
                                    <div class="flex items-center space-x-4">
                                        <div class="w-12 h-12 bg-slate-900 border border-slate-700 rounded-xl flex items-center justify-center text-lg shrink-0 text-amber-400 shadow-inner">
                                            🧠
                                        </div>
                                        <div>
                                            <h5 class="font-bold text-sm text-white">Manual Crypto (USD)</h5>
                                            <p class="text-[10px] text-slate-400 mt-0.5">Send BTC or USDT manually. Admin verification required.</p>
                                        </div>
                                    </div>
                                    <div class="w-5 h-5 rounded-full border-2 flex items-center justify-center transition-colors shrink-0"
                                         :class="gateway === 'crypto' ? 'border-emerald-500 bg-emerald-500' : 'border-slate-700'">
                                        <div class="w-1.5 h-1.5 rounded-full bg-white" x-show="gateway === 'crypto'" x-cloak></div>
                                    </div>
                                </div>

                                <div class="mt-4 text-[9px] text-slate-500 text-center border-t border-slate-800 pt-4">
                                    💱 Paystack processes payments in <strong class="text-amber-400">Nigerian Naira (NGN)</strong>. All other gateways charge in <strong class="text-emerald-400">USD</strong>.
                                </div>
                            </div>

                            <!-- Manual Crypto section (unchanged) -->
                            <div class="bg-slate-900/40 backdrop-blur-xl border border-slate-800 rounded-3xl p-6 md:p-8 shadow-2xl space-y-6 transition-all duration-500 ease-in-out overflow-hidden"
                                 x-show="gateway === 'crypto'" x-cloak
                                 x-transition:enter="transition ease-out duration-300"
                                 x-transition:enter-start="opacity-0 max-h-0"
                                 x-transition:enter-end="opacity-100 max-h-[900px]"
                                 x-transition:leave="transition ease-in duration-200"
                                 x-transition:leave-start="opacity-100 max-h-[900px]"
                                 x-transition:leave-end="opacity-0 max-h-0">
                                
                                <div class="border-b border-slate-800/60 pb-4">
                                    <h5 class="text-xs font-black tracking-widest uppercase text-amber-400 mb-1">🏦 Crypto Manual Verification</h5>
                                    <p class="text-[10px] text-slate-500 leading-relaxed">Send the exact USD amount to one of the addresses below. Upload proof for admin review.</p>
                                </div>

                                <?php if(!empty($crypto_addresses['manual_btc_address']) || !empty($crypto_addresses['manual_usdt_trc20'])): ?>
                                    <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                        <?php if(!empty($crypto_addresses['manual_btc_address'])): ?>
                                            <div class="bg-slate-950/60 border border-slate-800 p-4 rounded-2xl flex flex-col">
                                                <span class="text-[8px] font-black uppercase tracking-widest text-slate-500 mb-1.5">Bitcoin (BTC)</span>
                                                <span class="text-[9px] font-mono font-extrabold text-amber-400 break-all select-all"><?= htmlspecialchars($crypto_addresses['manual_btc_address']); ?></span>
                                            </div>
                                        <?php endif; ?>
                                        <?php if(!empty($crypto_addresses['manual_usdt_trc20'])): ?>
                                            <div class="bg-slate-950/60 border border-slate-800 p-4 rounded-2xl flex flex-col">
                                                <span class="text-[8px] font-black uppercase tracking-widest text-slate-500 mb-1.5">USDT (TRC20)</span>
                                                <span class="text-[9px] font-mono font-extrabold text-emerald-400 break-all select-all"><?= htmlspecialchars($crypto_addresses['manual_usdt_trc20']); ?></span>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                <?php endif; ?>

                                <div class="flex flex-col md:flex-row gap-6 bg-slate-950/40 p-4 rounded-2xl border border-slate-800/80 items-center">
                                    <div class="flex-1 space-y-2 w-full">
                                        <label class="block text-[8px] font-black uppercase tracking-widest text-slate-500">Active Address</label>
                                        <div class="flex items-center space-x-3 bg-slate-900 border border-slate-700/60 p-3 rounded-xl">
                                            <input type="text" readonly class="bg-transparent text-[10px] md:text-xs font-mono font-bold text-cyan-400 flex-1 outline-none select-all" 
                                                   :value="activeCryptoAddress" id="addressNode">
                                            <button @click.prevent="copyAddress()" class="bg-slate-800 hover:bg-slate-700 p-2 rounded-lg text-xs transition border border-slate-600 shrink-0">
                                                📋 Copy
                                            </button>
                                        </div>
                                        <span class="text-[8px] text-emerald-500 font-bold tracking-widest uppercase block mt-1" x-show="copied" x-cloak>✅ Copied!</span>
                                    </div>
                                    <div class="shrink-0 flex flex-col items-center">
                                        <span class="text-[8px] font-black uppercase tracking-widest text-slate-500 mb-2">QR</span>
                                        <div class="w-20 h-20 bg-slate-900 border border-slate-700 rounded-xl flex items-center justify-center text-[8px] text-slate-600 font-black tracking-widest uppercase">
                                            QR Code
                                        </div>
                                    </div>
                                </div>

                                <div class="space-y-4 pt-2">
                                    <div>
                                        <label class="block text-[8px] font-black uppercase tracking-widest text-slate-400 mb-1.5">Transaction Hash (TxID)</label>
                                        <input type="text" name="tx_hash" x-model="txHash" placeholder="Enter the transaction hash..." class="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 text-xs font-mono text-slate-200 outline-none focus:border-emerald-500/60 transition-colors">
                                    </div>
                                    <div>
                                        <label class="block text-[8px] font-black uppercase tracking-widest text-slate-400 mb-1.5">Upload Receipt</label>
                                        <div class="w-full border-2 border-dashed border-slate-800 hover:border-slate-700 transition-all rounded-2xl p-6 text-center cursor-pointer relative bg-slate-950/30"
                                             @dragover.prevent @drop.prevent="handleReceiptDrop($event)">
                                            <input type="file" name="receipt" @change="handleReceiptUpload($event)" accept="image/*,application/pdf" class="absolute inset-0 opacity-0 cursor-pointer w-full h-full">
                                            <div class="text-2xl mb-2">📂</div>
                                            <p class="text-[10px] text-slate-400 font-bold" x-text="receiptFile ? receiptFile.name : 'Click or drag to upload'">Click or drag to upload</p>
                                            <p class="text-[8px] text-slate-600 mt-1">JPG, PNG, or PDF</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Invoice Summary -->
                        <div class="lg:col-span-5 xl:col-span-4 bg-slate-900/40 backdrop-blur-xl border border-slate-800 rounded-3xl p-6 md:p-8 shadow-2xl flex flex-col justify-between h-fit sticky top-28">
                            <div>
                                <span class="text-[9px] font-black tracking-widest uppercase text-slate-500 block mb-1">Invoice Summary</span>
                                <h2 class="text-lg font-black text-white mb-6 border-b border-slate-800 pb-3 tracking-wide">Order Summary</h2>
                                
                                <div class="space-y-4 mb-8">
                                    <div class="flex justify-between items-center text-xs">
                                        <span class="text-slate-400 font-bold">Plan</span>
                                        <span class="font-black tracking-wider text-white"><?= htmlspecialchars($checkout_plan['plan_name']); ?></span>
                                    </div>
                                    <div class="flex justify-between items-center text-xs">
                                        <span class="text-slate-400 font-bold">Duration</span>
                                        <span class="font-black text-white"><?= $checkout_plan['duration_days']; ?> days</span>
                                    </div>
                                    <div class="flex justify-between items-center text-xs">
                                        <span class="text-slate-400 font-bold">Price (USD)</span>
                                        <span class="font-black text-white">$<?= number_format($checkout_plan['price'], 2); ?></span>
                                    </div>
                                    <div class="flex justify-between items-center text-xs">
                                        <span class="text-slate-400 font-bold">Price (NGN)</span>
                                        <span class="font-black text-amber-400">₦<?= number_format($checkout_plan['price'] * $rate, 0); ?></span>
                                    </div>
                                    <div class="border-t border-slate-800 pt-4 flex justify-between items-center text-sm">
                                        <span class="text-slate-200 font-black tracking-wider uppercase">Total</span>
                                        <span class="text-2xl font-black text-emerald-400 tracking-tight">$<?= number_format($checkout_plan['price'], 2); ?></span>
                                    </div>
                                </div>
                            </div>

                            <div class="space-y-3">
                                <div class="bg-rose-500/10 border border-rose-500/20 text-rose-400 px-4 py-3 rounded-xl text-[9px] font-black uppercase tracking-widest text-center animate-pulse" 
                                     x-show="gateway === ''" x-cloak>⚠️ Select a payment method</div>

                                <button type="submit" class="w-full bg-gradient-to-r from-emerald-600 to-emerald-500 hover:from-emerald-500 hover:to-emerald-400 text-white font-black py-4 px-6 rounded-2xl text-[11px] uppercase tracking-widest transition shadow-lg shadow-emerald-600/20"
                                        x-show="gateway === 'paystack' || gateway === 'stripe' || gateway === 'nowpayments'" 
                                        @click.prevent="triggerAutomatedGatewayFlow()"
                                        :disabled="isProcessing"
                                        x-cloak>
                                    Pay Now
                                </button>

                                <button type="submit" class="w-full bg-gradient-to-r from-amber-600 to-amber-500 hover:from-amber-500 hover:to-amber-400 text-slate-950 font-black py-4 px-6 rounded-2xl text-[11px] uppercase tracking-widest transition shadow-lg shadow-amber-600/15"
                                        x-show="gateway === 'crypto'" 
                                        @click.prevent="triggerManualCryptoVerifyFlow()"
                                        :disabled="isProcessing"
                                        x-cloak>
                                    Submit for Verification
                                </button>
                            </div>
                        </div>
                    </form>

                    <!-- Processing overlay -->
                    <div class="fixed inset-0 z-50 flex flex-col items-center justify-center bg-slate-950/85 backdrop-blur-md"
                         x-show="isProcessing" x-cloak>
                        <div class="relative w-16 h-16">
                            <div class="absolute inset-0 border-4 border-emerald-500/20 rounded-full"></div>
                            <div class="absolute inset-0 border-4 border-emerald-500 border-t-transparent rounded-full animate-spin"></div>
                        </div>
                        <p class="text-white font-black text-xs tracking-widest uppercase animate-pulse mt-6">Processing your payment...</p>
                    </div>
                </div>
            <?php endif; ?>

        </main>
    </div>

    <script>
        function checkoutProcessState() {
            return {
                gateway: '',
                isProcessing: false,
                activeCryptoAddress: '<?= htmlspecialchars($crypto_addresses['manual_usdt_trc20'] ?? 'TXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'); ?>',
                copied: false,
                txHash: '',
                receiptFile: null,

                copyAddress() {
                    const addrInput = document.getElementById("addressNode");
                    if(addrInput) {
                        addrInput.select();
                        document.execCommand('copy');
                        this.copied = true;
                        setTimeout(() => this.copied = false, 3000);
                    }
                },

                handleReceiptUpload(e) {
                    if(e.target.files.length) this.receiptFile = e.target.files[0];
                },

                handleReceiptDrop(e) {
                    if(e.dataTransfer.files.length) this.receiptFile = e.dataTransfer.files[0];
                },

                triggerAutomatedGatewayFlow() {
                    this.isProcessing = true;
                    setTimeout(() => {
                        document.forms[0].submit();
                    }, 1200);
                },

                triggerManualCryptoVerifyFlow() {
                    if(!this.txHash.trim()) {
                        alert('Please enter the Transaction Hash (TxID).');
                        return;
                    }
                    if(!this.receiptFile) {
                        alert('Please upload a receipt screenshot or PDF.');
                        return;
                    }
                    this.isProcessing = true;
                    document.forms[0].submit();
                }
            }
        }

        // Neural background canvas (unchanged)
        const canvas = document.getElementById("neuralCanvas");
        if(canvas) {
            const ctx = canvas.getContext("2d");
            let width, height;
            let particles = [];
            function initCanvas() {
                width = canvas.width = window.innerWidth;
                height = canvas.height = window.innerHeight;
                particles = [];
                for (let i = 0; i < (width * height) / 15000; i++) {
                    particles.push({
                        x: Math.random() * width, y: Math.random() * height,
                        vx: (Math.random() - 0.5) * 1.5, vy: (Math.random() - 0.5) * 1.5,
                        radius: Math.random() * 1.5 + 0.5
                    });
                }
            }
            function animateCanvas() {
                ctx.clearRect(0, 0, width, height);
                for (let i = 0; i < particles.length; i++) {
                    let p = particles[i];
                    p.x += p.vx; p.y += p.vy;
                    if (p.x < 0 || p.x > width) p.vx *= -1;
                    if (p.y < 0 || p.y > height) p.vy *= -1;
                    ctx.beginPath(); ctx.arc(p.x, p.y, p.radius, 0, Math.PI * 2);
                    ctx.fillStyle = "rgba(16, 185, 129, 0.15)"; ctx.fill();
                }
                requestAnimationFrame(animateCanvas);
            }
            window.addEventListener("resize", initCanvas);
            initCanvas(); animateCanvas();
        }
    </script>
    <canvas id="neuralCanvas" class="fixed inset-0 w-full h-full pointer-events-none z-0 opacity-30"></canvas>
</body>
</html>