<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech

if (session_status() === PHP_SESSION_NONE) { session_start(); }
require_once '../include/config.php';
require_once '../include/pocketfi.php';

if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    header('Location: ../signin.php');
    exit();
}

try {
    $stmt = $pdo->prepare("SELECT id, username, email, full_name, phone, main_balance, referral_code, referral_balance, total_referred, total_earnings, is_admin, created_at, pocketfi_account_number, pocketfi_account_name, pocketfi_bank_name FROM users WHERE id = :user_id");
    $stmt->bindParam(':user_id', $_SESSION['user_id'], PDO::PARAM_INT);
    $stmt->execute();
    if ($stmt->rowCount() == 1) {
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
    } else {
        session_destroy();
        header('Location: ../signin.php');
        exit();
    }
} catch (PDOException $e) {
    die("Error fetching user data: " . $e->getMessage());
}

$paystack_public_key   = $site_data['paystack_public_key'];
$paystack_secret_key   = $site_data['paystack_secret_key'];
$paystack_minimum      = $site_data['paystack_minimum'];
$korapay_public_key    = $site_data['korapay_public_key'];
$korapay_minimum       = $site_data['korapay_minimum'];

$flutterwave_enabled   = intval($site_data['flutterwave_enabled'] ?? 0);
$flutterwave_public_key = $site_data['flutterwave_public_key'] ?? '';
$flutterwave_secret_key = $site_data['flutterwave_secret_key'] ?? '';
$flutterwave_minimum_ngn = floatval($site_data['flutterwave_minimum'] ?? 100.00);
$flutterwave_default_currency = strtoupper(trim($site_data['flutterwave_default_currency'] ?? 'NGN'));

$cryptomus_merchant_id = $site_data['cryptomus_merchant_id'] ?? '';
$cryptomus_payment_key = $site_data['cryptomus_payment_key'] ?? '';
$cryptomus_minimum_usd = floatval($site_data['cryptomus_minimum'] ?? 1.00);
$cryptomus_enabled     = intval($site_data['cryptomus_enabled'] ?? 0);
$usd_to_ngn            = floatval($site_data['usd_to_ngn'] ?? 1600.00);
$cryptomus_minimum_ngn = $cryptomus_minimum_usd * $usd_to_ngn;

$pocketfi_enabled   = intval($site_data['pocketfi_enabled'] ?? 0);
$pocketfi_bank_name = $site_data['pocketfi_bank_name'] ?? 'Pocketfi Bank';
$va_account_number  = $user['pocketfi_account_number'] ?? '';
$va_account_name    = $user['pocketfi_account_name']   ?? '';
$va_bank_name       = $user['pocketfi_bank_name']      ?? $pocketfi_bank_name;

$pocketfi_retry_error = '';
if ($pocketfi_enabled && empty($va_account_number)) {
    $retry_result = retryPocketfiVirtualAccount($pdo, $site_data, $user);
    if ($retry_result['success'] && $retry_result['data'] !== null) {
        try {
            $stmt = $pdo->prepare("SELECT id, username, email, full_name, phone, main_balance, referral_code, referral_balance, total_referred, total_earnings, is_admin, created_at, pocketfi_account_number, pocketfi_account_name, pocketfi_bank_name FROM users WHERE id = :user_id");
            $stmt->execute([':user_id' => $_SESSION['user_id']]);
            $user              = $stmt->fetch(PDO::FETCH_ASSOC);
            $va_account_number = $user['pocketfi_account_number'] ?? '';
            $va_account_name   = $user['pocketfi_account_name']   ?? '';
            $va_bank_name      = $user['pocketfi_bank_name']      ?? $pocketfi_bank_name;
        } catch (PDOException $e) {
            error_log("[fund-wallet] Failed to reload user after Pocketfi retry: " . $e->getMessage());
        }
    } elseif (!$retry_result['success']) {
        $pocketfi_retry_error = $retry_result['message'];
    }
}

$error_message   = '';
$success_message = '';
if (!empty($_SESSION['success'])) { $success_message = $_SESSION['success']; unset($_SESSION['success']); }
if (!empty($_SESSION['error']))   { $error_message   = $_SESSION['error'];   unset($_SESSION['error']);   }

function get_ngn_equivalent_amount($amount, $currency, $site_data) {
    $currency = strtoupper(trim($currency ?: 'NGN'));
    if ($currency === 'NGN') {
        return round(floatval($amount), 2);
    }

    $rate_map = [
        'USD' => floatval($site_data['usd_to_ngn'] ?? 1600.00),
        'EUR' => 1700.00,
        'GBP' => 2000.00,
        'KES' => 12.00,
        'GHS' => 100.00,
        'ZAR' => 85.00,
        'CAD' => 1200.00,
        'AUD' => 1000.00,
        'JPY' => 11.00,
        'CNY' => 220.00,
        'AED' => 430.00,
        'INR' => 20.00,
    ];

    $rate = $rate_map[$currency] ?? floatval($site_data['usd_to_ngn'] ?? 1600.00);
    return round(floatval($amount) * $rate, 2);
}

if (isset($_POST['submit'])) {
    $amount          = floatval($_POST['amount']);
    $selected_currency = strtoupper(trim($_POST['currency'] ?? 'NGN'));
    $payment_gateway = isset($_POST['type']) ? trim($_POST['type']) : 'paystack';
    $ngn_equivalent = get_ngn_equivalent_amount($amount, $selected_currency, $site_data);

    if ($payment_gateway === 'korapay')        $minimum = $korapay_minimum;
    elseif ($payment_gateway === 'cryptomus')  $minimum = $cryptomus_minimum_ngn;
    elseif ($payment_gateway === 'flutterwave') $minimum = $flutterwave_minimum_ngn;
    else                                       $minimum = $paystack_minimum;

    if ($ngn_equivalent < $minimum) {
        $error_message = "Minimum deposit amount is ₦" . number_format($minimum, 2);
    } elseif ($payment_gateway === 'cryptomus' && !$cryptomus_enabled) {
        $error_message = "Crypto payments are currently unavailable.";
    } elseif ($payment_gateway === 'flutterwave' && !$flutterwave_enabled) {
        $error_message = "Flutterwave payments are currently unavailable.";
    } elseif ($payment_gateway === 'flutterwave' && (empty($flutterwave_public_key) || empty($flutterwave_secret_key))) {
        $error_message = "Flutterwave is not configured yet.";
    } else {
        $transaction_ref = 'TXN_' . strtoupper(uniqid()) . '_' . time();
        $ip_address      = $_SERVER['REMOTE_ADDR'];
        $check_stmt = $pdo->prepare("SELECT COUNT(*) as count FROM transactions WHERE user_id = :user_id AND status = 'successful'");
        $check_stmt->execute(['user_id' => $user['id']]);
        $is_first_deposit = ($check_stmt->fetch(PDO::FETCH_ASSOC)['count'] == 0) ? 1 : 0;
        $metadata_payload = [
            'original_amount' => $amount,
            'original_currency' => $selected_currency,
            'converted_ngn' => $ngn_equivalent,
            'fx_rate' => $selected_currency === 'NGN' ? 1 : null,
        ];
        $metadata_json = json_encode($metadata_payload, JSON_UNESCAPED_SLASHES);
        try {
            $pdo->prepare("INSERT INTO transactions (user_id, transaction_ref, payment_gateway, amount, currency, metadata, status, ip_address, is_first_deposit, created_at) VALUES (:user_id, :transaction_ref, :gateway, :amount, :currency, :metadata, 'pending', :ip_address, :is_first_deposit, NOW())")
                ->execute(['user_id'=>$user['id'],'transaction_ref'=>$transaction_ref,'gateway'=>$payment_gateway,'amount'=>$ngn_equivalent,'currency'=>$selected_currency,'metadata'=>$metadata_json,'ip_address'=>$ip_address,'is_first_deposit'=>$is_first_deposit]);

            if ($payment_gateway === 'cryptomus') {
                $amount_usd = round($amount / $usd_to_ngn, 2);
                if ($amount_usd < $cryptomus_minimum_usd) $amount_usd = $cryptomus_minimum_usd;
                $payload = ['amount'=>(string)$amount_usd,'currency'=>'USD','order_id'=>$transaction_ref,
                    'url_return'=>$site_data['web_url'].'/user/fund-wallet',
                    'url_callback'=>$site_data['web_url'].'/user/cryptomus-ipn.php',
                    'url_success'=>$site_data['web_url'].'/user/verify-payment?reference='.urlencode($transaction_ref).'&gateway=cryptomus',
                    'is_payment_multiple'=>false,'lifetime'=>3600,'to_currency'=>null];
                $payload_json = json_encode($payload);
                $sign = md5(base64_encode($payload_json) . $cryptomus_payment_key);
                $ch = curl_init('https://api.cryptomus.com/v1/payment');
                curl_setopt_array($ch,[CURLOPT_RETURNTRANSFER=>true,CURLOPT_POST=>true,CURLOPT_POSTFIELDS=>$payload_json,
                    CURLOPT_HTTPHEADER=>['Content-Type: application/json','merchant: '.$cryptomus_merchant_id,'sign: '.$sign],CURLOPT_TIMEOUT=>30]);
                $response = curl_exec($ch); $curl_err = curl_error($ch); curl_close($ch);
                if ($curl_err) {
                    $pdo->prepare("UPDATE transactions SET status='failed' WHERE transaction_ref=:ref")->execute(['ref'=>$transaction_ref]);
                    $error_message = "Unable to create crypto invoice. Please try again.";
                } else {
                    $result = json_decode($response, true);
                    if (isset($result['result']['url'])) {
                        $_SESSION['pending_transaction'] = $transaction_ref;
                        $_SESSION['pending_amount']      = $amount;
                        $_SESSION['pending_gateway']     = 'cryptomus';
                        header('Location: ' . $result['result']['url']); exit();
                    } else {
                        $pdo->prepare("UPDATE transactions SET status='failed' WHERE transaction_ref=:ref")->execute(['ref'=>$transaction_ref]);
                        $error_message = "Crypto invoice error: " . ($result['message'] ?? 'Unknown error.');
                    }
                }
            } elseif ($payment_gateway === 'flutterwave') {
                $payload = [
                    'tx_ref' => $transaction_ref,
                    'amount' => (string)$amount,
                    'currency' => $selected_currency,
                    'redirect_url' => $site_data['web_url'] . '/user/verify-payment?reference=' . urlencode($transaction_ref) . '&gateway=flutterwave',
                    'payment_options' => 'card,banktransfer,ussd',
                    'customer' => [
                        'email' => $user['email'],
                        'name' => $user['full_name'] ?: $user['username'],
                        'phone_number' => $user['phone'] ?? '',
                    ],
                    'customizations' => [
                        'title' => $site_data['web_name'] ?? 'Wallet Funding',
                        'description' => 'Fund your wallet. Amount will be credited in NGN.'
                    ],
                    'meta' => [
                        'user_id' => $user['id'],
                        'converted_ngn' => $ngn_equivalent,
                        'source_currency' => $selected_currency,
                    ],
                ];
                $payload_json = json_encode($payload);
                $ch = curl_init('https://api.flutterwave.com/v3/payments');
                curl_setopt_array($ch, [
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_POST => true,
                    CURLOPT_POSTFIELDS => $payload_json,
                    CURLOPT_HTTPHEADER => [
                        'Content-Type: application/json',
                        'Authorization: Bearer ' . $flutterwave_secret_key,
                    ],
                    CURLOPT_TIMEOUT => 30,
                ]);
                $response = curl_exec($ch);
                $curl_err = curl_error($ch);
                curl_close($ch);
                if ($curl_err) {
                    $pdo->prepare("UPDATE transactions SET status='failed' WHERE transaction_ref=:ref")->execute(['ref'=>$transaction_ref]);
                    $error_message = "Unable to start Flutterwave payment. Please try again.";
                } else {
                    $result = json_decode($response, true);
                    if (!empty($result['data']['link'])) {
                        header('Location: ' . $result['data']['link']);
                        exit();
                    } else {
                        $pdo->prepare("UPDATE transactions SET status='failed' WHERE transaction_ref=:ref")->execute(['ref'=>$transaction_ref]);
                        $error_message = "Flutterwave payment error: " . ($result['message'] ?? 'Unknown error.');
                    }
                }
            } else {
                $_SESSION['pending_transaction'] = $transaction_ref;
                $_SESSION['pending_amount']      = $amount;
                $_SESSION['pending_gateway']     = $payment_gateway;
            }
        } catch (PDOException $e) {
            $error_message = "Error creating transaction. Please try again.";
        }
    }
}

$page_title = $site_data['web_name'] . " | Fund Wallet";
include ('header.php');

try {
    $stmt = $pdo->prepare("SELECT * FROM transactions WHERE user_id = :user_id AND (payment_gateway != 'paystack_transfer' OR payment_gateway IS NULL) ORDER BY created_at DESC LIMIT 10");
    $stmt->execute(['user_id' => $user['id']]);
    $transactions = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $transactions = [];
}
?>
<title><?php echo $page_title; ?></title>

<style>
@keyframes fadeUp{from{opacity:0;transform:translateY(14px)}to{opacity:1;transform:translateY(0)}}
.anim{opacity:0;animation:fadeUp .45s ease-out forwards}
.anim-1{animation-delay:.05s}.anim-2{animation-delay:.12s}.anim-3{animation-delay:.19s}.anim-4{animation-delay:.26s}
.fw-hero{background:linear-gradient(145deg,#2d0a5e 0%,#4D148C 50%,#6b23c2 100%);border:1px solid rgba(255,102,0,.15);border-radius:20px;padding:20px;position:relative;overflow:hidden;margin-bottom:16px}
.fw-hero::before{content:'';position:absolute;inset:0;background:repeating-linear-gradient(45deg,transparent,transparent 40px,rgba(255,102,0,.012) 40px,rgba(255,102,0,.012) 41px);pointer-events:none}
.fw-orb{position:absolute;border-radius:50%;pointer-events:none;filter:blur(50px)}
.fw-card{background:#ffffff;border:1px solid rgba(0,0,0,.08);box-shadow:0 2px 12px rgba(0,0,0,.04);border-radius:16px;padding:20px;margin-bottom:14px}
.va-card{background:linear-gradient(145deg,#4D148C 0%,#6b23c2 60%,#7c3aed 100%);border:1px solid rgba(255,255,255,.12);border-radius:16px;padding:18px;position:relative;overflow:hidden;margin-bottom:14px}
.payment-method{border:1.5px solid rgba(0,0,0,.08);border-radius:13px;padding:14px;cursor:pointer;transition:all .2s ease;position:relative;background:#ffffff}
.payment-method:has(input:checked){border-color:#FF6600;background:rgba(255,102,0,.04)}
.txn-item{border:1px solid rgba(0,0,0,.08);border-radius:11px;padding:12px;transition:border-color .2s}
.txn-item:hover{border-color:rgba(77,20,140,.25)}
/* Shared gradient font style (same as dashboard balance-display) */
.gradient-text{font-weight:800;letter-spacing:-.03em;background:linear-gradient(135deg,#ffffff 0%,#ffffff 100%);-webkit-background-clip:text;-webkit-text-fill-color:transparent;background-clip:text;line-height:1.1;}
/* Eye toggle */
.eye-toggle-btn{background:none;border:none;cursor:pointer;padding:4px 6px;color:rgba(255,255,255,.5);transition:color .2s;display:inline-flex;align-items:center;justify-content:center;border-radius:6px;vertical-align:middle;}
.eye-toggle-btn:hover{color:rgba(255,255,255,.85);}
</style>

<div class="max-w-2xl mx-auto">

<?php if ($error_message): ?>
<div class="anim anim-1 mb-4" style="background:rgba(239,68,68,.06);border:1px solid rgba(239,68,68,.18);border-radius:12px;padding:12px 16px;display:flex;align-items:center;gap:10px;">
    <i class="fas fa-circle-exclamation text-red-500 text-base flex-shrink-0"></i>
    <p style="font-size:.82rem;color:#dc2626;"><?php echo htmlspecialchars($error_message); ?></p>
</div>
<?php endif; ?>
<?php if ($success_message): ?>
<div class="anim anim-1 mb-4" style="background:rgba(5,150,105,.06);border:1px solid rgba(5,150,105,.18);border-radius:12px;padding:12px 16px;display:flex;align-items:center;gap:10px;">
    <i class="fas fa-circle-check text-emerald-500 text-base flex-shrink-0"></i>
    <p style="font-size:.82rem;color:#047857;"><?php echo htmlspecialchars($success_message); ?></p>
</div>
<?php endif; ?>

<!-- Hero -->
<div class="fw-hero anim anim-1">
    <div class="fw-orb" style="width:160px;height:160px;background:radial-gradient(circle,rgba(5,150,105,.25),transparent);top:-40px;right:-40px;"></div>
    <div style="position:relative;z-index:1;">
        <div style="display:flex;align-items:center;gap:10px;margin-bottom:14px;">
            <div style="width:36px;height:36px;border-radius:9px;background:rgba(255,255,255,.1);display:flex;align-items:center;justify-content:center;">
                <i class="fas fa-wallet text-white text-sm"></i>
            </div>
            <div>
                <p style="font-size:.62rem;color:rgba(255,255,255,.55);font-weight:700;text-transform:uppercase;letter-spacing:.08em;">Fund Wallet</p>
                <p style="font-size:.9rem;font-weight:700;color:white;">Add funds to your account</p>
            </div>
        </div>
        <div style="display:flex;align-items:center;justify-content:space-between;background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.1);border-radius:12px;padding:12px 16px;">
            <div>
                <div style="display:flex;align-items:center;gap:6px;margin-bottom:4px;">
                    <p style="font-size:.62rem;color:rgba(255,255,255,.5);font-weight:600;text-transform:uppercase;letter-spacing:.06em;">Current Balance</p>
                    <!-- Eye toggle for fund-wallet balance -->
                    <button class="eye-toggle-btn" id="fwEyeBtn" onclick="toggleFwBalance()" title="Toggle balance visibility">
                        <i class="fas fa-eye" id="fwEyeIcon" style="font-size:.72rem;"></i>
                    </button>
                </div>
                <!-- Visible balance -->
                <p class="gradient-text" id="fwBalanceVisible" style="font-size:1.5rem;">₦<?php echo number_format($user['main_balance'],2); ?></p>
                <!-- Hidden balance placeholder -->
                <p class="gradient-text" id="fwBalanceHidden" style="font-size:1.5rem;display:none;">₦ • • • • • •</p>
            </div>
            <div style="background:rgba(34,184,100,.2);border:1px solid rgba(34,184,100,.3);border-radius:8px;padding:6px 14px;">
                <p style="font-size:.72rem;font-weight:700;color:#6ee7b7;">Available</p>
            </div>
        </div>
    </div>
</div>

<script>
(function(){
    // Sync with dashboard eye state via the same localStorage key
    var hidden = localStorage.getItem('dashBalanceHidden') === '1';
    function applyFwState(h){
        var vis  = document.getElementById('fwBalanceVisible');
        var hide = document.getElementById('fwBalanceHidden');
        var icon = document.getElementById('fwEyeIcon');
        if(!vis||!hide||!icon) return;
        if(h){
            vis.style.display='none'; hide.style.display='';
            icon.className='fas fa-eye-slash';
        } else {
            vis.style.display=''; hide.style.display='none';
            icon.className='fas fa-eye';
        }
    }
    window.toggleFwBalance = function(){
        hidden = !hidden;
        localStorage.setItem('dashBalanceHidden', hidden ? '1' : '0');
        applyFwState(hidden);
    };
    document.addEventListener('DOMContentLoaded', function(){ applyFwState(hidden); });
    if(document.readyState !== 'loading') applyFwState(hidden);
})();
</script>

<!-- Pocketfi Virtual Account -->
<?php if ($pocketfi_enabled && !empty($va_account_number)): ?>
<div class="va-card anim anim-2">
    <div style="position:absolute;right:-20px;top:-20px;width:120px;height:120px;background:rgba(255,255,255,.07);border-radius:50%;pointer-events:none;"></div>
    <div style="position:relative;z-index:1;">
        <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:12px;flex-wrap:wrap;gap:8px;">
            <div style="display:flex;align-items:center;gap:8px;">
                <div style="width:30px;height:30px;border-radius:8px;background:rgba(255,255,255,.15);display:flex;align-items:center;justify-content:center;">
                    <i class="fas fa-building-columns text-white text-sm"></i>
                </div>
                <p style="font-size:.82rem;font-weight:700;color:white;">Bank Transfer (Auto-Credit)</p>
            </div>
            <span style="background:rgba(255,255,255,.15);color:white;font-size:.62rem;font-weight:700;padding:3px 10px;border-radius:99px;">AUTO</span>
        </div>
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-bottom:12px;">
            <div style="background:rgba(255,255,255,.1);border-radius:9px;padding:10px;border:1px solid rgba(255,255,255,.1);">
                <p style="font-size:.6rem;color:rgba(255,255,255,.6);text-transform:uppercase;letter-spacing:.06em;margin-bottom:3px;">Account No.</p>
                <p class="gradient-text" id="va-account-number" style="font-size:clamp(0.85rem,2.8vw,1.1rem);letter-spacing:.05em;"><?php echo htmlspecialchars($va_account_number); ?></p>
            </div>
            <div style="background:rgba(255,255,255,.1);border-radius:9px;padding:10px;border:1px solid rgba(255,255,255,.1);">
                <p style="font-size:.6rem;color:rgba(255,255,255,.6);text-transform:uppercase;letter-spacing:.06em;margin-bottom:3px;">Bank</p>
                <p style="font-size:.82rem;font-weight:700;color:white;"><?php echo ucfirst(htmlspecialchars($va_bank_name)); ?> MFB</p>
            </div>
        </div>
        <p style="font-size:.75rem;color:rgba(255,255,255,.7);margin-bottom:12px;"><strong>Name:</strong> <?php echo ucfirst(htmlspecialchars($va_account_name ?: $user['full_name'] ?: $user['username'])); ?></p>
        <?php if (!empty($pocketfi_retry_error)): ?>
        <div style="background:rgba(239,68,68,.15);border:1px solid rgba(239,68,68,.25);border-radius:8px;padding:8px 12px;margin-bottom:10px;">
            <p style="font-size:.72rem;color:#fca5a5;">⚠️ <?php echo htmlspecialchars($pocketfi_retry_error); ?> — <a href="fund-wallet" style="font-weight:700;color:#fca5a5;text-decoration:underline;">Retry</a></p>
        </div>
        <?php endif; ?>
        <button onclick="copyAccountNumber()" id="copy-btn" style="display:flex;align-items:center;gap:6px;background:white;color:#047857;font-weight:700;font-size:.75rem;padding:8px 16px;border-radius:8px;border:none;cursor:pointer;">
            <i class="fa-regular fa-copy" id="copy-icon"></i>
            <span id="copy-label">Copy Account Number</span>
        </button>
    </div>
</div>
<?php elseif ($pocketfi_enabled && empty($va_account_number)): ?>
<div class="anim anim-2 mb-4" style="background:rgba(245,158,11,.06);border:1px solid rgba(245,158,11,.2);border-radius:13px;padding:14px;display:flex;align-items:center;gap:10px;">
    <div style="width:34px;height:34px;border-radius:8px;background:rgba(245,158,11,.12);color:#d97706;display:flex;align-items:center;justify-content:center;flex-shrink:0;">
        <i class="fas fa-triangle-exclamation text-sm"></i>
    </div>
    <div>
        <p style="font-weight:700;font-size:.82rem;color:var(--text-primary);">Virtual Account Not Yet Assigned</p>
        <p style="font-size:.72rem;color:var(--text-muted);margin-top:2px;">Your dedicated account is being set up. <a href="fund-wallet" style="color:#16a354;font-weight:700;">Retry →</a></p>
    </div>
</div>
<?php endif; ?>

<!-- Paystack DVA Virtual Account -->
<?php
// Load Paystack DVA
require_once '../include/paystack_dva.php';
$paystack_dva_enabled = intval($site_data['paystack_dva_enabled'] ?? 0);
$dva_account_number   = $user['paystack_dva_account_number'] ?? '';
$dva_account_name     = $user['paystack_dva_account_name']   ?? '';
$dva_bank_name        = $user['paystack_dva_bank_name']      ?? 'Wema Bank';
$dva_retry_error      = '';

if ($paystack_dva_enabled && empty($dva_account_number)) {
    $dva_result = createPaystackDVA($pdo, $site_data, (int)$user['id'], $user['full_name'] ?? '', $user['email'] ?? '', $user['phone'] ?? '');
    if ($dva_result['success'] && $dva_result['data'] !== null) {
        $dva_account_number = $dva_result['data']['account_number'];
        $dva_account_name   = $dva_result['data']['account_name'];
        $dva_bank_name      = $dva_result['data']['bank_name'];
    } elseif (!$dva_result['success']) {
        $dva_retry_error = $dva_result['message'];
    }
}
?>
<?php if ($paystack_dva_enabled && !empty($dva_account_number)): ?>
<div class="anim anim-2" style="background:linear-gradient(135deg,#0a2540 0%,#1a3a5c 100%);border-radius:16px;padding:18px;position:relative;overflow:hidden;margin-bottom:14px;">
    <div style="position:absolute;right:-20px;top:-20px;width:120px;height:120px;background:rgba(255,255,255,.05);border-radius:50%;pointer-events:none;"></div>
    <div style="position:relative;z-index:1;">
        <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:12px;flex-wrap:wrap;gap:8px;">
            <div style="display:flex;align-items:center;gap:8px;">
                <div style="width:30px;height:30px;border-radius:8px;background:rgba(255,255,255,.12);display:flex;align-items:center;justify-content:center;">
                    <i class="fas fa-university text-white text-sm"></i>
                </div>
                <p style="font-size:.82rem;font-weight:700;color:white;">Bank Transfer (Paystack)</p>
            </div>
            <span style="background:rgba(74,222,128,.2);color:#4ade80;font-size:.62rem;font-weight:700;padding:3px 10px;border-radius:99px;">INSTANT</span>
        </div>
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-bottom:12px;">
            <div style="background:rgba(255,255,255,.08);border-radius:9px;padding:10px;border:1px solid rgba(255,255,255,.08);">
                <p style="font-size:.6rem;color:rgba(255,255,255,.6);text-transform:uppercase;letter-spacing:.06em;margin-bottom:3px;">Account No.</p>
                <p id="dva-account-number" style="font-size:clamp(0.85rem,2.8vw,1.1rem);letter-spacing:.05em;font-weight:800;color:#4ade80;font-family:monospace;"><?php echo htmlspecialchars($dva_account_number); ?></p>
            </div>
            <div style="background:rgba(255,255,255,.08);border-radius:9px;padding:10px;border:1px solid rgba(255,255,255,.08);">
                <p style="font-size:.6rem;color:rgba(255,255,255,.6);text-transform:uppercase;letter-spacing:.06em;margin-bottom:3px;">Bank</p>
                <p style="font-size:.82rem;font-weight:700;color:white;"><?php echo htmlspecialchars($dva_bank_name); ?></p>
            </div>
        </div>
        <p style="font-size:.75rem;color:rgba(255,255,255,.7);margin-bottom:12px;"><strong>Name:</strong> <?php echo htmlspecialchars($dva_account_name ?: $user['full_name'] ?: $user['username']); ?></p>
        <button onclick="copyDvaNumber()" id="dva-copy-btn" style="display:flex;align-items:center;gap:6px;background:white;color:#0a2540;font-weight:700;font-size:.75rem;padding:8px 16px;border-radius:8px;border:none;cursor:pointer;">
            <i class="fa-regular fa-copy" id="dva-copy-icon"></i>
            <span id="dva-copy-label">Copy Account Number</span>
        </button>
    </div>
</div>
<?php elseif ($paystack_dva_enabled && empty($dva_account_number)): ?>
<div class="anim anim-2 mb-4" style="background:rgba(59,130,246,.06);border:1px solid rgba(59,130,246,.2);border-radius:13px;padding:14px;display:flex;align-items:center;gap:10px;">
    <div style="width:34px;height:34px;border-radius:8px;background:rgba(59,130,246,.12);color:#2563eb;display:flex;align-items:center;justify-content:center;flex-shrink:0;">
        <i class="fas fa-triangle-exclamation text-sm"></i>
    </div>
    <div>
        <p style="font-weight:700;font-size:.82rem;color:var(--text-primary);">Paystack Account Not Yet Assigned</p>
        <p style="font-size:.72rem;color:var(--text-muted);margin-top:2px;"><?php echo !empty($dva_retry_error) ? htmlspecialchars($dva_retry_error) . ' — ' : ''; ?><a href="fund-wallet" style="color:#2563eb;font-weight:700;">Retry &#8594;</a></p>
    </div>
</div>
<?php endif; ?>

<!-- Payment Methods -->
<div class="fw-card anim anim-3">
    <p style="font-weight:700;font-size:.88rem;color:var(--text-primary);margin-bottom:14px;display:flex;align-items:center;gap:8px;">
        <span style="width:28px;height:28px;border-radius:8px;background:rgba(34,184,100,.1);display:inline-flex;align-items:center;justify-content:center;">
            <i class="fas fa-credit-card" style="font-size:.72rem;color:#16a354;"></i>
        </span>
        Payment Methods
    </p>
    <form method="post" id="paymentForm" style="display:flex;flex-direction:column;gap:14px;">
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;">
            <?php 
            $paystack_enabled_flag = intval($site_data['paystack_enabled'] ?? 1);
            $korapay_enabled_flag = intval($site_data['korapay_enabled'] ?? 1);
            $flutterwave_enabled_flag = intval($site_data['flutterwave_enabled'] ?? 0);
            $first_checked = true;
            ?>
            <?php if ($paystack_enabled_flag): ?>
            <!-- Paystack -->
            <label class="payment-method" style="display:block;cursor:pointer;">
                <input type="radio" name="type" value="paystack" class="sr-only" <?php if($first_checked){echo 'checked';$first_checked=false;} ?>>
                <div style="display:flex;align-items:flex-start;gap:10px;">
                    <div style="width:38px;height:38px;border-radius:9px;background:rgba(77,20,140,.1);display:flex;align-items:center;justify-content:center;flex-shrink:0;">
                        <i class="fas fa-credit-card text-base" style="color:#4D148C;"></i>
                    </div>
                    <div>
                        <p style="font-weight:700;font-size:.78rem;color:var(--text-primary);">Paystack</p>
                        <p style="font-size:.68rem;color:var(--text-muted);margin-top:2px;line-height:1.4;">Card/Bank. Min: ₦<?php echo number_format($paystack_minimum,2); ?></p>
                    </div>
                </div>
            </label>
            <?php endif; ?>
            <?php if ($korapay_enabled_flag): ?>
            <!-- Korapay -->
            <label class="payment-method" style="display:block;cursor:pointer;">
                <input type="radio" name="type" value="korapay" class="sr-only" <?php if($first_checked){echo 'checked';$first_checked=false;} ?>>
                <div style="display:flex;align-items:flex-start;gap:10px;">
                    <div style="width:38px;height:38px;border-radius:9px;background:rgba(255,102,0,.1);display:flex;align-items:center;justify-content:center;flex-shrink:0;">
                        <i class="fas fa-bolt text-base" style="color:#FF6600;"></i>
                    </div>
                    <div>
                        <p style="font-weight:700;font-size:.78rem;color:var(--text-primary);">Korapay</p>
                        <p style="font-size:.68rem;color:var(--text-muted);margin-top:2px;line-height:1.4;">Card/Transfer. Min: ₦<?php echo number_format($korapay_minimum,2); ?></p>
                    </div>
                </div>
            </label>
            <?php endif; ?>
            <?php if ($cryptomus_enabled): ?>
            <!-- Cryptomus -->
            <label class="payment-method" style="display:block;cursor:pointer;">
                <input type="radio" name="type" value="cryptomus" class="sr-only" <?php if($first_checked){echo 'checked';$first_checked=false;} ?>>
                <div style="display:flex;align-items:flex-start;gap:10px;">
                    <div style="width:38px;height:38px;border-radius:9px;background:rgba(245,158,11,.1);display:flex;align-items:center;justify-content:center;flex-shrink:0;">
                        <i class="fab fa-bitcoin text-amber-500 text-base"></i>
                    </div>
                    <div>
                        <p style="font-weight:700;font-size:.78rem;color:var(--text-primary);">Cryptocurrency</p>
                        <p style="font-size:.68rem;color:var(--text-muted);margin-top:2px;line-height:1.4;">BTC/ETH/USDT. Min: ₦<?php echo number_format($cryptomus_minimum_ngn,2); ?></p>
                    </div>
                </div>
            </label>
            <?php endif; ?>
            <?php if ($flutterwave_enabled_flag): ?>
            <!-- Flutterwave -->
            <label class="payment-method" style="display:block;cursor:pointer;">
                <input type="radio" name="type" value="flutterwave" class="sr-only" <?php if($first_checked){echo 'checked';$first_checked=false;} ?>>
                <div style="display:flex;align-items:flex-start;gap:10px;">
                    <div style="width:38px;height:38px;border-radius:9px;background:rgba(59,130,246,.1);display:flex;align-items:center;justify-content:center;flex-shrink:0;">
                        <i class="fas fa-globe text-base" style="color:#2563eb;"></i>
                    </div>
                    <div>
                        <p style="font-weight:700;font-size:.78rem;color:var(--text-primary);">Flutterwave</p>
                        <p style="font-size:.68rem;color:var(--text-muted);margin-top:2px;line-height:1.4;">Cards, bank transfers & international. Min: ₦<?php echo number_format($flutterwave_minimum_ngn,2); ?></p>
                    </div>
                </div>
            </label>
            <?php endif; ?>
        </div>

        <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;">
            <div>
                <label style="display:block;font-size:.8rem;font-weight:600;color:var(--text-primary);margin-bottom:6px;">Amount</label>
                <div style="position:relative;">
                    <span style="position:absolute;left:14px;top:50%;transform:translateY(-50%);color:var(--text-muted);font-weight:600;">₦</span>
                    <input type="number" name="amount" id="amount" min="<?php echo floatval($paystack_minimum); ?>" placeholder="<?php echo ceil($paystack_minimum); ?>" required
                           style="width:100%;padding-left:32px;padding-right:14px;padding-top:12px;padding-bottom:12px;border-radius:10px;border:1.5px solid var(--card-border);background:var(--btn-bg);color:var(--hd-title);font-size:.88rem;outline:none;transition:border-color .2s;"
                           onfocus="this.style.borderColor='#22b864'" onblur="this.style.borderColor=''">
                </div>
            </div>
            <div>
                <label style="display:block;font-size:.8rem;font-weight:600;color:var(--text-primary);margin-bottom:6px;">Currency</label>
                <select name="currency" id="currency" style="width:100%;padding:12px 14px;border-radius:10px;border:1.5px solid var(--card-border);background:var(--btn-bg);color:var(--hd-title);font-size:.88rem;outline:none;">
                    <option value="NGN" <?php echo ($flutterwave_default_currency === 'NGN') ? 'selected' : ''; ?>>NGN</option>
                    <option value="USD" <?php echo ($flutterwave_default_currency === 'USD') ? 'selected' : ''; ?>>USD</option>
                    <option value="EUR">EUR</option>
                    <option value="GBP">GBP</option>
                    <option value="KES">KES</option>
                    <option value="GHS">GHS</option>
                    <option value="ZAR">ZAR</option>
                    <option value="CAD">CAD</option>
                    <option value="AUD">AUD</option>
                    <option value="JPY">JPY</option>
                    <option value="CNY">CNY</option>
                    <option value="AED">AED</option>
                    <option value="INR">INR</option>
                </select>
            </div>
        </div>
        <p style="font-size:.7rem;color:var(--text-muted);margin-top:5px;">Minimum: <span id="minAmount">₦<?php echo number_format($paystack_minimum,2); ?></span> • Wallet credits in NGN</p>

        <!-- Quick amount buttons -->
        <div style="display:flex;gap:8px;flex-wrap:wrap;">
            <?php foreach([500,1000,2000,5000,10000] as $qa): ?>
            <button type="button" onclick="document.getElementById('amount').value=<?php echo $qa; ?>"
                    style="padding:6px 12px;border-radius:8px;font-size:.72rem;font-weight:700;background:rgba(77,20,140,.07);border:1px solid rgba(77,20,140,.15);color:#4D148C;cursor:pointer;transition:all .2s;"
                    onmouseover="this.style.background='rgba(77,20,140,.15)'" onmouseout="this.style.background='rgba(77,20,140,.07)'">
                ₦<?php echo number_format($qa); ?>
            </button>
            <?php endforeach; ?>
        </div>

        <button type="submit" name="submit"
                style="width:100%;background:linear-gradient(135deg,#4D148C,#6b23c2);color:white;font-weight:700;padding:14px;border-radius:12px;border:none;cursor:pointer;font-size:.88rem;display:flex;align-items:center;justify-content:center;gap:8px;box-shadow:0 4px 16px rgba(77,20,140,.28);transition:all .2s;">
            <i class="fas fa-lock text-sm"></i> Proceed to Pay
        </button>
    </form>
</div>

<!-- Recent Transactions -->
<div class="fw-card anim anim-4">
    <p style="font-weight:700;font-size:.88rem;color:var(--text-primary);margin-bottom:14px;display:flex;align-items:center;gap:8px;">
        <span style="width:28px;height:28px;border-radius:8px;background:rgba(168,85,247,.1);display:inline-flex;align-items:center;justify-content:center;">
            <i class="fas fa-clock-rotate-left" style="font-size:.72rem;color:#9333ea;"></i>
        </span>
        Recent Transactions
    </p>
    <?php if (empty($transactions)): ?>
    <div style="text-align:center;padding:32px 0;">
        <div style="width:52px;height:52px;border-radius:50%;background:rgba(5,150,105,.07);display:flex;align-items:center;justify-content:center;margin:0 auto 12px;">
            <i class="fas fa-receipt" style="font-size:1.2rem;color:var(--text-muted);"></i>
        </div>
        <p style="color:var(--text-muted);font-size:.82rem;">No transactions yet</p>
    </div>
    <?php else: ?>
    <div style="display:flex;flex-direction:column;gap:8px;">
        <?php foreach ($transactions as $txn):
            $gw = $txn['payment_gateway'] ?? '';
            if ($gw === 'virtual_account')      $gw_label = '🏦 Bank Transfer';
            elseif ($gw === 'cryptomus')        $gw_label = '₿ Crypto';
            elseif ($gw === 'korapay')          $gw_label = '⚡ Korapay';
            elseif ($gw === 'paystack')         $gw_label = '💳 Paystack';
            elseif ($gw === 'virtual_number')   $gw_label = '&#128241; Virtual Number';
            elseif ($gw === 'paystack_dva')      $gw_label = '&#127974; Bank Transfer';
            else                                $gw_label = ucfirst($gw);
            if ($txn['status'] === 'successful')     { $sc='rgba(5,150,105,.08)'; $si='fa-check-circle'; $sic='#059669'; $badge='rgba(5,150,105,.1)'; $bc='#047857'; }
            elseif ($txn['status'] === 'failed')     { $sc='rgba(239,68,68,.06)'; $si='fa-times-circle'; $sic='#dc2626'; $badge='rgba(239,68,68,.08)'; $bc='#b91c1c'; }
            else                                      { $sc='rgba(245,158,11,.06)'; $si='fa-clock'; $sic='#d97706'; $badge='rgba(245,158,11,.1)'; $bc='#b45309'; }
        ?>
        <div class="txn-item">
            <div style="display:flex;align-items:center;justify-content:space-between;gap:10px;">
                <div style="display:flex;align-items:center;gap:10px;">
                    <div style="width:38px;height:38px;border-radius:9px;background:<?php echo $sc; ?>;display:flex;align-items:center;justify-content:center;flex-shrink:0;">
                        <i class="fas <?php echo $si; ?>" style="color:<?php echo $sic; ?>;"></i>
                    </div>
                    <div>
                        <p style="font-weight:600;font-size:.8rem;color:var(--text-primary);"><?php echo $gw_label; ?> Deposit</p>
                        <p style="font-size:.68rem;color:var(--text-muted);margin-top:1px;"><?php echo date('M d, Y — h:i A', strtotime($txn['created_at'])); ?></p>
                    </div>
                </div>
                <div style="text-align:right;flex-shrink:0;">
                    <p style="font-weight:700;font-size:.85rem;color:var(--text-primary);">₦<?php echo number_format($txn['amount'],2); ?></p>
                    <span style="font-size:.65rem;font-weight:600;padding:2px 8px;border-radius:99px;background:<?php echo $badge; ?>;color:<?php echo $bc; ?>;"><?php echo ucfirst($txn['status']); ?></span>
                </div>
            </div>
            <p style="font-size:.65rem;color:var(--text-muted);font-family:monospace;border-top:1px solid var(--card-border);padding-top:7px;margin-top:8px;">Ref: <?php echo htmlspecialchars($txn['transaction_ref']); ?></p>
        </div>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>
</div>
</div><!-- /max-w -->

<!-- Paystack & Korapay JS -->
<script src="https://js.paystack.co/v1/inline.js"></script>
<script src="https://korablobstorage.blob.core.windows.net/modal-bucket/korapay-collections.min.js"></script>
<script>
const mins={paystack:<?php echo floatval($paystack_minimum); ?>,korapay:<?php echo floatval($korapay_minimum); ?>,cryptomus:<?php echo floatval($cryptomus_minimum_ngn); ?>,flutterwave:<?php echo floatval($flutterwave_minimum_ngn); ?>};
document.querySelectorAll('input[name="type"]').forEach(r=>{
    r.addEventListener('change',function(){
        const m=mins[this.value]||mins.korapay;
        document.getElementById('minAmount').textContent='₦'+m.toLocaleString('en-NG',{minimumFractionDigits:2});
        document.getElementById('amount').min=m;
        document.getElementById('amount').placeholder=Math.ceil(m);
    });
});
function copyAccountNumber(){
    const acct=document.getElementById('va-account-number');if(!acct)return;
    const text=acct.innerText.trim();
    if(navigator.clipboard&&navigator.clipboard.writeText){navigator.clipboard.writeText(text).then(showCopied).catch(()=>fallbackCopy(text));}
    else{fallbackCopy(text);}
}
function showCopied(){
    document.getElementById('copy-icon').className='fa-solid fa-check';
    document.getElementById('copy-label').textContent='Copied!';
    setTimeout(()=>{document.getElementById('copy-icon').className='fa-regular fa-copy';document.getElementById('copy-label').textContent='Copy Account Number';},2500);
}
function fallbackCopy(text){const el=document.createElement('textarea');el.value=text;el.style.position='fixed';el.style.opacity='0';document.body.appendChild(el);el.select();try{document.execCommand('copy');showCopied();}catch(e){alert('Account number: '+text);}document.body.removeChild(el);}

function copyDvaNumber(){
    const acct=document.getElementById('dva-account-number');if(!acct)return;
    const text=acct.innerText.trim();
    if(navigator.clipboard&&navigator.clipboard.writeText){navigator.clipboard.writeText(text).then(showDvaCopied).catch(()=>fallbackDvaCopy(text));}
    else{fallbackDvaCopy(text);}
}
function showDvaCopied(){
    document.getElementById('dva-copy-icon').className='fa-solid fa-check';
    document.getElementById('dva-copy-label').textContent='Copied!';
    setTimeout(()=>{document.getElementById('dva-copy-icon').className='fa-regular fa-copy';document.getElementById('dva-copy-label').textContent='Copy Account Number';},2500);
}
function fallbackDvaCopy(text){const el=document.createElement('textarea');el.value=text;el.style.position='fixed';el.style.opacity='0';document.body.appendChild(el);el.select();try{document.execCommand('copy');showDvaCopied();}catch(e){alert('Account number: '+text);}document.body.removeChild(el);}

<?php if (isset($_SESSION['pending_transaction']) && !empty($_SESSION['pending_transaction']) && $_SESSION['pending_gateway'] !== 'cryptomus'): ?>
document.addEventListener('DOMContentLoaded',function(){
    const gateway='<?php echo addslashes($_SESSION['pending_gateway']); ?>';
    const reference='<?php echo addslashes($_SESSION['pending_transaction']); ?>';
    const amount=<?php echo floatval($_SESSION['pending_amount']); ?>;
    const email='<?php echo addslashes($user['email']); ?>';
    const name='<?php echo addslashes($user['full_name'] ?: $user['username']); ?>';
    if(gateway==='korapay'){
        window.Korapay.initialize({key:'<?php echo addslashes($korapay_public_key); ?>',reference,amount,currency:'NGN',
            customer:{name,email},
            onSuccess:d=>window.location.href='verify-payment?reference='+encodeURIComponent(d.reference)+'&gateway=korapay',
            onFailed:()=>{alert('Payment failed. Please try again.');window.location.href='fund-wallet';},
            onClose:()=>{alert('Payment cancelled.');window.location.href='fund-wallet';}
        });
    } else {
        PaystackPop.setup({key:'<?php echo addslashes($paystack_public_key); ?>',email,amount:amount*100,currency:'NGN',ref:reference,
            metadata:{custom_fields:[{display_name:"User ID",variable_name:"user_id",value:"<?php echo intval($user['id']); ?>"}]},
            callback:r=>window.location.href='verify-payment?reference='+encodeURIComponent(r.reference)+'&gateway=paystack',
            onClose:()=>{alert('Payment cancelled.');window.location.href='fund-wallet';}
        }).openIframe();
    }
});
<?php unset($_SESSION['pending_transaction'],$_SESSION['pending_amount'],$_SESSION['pending_gateway']); ?>
<?php endif; ?>
</script>

<?php include ('footer.php'); ?>