<?php
session_start();
require_once '../connection.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header("Location: ../login.php");
    exit();
}

// Get user ID
$user_id = $_SESSION['user_id'];

// Fetch user data
$stmt = $conn->prepare("SELECT *, 
    CASE WHEN withdrawal_pin IS NOT NULL THEN 'Set' ELSE 'Not Set' END as withdrawal_pin_status,
    CASE WHEN upgrade_pin IS NOT NULL THEN 'Set' ELSE 'Not Set' END as upgrade_pin_status,
    CASE WHEN tax_pin IS NOT NULL THEN 'Set' ELSE 'Not Set' END as tax_pin_status
    FROM users WHERE id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    session_destroy();
    header("Location: ../login.php?error=User account not found");
    exit();
}

$user = $result->fetch_assoc();
$stmt->close();

// Check account status
if (isset($user['account_status']) && $user['account_status'] != 'active') {
    $error_message = "Your account is " . $user['account_status'];
    header("Location: ../login.php?error=" . urlencode($error_message));
    exit();
}

// Fetch site settings
$site_settings = [];
$settings_stmt = $conn->prepare("SELECT setting_key, setting_value FROM site_settings WHERE setting_group = 'general'");
if ($settings_stmt) {
    if ($settings_stmt->execute()) {
        $settings_result = $settings_stmt->get_result();
        while ($row = $settings_result->fetch_assoc()) {
            $site_settings[$row['setting_key']] = $row['setting_value'];
        }
        $settings_result->free();
    }
    $settings_stmt->close();
} else {
    $site_settings['site_name'] = 'Trading Platform';
    $site_settings['site_email'] = 'support@example.com';
    $site_settings['min_withdrawal_amount'] = '50';
    $site_settings['max_withdrawal_amount'] = '50000';
    $site_settings['withdrawal_fee_percent'] = '0'; // 0% fee by default
    $site_settings['withdrawal_instruction'] = 'Enter your withdrawal amount and select payment method.';
}

// Fetch payment methods for withdrawals
$payment_methods = [];
$payment_stmt = $conn->prepare("SELECT * FROM payment_tb WHERE status = 'active' ORDER BY is_default DESC, payment_type ASC");
if ($payment_stmt) {
    if ($payment_stmt->execute()) {
        $payment_result = $payment_stmt->get_result();
        while ($row = $payment_result->fetch_assoc()) {
            $payment_methods[] = $row;
        }
        $payment_result->free();
    }
    $payment_stmt->close();
}

// Filter payment methods
$crypto_methods = array_filter($payment_methods, function($method) {
    return $method['payment_type'] === 'crypto';
});

$bank_methods = array_filter($payment_methods, function($method) {
    return $method['payment_type'] === 'bank';
});

// Check if user has all required PINs
$has_withdrawal_pin = !empty($user['withdrawal_pin']);
$has_upgrade_pin = !empty($user['upgrade_pin']);
$has_tax_pin = !empty($user['tax_pin']);
$upgrade_fee = floatval($user['upgrade_fee'] ?? 0);
$tax_fee = floatval($user['tax_fee'] ?? 0);

// Initialize variables
$success_message = '';
$error_message = '';
$withdrawal_pin_verified = false;
$upgrade_pin_verified = false;
$tax_pin_verified = false;
$pin_error = '';
$current_pin_step = 'withdrawal'; // withdrawal, upgrade, tax, or complete
$withdrawal_data = []; // Store withdrawal data for PIN verification

// Check which PINs need verification
$needs_withdrawal_pin = $has_withdrawal_pin;
$needs_upgrade_pin = $has_upgrade_pin && $upgrade_fee > 0;
$needs_tax_pin = $has_tax_pin && $tax_fee > 0;

// Check if we have withdrawal data from form submission
if (isset($_SESSION['withdrawal_data'])) {
    $withdrawal_data = $_SESSION['withdrawal_data'];
}

// Check PIN verification session
if (isset($_SESSION['withdrawal_pin_verified']) && isset($_SESSION['pin_verified_time'])) {
    $verification_time = $_SESSION['pin_verified_time'];
    $current_time = time();
    $expiry_time = 300; // 5 minutes in seconds
    
    if (($current_time - $verification_time) <= $expiry_time) {
        $withdrawal_pin_verified = $_SESSION['withdrawal_pin_verified'];
        $upgrade_pin_verified = $_SESSION['upgrade_pin_verified'] ?? false;
        $tax_pin_verified = $_SESSION['tax_pin_verified'] ?? false;
    } else {
        // Clear all PIN verifications if expired
        unset($_SESSION['withdrawal_pin_verified']);
        unset($_SESSION['upgrade_pin_verified']);
        unset($_SESSION['tax_pin_verified']);
        unset($_SESSION['pin_verified_time']);
        unset($_SESSION['current_pin_step']);
        unset($_SESSION['withdrawal_data']);
    }
}

// Determine current PIN step based on verification status
if ($withdrawal_pin_verified) {
    if ($needs_upgrade_pin && !$upgrade_pin_verified) {
        $current_pin_step = 'upgrade';
    } elseif ($needs_tax_pin && !$tax_pin_verified) {
        $current_pin_step = 'tax';
    } else {
        $current_pin_step = 'complete';
    }
}

// Handle withdrawal form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_withdrawal'])) {
    // First, validate withdrawal data
    $amount = floatval($_POST['amount'] ?? 0);
    $payment_method_id = intval($_POST['payment_method_id'] ?? 0);
    $wallet_address = trim($_POST['wallet_address'] ?? '');
    $bank_details = trim($_POST['bank_details'] ?? '');
    
    // Validation
    $min_withdrawal = floatval($site_settings['min_withdrawal_amount'] ?? 50);
    $max_withdrawal = floatval($site_settings['max_withdrawal_amount'] ?? 50000);
    $withdrawal_fee_percent = floatval($site_settings['withdrawal_fee_percent'] ?? 0);
    $account_balance = floatval($user['account_balance'] ?? 0);
    
    // Calculate fees
    $withdrawal_fee_amount = ($amount * $withdrawal_fee_percent) / 100;
    $upgrade_fee_amount = $upgrade_fee;
    $tax_fee_amount = $tax_fee;
    $total_fees = $withdrawal_fee_amount + $upgrade_fee_amount + $tax_fee_amount;
    $net_amount = $amount - $total_fees;
    
    // Store withdrawal data in session for later use
    $withdrawal_data = [
        'amount' => $amount,
        'payment_method_id' => $payment_method_id,
        'wallet_address' => $wallet_address,
        'bank_details' => $bank_details,
        'withdrawal_fee_amount' => $withdrawal_fee_amount,
        'upgrade_fee_amount' => $upgrade_fee_amount,
        'tax_fee_amount' => $tax_fee_amount,
        'total_fees' => $total_fees,
        'net_amount' => $net_amount
    ];
    
    $_SESSION['withdrawal_data'] = $withdrawal_data;
    
    // Basic validation
    if ($amount < $min_withdrawal) {
        $error_message = "Minimum withdrawal amount is $" . number_format($min_withdrawal, 2);
    } elseif ($amount > $max_withdrawal) {
        $error_message = "Maximum withdrawal amount is $" . number_format($max_withdrawal, 2);
    } elseif ($amount > $account_balance) {
        $error_message = "Insufficient balance. Available balance: $" . number_format($account_balance, 2);
    } elseif ($payment_method_id <= 0) {
        $error_message = "Please select a payment method";
    } else {
        // Get selected payment method
        $method_stmt = $conn->prepare("SELECT * FROM payment_tb WHERE id = ? AND status = 'active'");
        $method_stmt->bind_param("i", $payment_method_id);
        $method_stmt->execute();
        $method_result = $method_stmt->get_result();
        
        if ($method_result->num_rows === 0) {
            $error_message = "Selected payment method is not available";
        } else {
            $selected_method = $method_result->fetch_assoc();
            $method_stmt->close();
            
            // Validate wallet address for crypto
            if ($selected_method['payment_type'] === 'crypto') {
                if (empty($wallet_address)) {
                    $error_message = "Please enter your wallet address";
                } elseif (strlen($wallet_address) < 20) {
                    $error_message = "Please enter a valid wallet address";
                }
            }
            
            // Validate bank details for bank transfer
            if ($selected_method['payment_type'] === 'bank') {
                if (empty($bank_details)) {
                    $error_message = "Please enter your bank account details";
                }
            }
            
            if (!$error_message) {
                // Store payment method details
                $withdrawal_data['payment_type'] = $selected_method['payment_type'];
                $withdrawal_data['payment_method_name'] = $selected_method['payment_type'] === 'crypto' 
                    ? $selected_method['wallet_name'] 
                    : $selected_method['bank_name'];
                $_SESSION['withdrawal_data'] = $withdrawal_data;
                
                // Check if PIN verification is needed
                if ($has_withdrawal_pin || ($has_upgrade_pin && $upgrade_fee > 0) || ($has_tax_pin && $tax_fee > 0)) {
                    // PIN verification required
                    $withdrawal_pin_verified = false;
                    $upgrade_pin_verified = false;
                    $tax_pin_verified = false;
                    $current_pin_step = 'withdrawal';
                    
                    // Clear any previous PIN verification
                    unset($_SESSION['withdrawal_pin_verified']);
                    unset($_SESSION['upgrade_pin_verified']);
                    unset($_SESSION['tax_pin_verified']);
                    unset($_SESSION['pin_verified_time']);
                    $_SESSION['current_pin_step'] = $current_pin_step;
                } else {
                    // No PINs set, proceed directly to withdrawal processing
                    $current_pin_step = 'complete';
                    $withdrawal_pin_verified = true;
                    $upgrade_pin_verified = true;
                    $tax_pin_verified = true;
                }
            }
        }
    }
}

// Handle PIN verification
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['verify_withdrawal_pin'])) {
        $entered_pin = trim($_POST['withdrawal_pin'] ?? '');
        
        if (empty($entered_pin)) {
            $pin_error = "Please enter your withdrawal PIN";
        } elseif (!$has_withdrawal_pin) {
            $pin_error = "Withdrawal PIN is not set. Please contact support.";
        } elseif (!password_verify($entered_pin, $user['withdrawal_pin'])) {
            $pin_error = "Invalid withdrawal PIN";
        } else {
            $withdrawal_pin_verified = true;
            $_SESSION['withdrawal_pin_verified'] = true;
            $_SESSION['pin_verified_time'] = time();
            
            if ($needs_upgrade_pin) {
                $current_pin_step = 'upgrade';
            } elseif ($needs_tax_pin) {
                $current_pin_step = 'tax';
            } else {
                $current_pin_step = 'complete';
            }
            $_SESSION['current_pin_step'] = $current_pin_step;
        }
    }
    
    if (isset($_POST['verify_upgrade_pin'])) {
        $entered_pin = trim($_POST['upgrade_pin'] ?? '');
        
        if (empty($entered_pin)) {
            $pin_error = "Please enter your upgrade PIN";
        } elseif (!$has_upgrade_pin) {
            $pin_error = "Upgrade PIN is not set. Please contact support.";
        } elseif (!password_verify($entered_pin, $user['upgrade_pin'])) {
            $pin_error = "Invalid upgrade PIN";
        } else {
            $upgrade_pin_verified = true;
            $_SESSION['upgrade_pin_verified'] = true;
            $_SESSION['pin_verified_time'] = time(); // Reset timer
            
            if ($needs_tax_pin) {
                $current_pin_step = 'tax';
            } else {
                $current_pin_step = 'complete';
            }
            $_SESSION['current_pin_step'] = $current_pin_step;
        }
    }
    
    if (isset($_POST['verify_tax_pin'])) {
        $entered_pin = trim($_POST['tax_pin'] ?? '');
        
        if (empty($entered_pin)) {
            $pin_error = "Please enter your tax PIN";
        } elseif (!$has_tax_pin) {
            $pin_error = "Tax PIN is not set. Please contact support.";
        } elseif (!password_verify($entered_pin, $user['tax_pin'])) {
            $pin_error = "Invalid tax PIN";
        } else {
            $tax_pin_verified = true;
            $_SESSION['tax_pin_verified'] = true;
            $_SESSION['pin_verified_time'] = time(); // Reset timer
            $current_pin_step = 'complete';
            $_SESSION['current_pin_step'] = 'complete';
        }
    }
}

// Check if all required PINs are verified
$all_pins_verified = true;
if ($has_withdrawal_pin) {
    $all_pins_verified = $all_pins_verified && $withdrawal_pin_verified;
}
if ($has_upgrade_pin && $upgrade_fee > 0) {
    $all_pins_verified = $all_pins_verified && $upgrade_pin_verified;
}
if ($has_tax_pin && $tax_fee > 0) {
    $all_pins_verified = $all_pins_verified && $tax_pin_verified;
}

// Process withdrawal if all PINs are verified and we have withdrawal data
if ($all_pins_verified && !empty($withdrawal_data) && isset($_SESSION['withdrawal_data'])) {
    // Extract withdrawal data from session
    $amount = $withdrawal_data['amount'];
    $payment_method_id = $withdrawal_data['payment_method_id'];
    $wallet_address = $withdrawal_data['wallet_address'];
    $bank_details = $withdrawal_data['bank_details'];
    $withdrawal_fee_amount = $withdrawal_data['withdrawal_fee_amount'];
    $upgrade_fee_amount = $withdrawal_data['upgrade_fee_amount'];
    $tax_fee_amount = $withdrawal_data['tax_fee_amount'];
    $total_fees = $withdrawal_data['total_fees'];
    $net_amount = $withdrawal_data['net_amount'];
    
    // Get selected payment method again
    $method_stmt = $conn->prepare("SELECT * FROM payment_tb WHERE id = ? AND status = 'active'");
    $method_stmt->bind_param("i", $payment_method_id);
    $method_stmt->execute();
    $method_result = $method_stmt->get_result();
    
    if ($method_result->num_rows > 0) {
        $selected_method = $method_result->fetch_assoc();
        $method_stmt->close();
        
        // Start transaction
        $conn->begin_transaction();
        
        try {
            // Create withdrawals table if it doesn't exist
            $check_table = $conn->query("SHOW TABLES LIKE 'withdrawals'");
            if ($check_table->num_rows === 0) {
                $create_table_sql = "
                    CREATE TABLE IF NOT EXISTS withdrawals (
                        id INT PRIMARY KEY AUTO_INCREMENT,
                        user_id INT NOT NULL,
                        transaction_id VARCHAR(50) UNIQUE NOT NULL,
                        amount DECIMAL(15,2) NOT NULL,
                        withdrawal_fee DECIMAL(15,2) DEFAULT 0.00,
                        upgrade_fee DECIMAL(15,2) DEFAULT 0.00,
                        tax_fee DECIMAL(15,2) DEFAULT 0.00,
                        total_fees DECIMAL(15,2) DEFAULT 0.00,
                        net_amount DECIMAL(15,2) NOT NULL,
                        payment_method_id INT NOT NULL,
                        payment_type ENUM('crypto', 'bank') NOT NULL,
                        wallet_address VARCHAR(500),
                        bank_details TEXT,
                        status ENUM('pending', 'processing', 'completed', 'rejected') DEFAULT 'pending',
                        admin_notes TEXT,
                        processed_by INT,
                        processed_at TIMESTAMP NULL DEFAULT NULL,
                        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                        INDEX idx_user_id (user_id),
                        INDEX idx_status (status),
                        INDEX idx_created_at (created_at),
                        FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
                    )
                ";
                
                if (!$conn->query($create_table_sql)) {
                    throw new Exception("Failed to create withdrawals table: " . $conn->error);
                }
            }
            
// Generate unique transaction ID
$transaction_id = 'WTH' . time() . rand(10000, 99999) . $user_id;

// Insert withdrawal record - CORRECTED BIND_PARAM
if ($selected_method['payment_type'] === 'crypto') {
    $withdrawal_stmt = $conn->prepare("
        INSERT INTO withdrawals 
        (user_id, transaction_id, amount, withdrawal_fee, upgrade_fee, tax_fee, total_fees, net_amount, 
         payment_method_id, payment_type, wallet_address, bank_details, status, created_at, updated_at) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, 'pending', NOW(), NOW())
    ");
    
    $withdrawal_stmt->bind_param(
        "isdssssdiss",
        $user_id,
        $transaction_id,
        $amount,
        $withdrawal_fee_amount,
        $upgrade_fee_amount,
        $tax_fee_amount,
        $total_fees,
        $net_amount,
        $payment_method_id,
        $selected_method['payment_type'],
        $wallet_address
    );
} else {
    $withdrawal_stmt = $conn->prepare("
        INSERT INTO withdrawals 
        (user_id, transaction_id, amount, withdrawal_fee, upgrade_fee, tax_fee, total_fees, net_amount, 
         payment_method_id, payment_type, wallet_address, bank_details, status, created_at, updated_at) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, 'pending', NOW(), NOW())
    ");
    
    $withdrawal_stmt->bind_param(
        "isdssssdiss",
        $user_id,
        $transaction_id,
        $amount,
        $withdrawal_fee_amount,
        $upgrade_fee_amount,
        $tax_fee_amount,
        $total_fees,
        $net_amount,
        $payment_method_id,
        $selected_method['payment_type'],
        $bank_details
    );
}

            if (!$withdrawal_stmt->execute()) {
                throw new Exception("Failed to insert withdrawal record: " . $withdrawal_stmt->error);
            }
            
            // Update user statistics (NOT deducting balance)
            $update_stmt = $conn->prepare("
                UPDATE users SET 
                total_withdrawals = total_withdrawals + ?,
                last_withdrawal = NOW(),
                updated_at = NOW()
                WHERE id = ?
            ");
            
            $update_stmt->bind_param("di", $amount, $user_id);
            
            if (!$update_stmt->execute()) {
                throw new Exception("Failed to update user statistics: " . $update_stmt->error);
            }
            
            // Create notification
            try {
                $notification_stmt = $conn->prepare("
                    INSERT INTO notifications 
                    (user_id, notification_type, title, message, created_at) 
                    VALUES (?, 'transaction', 'Withdrawal Request Submitted', ?, NOW())
                ");
                $notification_msg = "Your withdrawal request of $" . number_format($amount, 2) . " has been submitted. Transaction ID: " . $transaction_id;
                $notification_stmt->bind_param("is", $user_id, $notification_msg);
                $notification_stmt->execute();
            } catch (Exception $e) {
                // Notification failure shouldn't stop the transaction
                error_log("Notification error: " . $e->getMessage());
            }
            
            $conn->commit();
            
            // Clear all PIN verification sessions and withdrawal data
            unset($_SESSION['withdrawal_pin_verified']);
            unset($_SESSION['upgrade_pin_verified']);
            unset($_SESSION['tax_pin_verified']);
            unset($_SESSION['pin_verified_time']);
            unset($_SESSION['current_pin_step']);
            unset($_SESSION['withdrawal_data']);
            
            $success_message = "Withdrawal request submitted successfully! Transaction ID: " . $transaction_id . 
                              ". Amount: $" . number_format($amount, 2) . 
                              ($total_fees > 0 ? " (Total Fees: $" . number_format($total_fees, 2) . ")" : "") . 
                              ". Net amount: $" . number_format($net_amount, 2) . ". Please wait for processing.";
            
            // Reset withdrawal data
            $withdrawal_data = [];
            $all_pins_verified = false;
            $withdrawal_pin_verified = false;
            $upgrade_pin_verified = false;
            $tax_pin_verified = false;
            $current_pin_step = 'withdrawal';
            
        } catch (Exception $e) {
            $conn->rollback();
            $error_message = "Failed to process withdrawal: " . $e->getMessage();
        }
    }
}

// Get user's recent withdrawals
$recent_withdrawals = [];
$check_table = $conn->query("SHOW TABLES LIKE 'withdrawals'");
if ($check_table->num_rows > 0) {
    $withdrawal_stmt = $conn->prepare("
        SELECT w.*, p.payment_type, p.wallet_name, p.bank_name 
        FROM withdrawals w 
        LEFT JOIN payment_tb p ON w.payment_method_id = p.id 
        WHERE w.user_id = ? 
        ORDER BY w.created_at DESC 
        LIMIT 5
    ");
    if ($withdrawal_stmt) {
        $withdrawal_stmt->bind_param("i", $user_id);
        if ($withdrawal_stmt->execute()) {
            $withdrawal_result = $withdrawal_stmt->get_result();
            while ($row = $withdrawal_result->fetch_assoc()) {
                $recent_withdrawals[] = $row;
            }
            $withdrawal_result->free();
        }
        $withdrawal_stmt->close();
    }
}

// Get user's account balance
$account_balance = floatval($user['account_balance'] ?? 0);
$total_withdrawals = floatval($user['total_withdrawals'] ?? 0);
$last_withdrawal = $user['last_withdrawal'] ?? null;

// Format dates
$last_withdrawal_date = $last_withdrawal ? date('M d, Y h:i A', strtotime($last_withdrawal)) : 'No withdrawals yet';

// Set default payment method
$default_crypto = null;
$default_bank = null;
foreach ($payment_methods as $method) {
    if ($method['is_default'] == 1) {
        if ($method['payment_type'] == 'crypto' && !$default_crypto) {
            $default_crypto = $method;
        } elseif ($method['payment_type'] == 'bank' && !$default_bank) {
            $default_bank = $method;
        }
    }
}

// Account ID for display
$account_id = str_pad($user['id'], 8, '0', STR_PAD_LEFT);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Withdraw Funds - <?php echo htmlspecialchars($site_settings['site_name'] ?? 'Trading Platform'); ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    
    <style>
        :root {
            --sidebar-width: 16rem;
            --primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            --danger-gradient: linear-gradient(135deg, #f56565 0%, #ed64a6 100%);
            --success-gradient: linear-gradient(135deg, #10b981 0%, #059669 100%);
            --warning-gradient: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
            --info-gradient: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Inter', sans-serif;
            background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%);
            min-height: 100vh;
            color: #e2e8f0;
        }
        
        /* Sidebar Styles */
        .sidebar {
            background: linear-gradient(180deg, #1e293b 0%, #0f172a 100%);
            width: var(--sidebar-width);
            height: 100vh;
            position: fixed;
            left: 0;
            top: 0;
            z-index: 1000;
            transform: translateX(-100%);
            transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            overflow-y: auto;
            box-shadow: 4px 0 20px rgba(0, 0, 0, 0.3);
            border-right: 1px solid rgba(255, 255, 255, 0.05);
        }
        
        .sidebar.active {
            transform: translateX(0);
        }
        
        @media (min-width: 1024px) {
            .sidebar {
                transform: translateX(0) !important;
            }
        }
        
        .sidebar-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.7);
            z-index: 999;
            backdrop-filter: blur(4px);
        }
        
        .sidebar-overlay.active {
            display: block;
        }
        
        /* Main Content */
        .main-content {
            width: 100%;
            min-height: 100vh;
            transition: margin-left 0.3s ease;
        }
        
        @media (min-width: 1024px) {
            .main-content {
                margin-left: var(--sidebar-width);
                width: calc(100% - var(--sidebar-width));
            }
        }
        
        /* Mobile Menu Button */
        .mobile-menu-btn {
            position: fixed;
            top: 1.5rem;
            left: 1.5rem;
            z-index: 1100;
            width: 3rem;
            height: 3rem;
            background: rgba(30, 41, 59, 0.95);
            border-radius: 0.75rem;
            display: flex;
            align-items: center;
            justify-content: center;
            border: 1px solid rgba(255, 255, 255, 0.1);
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
            transition: all 0.3s ease;
            backdrop-filter: blur(10px);
        }
        
        @media (min-width: 1024px) {
            .mobile-menu-btn {
                display: none;
            }
        }
        
        /* Navigation Items */
        .nav-item {
            display: flex;
            align-items: center;
            padding: 0.875rem 1rem;
            border-radius: 0.75rem;
            margin: 0.25rem 0.75rem;
            color: #94a3b8;
            text-decoration: none;
            transition: all 0.2s ease;
            position: relative;
            overflow: hidden;
        }
        
        .nav-item::before {
            content: '';
            position: absolute;
            left: 0;
            top: 0;
            height: 100%;
            width: 3px;
            background: var(--primary-gradient);
            transform: translateX(-100%);
            transition: transform 0.3s ease;
        }
        
        .nav-item:hover {
            background: rgba(255, 255, 255, 0.05);
            color: #e2e8f0;
            transform: translateX(4px);
        }
        
        .nav-item:hover::before {
            transform: translateX(0);
        }
        
        .nav-item.active {
            background: rgba(102, 126, 234, 0.1);
            color: #e2e8f0;
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.15);
        }
        
        .nav-item.active::before {
            transform: translateX(0);
        }
        
        .nav-item.active i {
            color: #667eea;
            transform: scale(1.1);
        }
        
        .nav-item i {
            width: 1.5rem;
            margin-right: 0.875rem;
            transition: all 0.2s ease;
            font-size: 1.1rem;
        }
        
        /* Card Styles */
        .glass-card {
            background: rgba(30, 41, 59, 0.7);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.1);
            border-radius: 1.25rem;
            transition: all 0.3s ease;
        }
        
        .glass-card:hover {
            transform: translateY(-4px);
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
            border-color: rgba(102, 126, 234, 0.3);
        }
        
        .danger-card {
            background: linear-gradient(135deg, rgba(245, 101, 101, 0.15) 0%, rgba(237, 100, 166, 0.15) 100%);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(245, 101, 101, 0.2);
            border-radius: 1.25rem;
        }
        
        .warning-card {
            background: linear-gradient(135deg, rgba(245, 158, 11, 0.15) 0%, rgba(217, 119, 6, 0.15) 100%);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(245, 158, 11, 0.2);
            border-radius: 1.25rem;
        }
        
        .info-card {
            background: linear-gradient(135deg, rgba(59, 130, 246, 0.15) 0%, rgba(29, 78, 216, 0.15) 100%);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(59, 130, 246, 0.2);
            border-radius: 1.25rem;
        }
        
        /* Form Styles */
        .form-input {
            background: rgba(255, 255, 255, 0.05);
            border: 1px solid rgba(255, 255, 255, 0.1);
            border-radius: 0.75rem;
            padding: 0.875rem 1rem;
            color: #e2e8f0;
            font-size: 0.95rem;
            transition: all 0.2s ease;
            width: 100%;
        }
        
        .form-input:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
            background: rgba(255, 255, 255, 0.08);
        }
        
        .form-input::placeholder {
            color: #94a3b8;
        }
        
        .form-label {
            display: block;
            color: #cbd5e0;
            font-size: 0.875rem;
            font-weight: 500;
            margin-bottom: 0.5rem;
        }
        
        .form-group {
            margin-bottom: 1.5rem;
        }
        
        .form-select {
            background: rgba(255, 255, 255, 0.05);
            border: 1px solid rgba(255, 255, 255, 0.1);
            border-radius: 0.75rem;
            padding: 0.875rem 1rem;
            color: #e2e8f0;
            font-size: 0.95rem;
            transition: all 0.2s ease;
            width: 100%;
            appearance: none;
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3E%3Cpath stroke='%2394a3b8' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M6 8l4 4 4-4'/%3E%3C/svg%3E");
            background-position: right 0.75rem center;
            background-repeat: no-repeat;
            background-size: 1.5em 1.5em;
        }
        
        .form-select:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
            background-color: rgba(255, 255, 255, 0.08);
        }
        
        .btn-primary {
            background: var(--primary-gradient);
            color: white;
            border: none;
            border-radius: 0.75rem;
            padding: 0.875rem 1.75rem;
            font-weight: 600;
            font-size: 0.95rem;
            cursor: pointer;
            transition: all 0.2s ease;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 0.5rem;
        }
        
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px -5px rgba(102, 126, 234, 0.4);
        }
        
        .btn-primary:active {
            transform: translateY(0);
        }
        
        .btn-danger {
            background: var(--danger-gradient);
            color: white;
            border: none;
            border-radius: 0.75rem;
            padding: 0.875rem 1.75rem;
            font-weight: 600;
            font-size: 0.95rem;
            cursor: pointer;
            transition: all 0.2s ease;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 0.5rem;
        }
        
        .btn-danger:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px -5px rgba(245, 101, 101, 0.4);
        }
        
        .btn-warning {
            background: var(--warning-gradient);
            color: white;
            border: none;
            border-radius: 0.75rem;
            padding: 0.875rem 1.75rem;
            font-weight: 600;
            font-size: 0.95rem;
            cursor: pointer;
            transition: all 0.2s ease;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 0.5rem;
        }
        
        .btn-warning:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px -5px rgba(245, 158, 11, 0.4);
        }
        
        .btn-info {
            background: var(--info-gradient);
            color: white;
            border: none;
            border-radius: 0.75rem;
            padding: 0.875rem 1.75rem;
            font-weight: 600;
            font-size: 0.95rem;
            cursor: pointer;
            transition: all 0.2s ease;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 0.5rem;
        }
        
        .btn-info:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px -5px rgba(59, 130, 246, 0.4);
        }
        
        .btn-secondary {
            background: rgba(255, 255, 255, 0.05);
            color: #cbd5e0;
            border: 1px solid rgba(255, 255, 255, 0.1);
            border-radius: 0.75rem;
            padding: 0.875rem 1.75rem;
            font-weight: 500;
            font-size: 0.95rem;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .btn-secondary:hover {
            background: rgba(255, 255, 255, 0.1);
            color: #e2e8f0;
        }
        
        /* Alert Messages */
        .alert-success {
            background: rgba(72, 187, 120, 0.1);
            border: 1px solid rgba(72, 187, 120, 0.2);
            color: #48bb78;
            padding: 1rem 1.5rem;
            border-radius: 0.75rem;
            margin-bottom: 1.5rem;
            display: flex;
            align-items: center;
            gap: 0.75rem;
            animation: slideIn 0.3s ease-out;
        }
        
        .alert-error {
            background: rgba(245, 101, 101, 0.1);
            border: 1px solid rgba(245, 101, 101, 0.2);
            color: #f56565;
            padding: 1rem 1.5rem;
            border-radius: 0.75rem;
            margin-bottom: 1.5rem;
            display: flex;
            align-items: center;
            gap: 0.75rem;
            animation: slideIn 0.3s ease-out;
        }
        
        .alert-info {
            background: rgba(59, 130, 246, 0.1);
            border: 1px solid rgba(59, 130, 246, 0.2);
            color: #3b82f6;
            padding: 1rem 1.5rem;
            border-radius: 0.75rem;
            margin-bottom: 1.5rem;
            display: flex;
            align-items: center;
            gap: 0.75rem;
        }
        
        .alert-warning {
            background: rgba(245, 158, 11, 0.1);
            border: 1px solid rgba(245, 158, 11, 0.2);
            color: #f59e0b;
            padding: 1rem 1.5rem;
            border-radius: 0.75rem;
            margin-bottom: 1.5rem;
            display: flex;
            align-items: center;
            gap: 0.75rem;
        }
        
        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(-10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        /* PIN Input Styles */
        .pin-input-container {
            display: flex;
            justify-content: center;
            gap: 0.75rem;
            margin: 1.5rem 0;
        }
        
        .pin-input {
            width: 3.5rem;
            height: 3.5rem;
            text-align: center;
            font-size: 1.5rem;
            font-weight: bold;
            background: rgba(255, 255, 255, 0.05);
            border: 2px solid rgba(255, 255, 255, 0.1);
            border-radius: 0.75rem;
            color: #e2e8f0;
            transition: all 0.2s ease;
        }
        
        .pin-input:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
            background: rgba(255, 255, 255, 0.08);
            outline: none;
        }
        
        /* Payment Method Cards */
        .payment-method-card {
            background: rgba(255, 255, 255, 0.03);
            border: 1px solid rgba(255, 255, 255, 0.1);
            border-radius: 1rem;
            padding: 1.5rem;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .payment-method-card:hover {
            background: rgba(255, 255, 255, 0.05);
            border-color: #667eea;
            transform: translateY(-2px);
        }
        
        .payment-method-card.selected {
            background: rgba(102, 126, 234, 0.1);
            border-color: #667eea;
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.15);
        }
        
        /* Crypto Network Badge */
        .network-badge {
            display: inline-flex;
            align-items: center;
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 500;
            margin-top: 0.5rem;
        }
        
        .network-btc {
            background: rgba(247, 147, 26, 0.1);
            color: #f7931a;
            border: 1px solid rgba(247, 147, 26, 0.2);
        }
        
        .network-eth {
            background: rgba(118, 92, 222, 0.1);
            color: #767cde;
            border: 1px solid rgba(118, 92, 222, 0.2);
        }
        
        .network-usdt {
            background: rgba(38, 161, 123, 0.1);
            color: #26a17b;
            border: 1px solid rgba(38, 161, 123, 0.2);
        }
        
        /* Progress Bar */
        .progress-bar {
            height: 6px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 3px;
            overflow: hidden;
            margin-top: 0.5rem;
        }
        
        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #667eea, #764ba2);
            border-radius: 3px;
        }
        
        /* Status Badges */
        .status-badge {
            display: inline-flex;
            align-items: center;
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 500;
        }
        
        .status-pending {
            background: rgba(245, 158, 11, 0.1);
            color: #f59e0b;
            border: 1px solid rgba(245, 158, 11, 0.2);
        }
        
        .status-processing {
            background: rgba(59, 130, 246, 0.1);
            color: #3b82f6;
            border: 1px solid rgba(59, 130, 246, 0.2);
        }
        
        .status-completed {
            background: rgba(72, 187, 120, 0.1);
            color: #48bb78;
            border: 1px solid rgba(72, 187, 120, 0.2);
        }
        
        .status-rejected {
            background: rgba(245, 101, 101, 0.1);
            color: #f56565;
            border: 1px solid rgba(245, 101, 101, 0.2);
        }
        
        /* Withdrawal Form */
        #withdrawalForm {
            transition: all 0.3s ease;
        }
        
        /* Hidden class */
        .hidden {
            display: none !important;
        }
        
        /* PIN Verification Steps */
        .pin-steps-container {
            display: flex;
            justify-content: center;
            gap: 2rem;
            margin-bottom: 2rem;
        }
        
        .pin-step {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 0.5rem;
            position: relative;
        }
        
        .pin-step:not(:last-child)::after {
            content: '';
            position: absolute;
            top: 1rem;
            right: -2rem;
            width: 2rem;
            height: 2px;
            background: rgba(255, 255, 255, 0.1);
        }
        
        .pin-step-icon {
            width: 2.5rem;
            height: 2.5rem;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1rem;
            transition: all 0.3s ease;
        }
        
        .pin-step-icon.pending {
            background: rgba(255, 255, 255, 0.05);
            border: 2px solid rgba(255, 255, 255, 0.1);
            color: #94a3b8;
        }
        
        .pin-step-icon.active {
            background: rgba(102, 126, 234, 0.2);
            border: 2px solid #667eea;
            color: #667eea;
            box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.1);
        }
        
        .pin-step-icon.completed {
            background: rgba(72, 187, 120, 0.2);
            border: 2px solid #48bb78;
            color: #48bb78;
        }
        
        .pin-step-label {
            font-size: 0.75rem;
            color: #94a3b8;
        }
        
        .pin-step.active .pin-step-label {
            color: #667eea;
            font-weight: 500;
        }
        
        .pin-step.completed .pin-step-label {
            color: #48bb78;
        }
        
        /* Scrollbar */
        ::-webkit-scrollbar {
            width: 6px;
            height: 6px;
        }
        
        ::-webkit-scrollbar-track {
            background: rgba(255, 255, 255, 0.05);
        }
        
        ::-webkit-scrollbar-thumb {
            background: var(--primary-gradient);
            border-radius: 3px;
        }
        
        /* Animations */
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .animate-fade-in {
            animation: fadeIn 0.5s ease-out;
        }
        
        @keyframes shake {
            0%, 100% { transform: translateX(0); }
            10%, 30%, 50%, 70%, 90% { transform: translateX(-5px); }
            20%, 40%, 60%, 80% { transform: translateX(5px); }
        }
        
        .shake {
            animation: shake 0.5s ease-in-out;
        }
        
        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.5; }
        }
        
        .pulse {
            animation: pulse 2s infinite;
        }
    </style>
</head>
<body class="text-white">
    <?php include("nav.php"); ?>
    
    <!-- Main Content -->
    <div class="main-content">
        <!-- Top Bar -->
        <div class="border-b border-gray-800/50 p-6 glass-card mx-4 mt-4">
            <div class="flex flex-col lg:flex-row lg:justify-between lg:items-center gap-6">
                <div>
                    <h2 class="text-2xl lg:text-3xl font-bold bg-gradient-to-r from-blue-400 to-purple-400 bg-clip-text text-transparent">
                        Withdraw Funds
                    </h2>
                    <p class="text-gray-400 mt-2">
                        Withdraw your earnings securely using various payment methods
                    </p>
                </div>
                <div class="flex items-center gap-4">
                    <div class="hidden lg:block">
                        <div class="flex items-center gap-2 px-4 py-2 bg-gray-800/50 rounded-lg">
                            <i class="fas fa-wallet text-blue-400"></i>
                            <span class="text-sm">Balance: <span class="font-bold text-green-400">$<?php echo number_format($account_balance, 2); ?></span></span>
                        </div>
                    </div>
                    <a href="index.php" class="btn-secondary">
                        <i class="fas fa-arrow-left mr-2"></i> Back to Dashboard
                    </a>
                </div>
            </div>
        </div>

        <!-- Withdrawal Content -->
        <div class="p-6">
            <!-- Success/Error Messages -->
            <?php if ($success_message): ?>
                <div class="alert-success">
                    <i class="fas fa-check-circle"></i>
                    <span><?php echo htmlspecialchars($success_message); ?></span>
                </div>
            <?php endif; ?>
            
            <?php if ($error_message): ?>
                <div class="alert-error">
                    <i class="fas fa-exclamation-circle"></i>
                    <span><?php echo htmlspecialchars($error_message); ?></span>
                </div>
            <?php endif; ?>
            
            <!-- Withdrawal Limits Info -->
            <div class="alert-info mb-6">
                <i class="fas fa-info-circle"></i>
                <div class="flex-1">
                    <span class="font-medium">Withdrawal Limits:</span> 
                    Minimum: <span class="font-bold">$<?php echo number_format($site_settings['min_withdrawal_amount'] ?? 50, 2); ?></span> • 
                    Maximum: <span class="font-bold">$<?php echo number_format($site_settings['max_withdrawal_amount'] ?? 50000, 2); ?></span>
                    <?php if (isset($site_settings['withdrawal_fee_percent']) && floatval($site_settings['withdrawal_fee_percent']) > 0): ?>
                    • Fee: <span class="font-bold"><?php echo $site_settings['withdrawal_fee_percent']; ?>%</span>
                    <?php endif; ?>
                </div>
            </div>

            <?php if (!$has_withdrawal_pin && $has_upgrade_pin && $has_tax_pin): ?>
                <!-- No Withdrawal PIN Set Message -->
                <div class="danger-card p-8 text-center mb-6">
                    <i class="fas fa-exclamation-triangle text-4xl text-red-400 mb-4"></i>
                    <h3 class="text-xl font-bold mb-2">Withdrawal PIN Not Set</h3>
                    <p class="text-gray-300 mb-4">You need to set a withdrawal PIN before you can withdraw funds.</p>
                    <p class="text-sm text-gray-400">Please contact support to set your withdrawal PIN.</p>
                </div>
            <?php elseif (!$all_pins_verified && !empty($withdrawal_data)): ?>
                <!-- PIN Verification Process (Only shown after form submission) -->
                <div class="glass-card p-8 max-w-2xl mx-auto">
                    <!-- Withdrawal Summary -->
                    <div class="info-card p-6 mb-8">
                        <h4 class="text-lg font-bold mb-4 flex items-center">
                            <i class="fas fa-receipt mr-2"></i> Withdrawal Summary
                        </h4>
                        <div class="space-y-3">
                            <div class="flex justify-between">
                                <span class="text-gray-400">Amount:</span>
                                <span class="font-bold text-xl">$<?php echo number_format($withdrawal_data['amount'], 2); ?></span>
                            </div>
                            <div class="flex justify-between">
                                <span class="text-gray-400">Payment Method:</span>
                                <span class="font-medium"><?php echo htmlspecialchars($withdrawal_data['payment_method_name'] ?? 'Selected Method'); ?></span>
                            </div>
                            <?php if ($withdrawal_data['withdrawal_fee_amount'] > 0): ?>
                            <div class="flex justify-between">
                                <span class="text-gray-400">Withdrawal Fee:</span>
                                <span class="text-blue-400">-$<?php echo number_format($withdrawal_data['withdrawal_fee_amount'], 2); ?></span>
                            </div>
                            <?php endif; ?>
                            <?php if ($withdrawal_data['upgrade_fee_amount'] > 0): ?>
                            <div class="flex justify-between">
                                <span class="text-gray-400">Upgrade Fee:</span>
                                <span class="text-yellow-400">-$<?php echo number_format($withdrawal_data['upgrade_fee_amount'], 2); ?></span>
                            </div>
                            <?php endif; ?>
                            <?php if ($withdrawal_data['tax_fee_amount'] > 0): ?>
                            <div class="flex justify-between">
                                <span class="text-gray-400">Tax Fee:</span>
                                <span class="text-red-400">-$<?php echo number_format($withdrawal_data['tax_fee_amount'], 2); ?></span>
                            </div>
                            <?php endif; ?>
                            <div class="flex justify-between border-t border-gray-700/50 pt-3">
                                <span class="text-gray-400">Net Amount:</span>
                                <span class="font-bold text-green-400 text-xl">$<?php echo number_format($withdrawal_data['net_amount'], 2); ?></span>
                            </div>
                        </div>
                    </div>
                    
                    <!-- PIN Verification Steps -->
                    <div class="pin-steps-container">
                        <!-- Withdrawal PIN Step -->
                        <?php if ($has_withdrawal_pin): ?>
                        <div class="pin-step <?php echo $current_pin_step == 'withdrawal' ? 'active' : ($withdrawal_pin_verified ? 'completed' : ''); ?>">
                            <div class="pin-step-icon <?php echo $current_pin_step == 'withdrawal' ? 'active' : ($withdrawal_pin_verified ? 'completed' : 'pending'); ?>">
                                <i class="fas fa-key"></i>
                            </div>
                            <span class="pin-step-label">Withdrawal PIN</span>
                            <?php if ($withdrawal_pin_verified): ?>
                                <i class="fas fa-check text-green-400 text-xs absolute -top-1 -right-1"></i>
                            <?php endif; ?>
                        </div>
                        <?php endif; ?>
                        
                        <!-- Upgrade PIN Step -->
                        <?php if ($needs_upgrade_pin): ?>
                            <div class="pin-step <?php echo $current_pin_step == 'upgrade' ? 'active' : ($upgrade_pin_verified ? 'completed' : ''); ?>">
                                <div class="pin-step-icon <?php echo $current_pin_step == 'upgrade' ? 'active' : ($upgrade_pin_verified ? 'completed' : 'pending'); ?>">
                                    <i class="fas fa-level-up-alt"></i>
                                </div>
                                <span class="pin-step-label">Upgrade PIN</span>
                                <?php if ($upgrade_pin_verified): ?>
                                    <i class="fas fa-check text-green-400 text-xs absolute -top-1 -right-1"></i>
                                <?php endif; ?>
                            </div>
                        <?php endif; ?>
                        
                        <!-- Tax PIN Step -->
                        <?php if ($needs_tax_pin): ?>
                            <div class="pin-step <?php echo $current_pin_step == 'tax' ? 'active' : ($tax_pin_verified ? 'completed' : ''); ?>">
                                <div class="pin-step-icon <?php echo $current_pin_step == 'tax' ? 'active' : ($tax_pin_verified ? 'completed' : 'pending'); ?>">
                                    <i class="fas fa-percentage"></i>
                                </div>
                                <span class="pin-step-label">Tax PIN</span>
                                <?php if ($tax_pin_verified): ?>
                                    <i class="fas fa-check text-green-400 text-xs absolute -top-1 -right-1"></i>
                                <?php endif; ?>
                            </div>
                        <?php endif; ?>
                        
                        <!-- Complete Step -->
                        <div class="pin-step <?php echo $current_pin_step == 'complete' ? 'active' : ($all_pins_verified ? 'completed' : 'pending'); ?>">
                            <div class="pin-step-icon <?php echo $current_pin_step == 'complete' ? 'active' : ($all_pins_verified ? 'completed' : 'pending'); ?>">
                                <i class="fas fa-check-circle"></i>
                            </div>
                            <span class="pin-step-label">Complete</span>
                        </div>
                    </div>
                    
                    <!-- PIN Verification Forms -->
                    <div class="text-center mb-6">
                        <?php if ($current_pin_step == 'withdrawal'): ?>
                            <div class="w-16 h-16 bg-gradient-to-br from-blue-500/20 to-purple-500/20 rounded-full flex items-center justify-center mx-auto mb-4">
                                <i class="fas fa-lock text-2xl text-blue-400"></i>
                            </div>
                            <h3 class="text-2xl font-bold mb-2">Verify Withdrawal PIN</h3>
                            <p class="text-gray-400">Enter your 4 digit withdrawal PIN to continue</p>
                        <?php elseif ($current_pin_step == 'upgrade'): ?>
                            <div class="w-16 h-16 bg-gradient-to-br from-yellow-500/20 to-orange-500/20 rounded-full flex items-center justify-center mx-auto mb-4">
                                <i class="fas fa-level-up-alt text-2xl text-yellow-400"></i>
                            </div>
                            <h3 class="text-2xl font-bold mb-2">Verify Upgrade PIN</h3>
                            <p class="text-gray-400">Enter your upgrade PIN to proceed</p>
                        <?php elseif ($current_pin_step == 'tax'): ?>
                            <div class="w-16 h-16 bg-gradient-to-br from-red-500/20 to-pink-500/20 rounded-full flex items-center justify-center mx-auto mb-4">
                                <i class="fas fa-percentage text-2xl text-red-400"></i>
                            </div>
                            <h3 class="text-2xl font-bold mb-2">Verify Tax PIN</h3>
                            <p class="text-gray-400">Enter your tax PIN to proceed</p>
                        <?php endif; ?>
                    </div>
                    
                    <?php if ($pin_error): ?>
                        <div class="alert-error mb-6">
                            <i class="fas fa-exclamation-circle"></i>
                            <span><?php echo htmlspecialchars($pin_error); ?></span>
                        </div>
                    <?php endif; ?>
                    
                    <!-- Withdrawal PIN Form -->
                    <?php if ($current_pin_step == 'withdrawal'): ?>
                        <form method="POST" action="" id="withdrawalPinForm">
                            <div class="form-group">
                                <label class="form-label text-center block">Withdrawal PIN</label>
                                <div class="pin-input-container">
                                    <input type="password" name="withdrawal_pin_digit1" id="withdrawal_pin1" class="pin-input" maxlength="1" pattern="[0-9]" inputmode="numeric" autocomplete="off" required autofocus>
                                    <input type="password" name="withdrawal_pin_digit2" id="withdrawal_pin2" class="pin-input" maxlength="1" pattern="[0-9]" inputmode="numeric" autocomplete="off" required>
                                    <input type="password" name="withdrawal_pin_digit3" id="withdrawal_pin3" class="pin-input" maxlength="1" pattern="[0-9]" inputmode="numeric" autocomplete="off" required>
                                    <input type="password" name="withdrawal_pin_digit4" id="withdrawal_pin4" class="pin-input" maxlength="1" pattern="[0-9]" inputmode="numeric" autocomplete="off" required>
                                </div>
                                <input type="hidden" name="withdrawal_pin" id="full_withdrawal_pin">
                            </div>
                            
                            <div class="form-group">
                                <button type="submit" name="verify_withdrawal_pin" class="btn-primary w-full">
                                    <i class="fas fa-unlock-alt mr-2"></i> Verify Withdrawal PIN
                                </button>
                            </div>
                        </form>
                    <?php endif; ?>
                    
                    <!-- Upgrade PIN Form -->
                    <?php if ($current_pin_step == 'upgrade'): ?>
                        <form method="POST" action="" id="upgradePinForm">
                            <div class="form-group">
                                <label class="form-label text-center block">Upgrade PIN</label>
                                <div class="pin-input-container">
                                    <input type="password" name="upgrade_pin_digit1" id="upgrade_pin1" class="pin-input" maxlength="1" pattern="[0-9]" inputmode="numeric" autocomplete="off" required autofocus>
                                    <input type="password" name="upgrade_pin_digit2" id="upgrade_pin2" class="pin-input" maxlength="1" pattern="[0-9]" inputmode="numeric" autocomplete="off" required>
                                    <input type="password" name="upgrade_pin_digit3" id="upgrade_pin3" class="pin-input" maxlength="1" pattern="[0-9]" inputmode="numeric" autocomplete="off" required>
                                    <input type="password" name="upgrade_pin_digit4" id="upgrade_pin4" class="pin-input" maxlength="1" pattern="[0-9]" inputmode="numeric" autocomplete="off" required>
                                </div>
                                <input type="hidden" name="upgrade_pin" id="full_upgrade_pin">
                            </div>
                            
                            <div class="form-group">
                                <button type="submit" name="verify_upgrade_pin" class="btn-warning w-full">
                                    <i class="fas fa-lock-open mr-2"></i> Verify Upgrade PIN
                                </button>
                            </div>
                        </form>
                    <?php endif; ?>
                    
                    <!-- Tax PIN Form -->
                    <?php if ($current_pin_step == 'tax'): ?>
                        <form method="POST" action="" id="taxPinForm">
                            <div class="form-group">
                                <label class="form-label text-center block">Tax PIN</label>
                                <div class="pin-input-container">
                                    <input type="password" name="tax_pin_digit1" id="tax_pin1" class="pin-input" maxlength="1" pattern="[0-9]" inputmode="numeric" autocomplete="off" required autofocus>
                                    <input type="password" name="tax_pin_digit2" id="tax_pin2" class="pin-input" maxlength="1" pattern="[0-9]" inputmode="numeric" autocomplete="off" required>
                                    <input type="password" name="tax_pin_digit3" id="tax_pin3" class="pin-input" maxlength="1" pattern="[0-9]" inputmode="numeric" autocomplete="off" required>
                                    <input type="password" name="tax_pin_digit4" id="tax_pin4" class="pin-input" maxlength="1" pattern="[0-9]" inputmode="numeric" autocomplete="off" required>
                                </div>
                                <input type="hidden" name="tax_pin" id="full_tax_pin">
                            </div>
                            
                            <div class="form-group">
                                <button type="submit" name="verify_tax_pin" class="btn-danger w-full">
                                    <i class="fas fa-unlock mr-2"></i> Verify Tax PIN
                                </button>
                            </div>
                        </form>
                    <?php endif; ?>
                    
                    <!-- Verification Complete -->
                    <?php if ($current_pin_step == 'complete'): ?>
                        <div class="text-center">
                            <div class="w-16 h-16 bg-gradient-to-br from-green-500/20 to-emerald-500/20 rounded-full flex items-center justify-center mx-auto mb-4">
                                <i class="fas fa-check-circle text-2xl text-green-400"></i>
                            </div>
                            <h3 class="text-2xl font-bold mb-2">All PINs Verified!</h3>
                            <p class="text-gray-400 mb-6">Your withdrawal is being processed.</p>
                            
                            <div class="alert-success mb-6">
                                <i class="fas fa-spinner fa-spin"></i>
                                <span>Processing your withdrawal request...</span>
                            </div>
                            
                            <p class="text-sm text-gray-500 mb-6">You will be redirected in a few seconds.</p>
                            
                            <form method="POST" action="" id="processWithdrawalForm">
                                <button type="submit" name="process_withdrawal" class="btn-primary w-full">
                                    <i class="fas fa-paper-plane mr-2"></i> Process Withdrawal Now
                                </button>
                            </form>
                        </div>
                    <?php endif; ?>
                    
                    <div class="text-center mt-6 pt-6 border-t border-gray-700/50">
                        <p class="text-sm text-gray-400">
                            <i class="fas fa-shield-alt mr-1"></i>
                            PIN verification is required for security
                        </p>
                        <p class="text-xs text-gray-500 mt-1">
                            Verification expires in 5 minutes
                        </p>
                        <a href="withdraw.php?reset=1" class="text-sm text-blue-400 hover:text-blue-300 mt-2 inline-block">
                            <i class="fas fa-redo mr-1"></i> Cancel and start over
                        </a>
                    </div>
                </div>
            <?php else: ?>
                <!-- Withdrawal Form (Shows first) -->
                <div id="withdrawalFormSection">
                    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
                        <!-- Left Column: Withdrawal Form -->
                        <div class="lg:col-span-2">
                            <div class="glass-card p-6 mb-6 animate-fade-in">
                                <div class="flex items-center justify-between mb-6">
                                    <h3 class="text-xl font-bold flex items-center">
                                        <i class="fas fa-money-bill-wave mr-3 text-green-400"></i> Withdrawal Form
                                    </h3>
                                    <span class="text-sm <?php echo $has_withdrawal_pin ? 'text-yellow-400' : 'text-green-400'; ?> flex items-center">
                                        <?php if ($has_withdrawal_pin): ?>
                                            <i class="fas fa-key mr-1"></i> PIN Verification Required
                                        <?php else: ?>
                                            <i class="fas fa-check-circle mr-1"></i> No PINs Required
                                        <?php endif; ?>
                                    </span>
                                </div>
                                
                                <form method="POST" action="" id="withdrawalForm">
                                    <!-- Amount Input -->
                                    <div class="form-group">
                                        <label class="form-label">Withdrawal Amount (USD)</label>
                                        <div class="relative">
                                            <span class="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400">$</span>
                                            <input type="number" 
                                                   name="amount" 
                                                   id="amount"
                                                   class="form-input pl-8"
                                                   step="0.01"
                                                   min="<?php echo $site_settings['min_withdrawal_amount'] ?? 50; ?>"
                                                   max="<?php echo min($site_settings['max_withdrawal_amount'] ?? 50000, $account_balance); ?>"
                                                   placeholder="Enter amount"
                                                   required
                                                   value="<?php echo $site_settings['min_withdrawal_amount'] ?? 50; ?>"
                                                   oninput="updateWithdrawalAmountDisplay(this.value)">
                                        </div>
                                        <div class="flex justify-between text-xs text-gray-400 mt-2">
                                            <span>Min: $<?php echo number_format($site_settings['min_withdrawal_amount'] ?? 50, 2); ?></span>
                                            <span id="amountDisplay">$<?php echo number_format($site_settings['min_withdrawal_amount'] ?? 50, 2); ?></span>
                                            <span>Max: $<?php echo number_format(min($site_settings['max_withdrawal_amount'] ?? 50000, $account_balance), 2); ?></span>
                                        </div>
                                        <div class="progress-bar">
                                            <div id="amountProgress" class="progress-fill" style="width: 0%"></div>
                                        </div>
                                        <div class="mt-2 text-sm" id="feeDisplay"></div>
                                    </div>
                                    
                                    <!-- Payment Method Selection -->
                                    <div class="form-group">
                                        <label class="form-label mb-3">Select Payment Method</label>
                                        
                                        <!-- Crypto Methods -->
                                        <?php if (!empty($crypto_methods)): ?>
                                        <div class="mb-4">
                                            <h4 class="text-sm font-medium text-gray-300 mb-2 flex items-center">
                                                <i class="fab fa-bitcoin mr-2 text-yellow-400"></i> Cryptocurrency
                                            </h4>
                                            <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                                                <?php foreach ($crypto_methods as $method): ?>
                                                    <div class="payment-method-card" onclick="selectPaymentMethod(<?php echo $method['id']; ?>, 'crypto')">
                                                        <div class="flex items-center justify-between">
                                                            <div class="flex items-center">
                                                                <?php 
                                                                $icon_class = '';
                                                                $network_class = '';
                                                                if (stripos($method['wallet_name'], 'bitcoin') !== false) {
                                                                    $icon_class = 'fab fa-bitcoin text-yellow-400';
                                                                    $network_class = 'network-btc';
                                                                } elseif (stripos($method['wallet_name'], 'ethereum') !== false) {
                                                                    $icon_class = 'fab fa-ethereum text-purple-400';
                                                                    $network_class = 'network-eth';
                                                                } elseif (stripos($method['wallet_name'], 'tether') !== false) {
                                                                    $icon_class = 'fas fa-coins text-green-400';
                                                                    $network_class = 'network-usdt';
                                                                } else {
                                                                    $icon_class = 'fas fa-wallet text-blue-400';
                                                                }
                                                                ?>
                                                                <i class="<?php echo $icon_class; ?> text-xl mr-3"></i>
                                                                <div>
                                                                    <div class="font-medium"><?php echo htmlspecialchars($method['wallet_name']); ?></div>
                                                                    <div class="text-xs text-gray-400">Receive <?php echo htmlspecialchars($method['crypto_network']); ?> only</div>
                                                                </div>
                                                            </div>
                                                            <?php if ($method['is_default'] == 1): ?>
                                                                <span class="text-xs bg-blue-500/20 text-blue-400 px-2 py-1 rounded">Default</span>
                                                            <?php endif; ?>
                                                        </div>
                                                        <div class="<?php echo $network_class; ?> network-badge">
                                                            <?php echo htmlspecialchars($method['crypto_network']); ?>
                                                        </div>
                                                    </div>
                                                <?php endforeach; ?>
                                            </div>
                                        </div>
                                        <?php endif; ?>
                                        
                                        <!-- Bank Methods -->
                                        <?php if (!empty($bank_methods)): ?>
                                        <div>
                                            <h4 class="text-sm font-medium text-gray-300 mb-2 flex items-center">
                                                <i class="fas fa-university mr-2 text-blue-400"></i> Bank Transfer
                                            </h4>
                                            <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                                                <?php foreach ($bank_methods as $method): ?>
                                                    <div class="payment-method-card" onclick="selectPaymentMethod(<?php echo $method['id']; ?>, 'bank')">
                                                        <div class="flex items-center justify-between">
                                                            <div class="flex items-center">
                                                                <i class="fas fa-university text-xl text-blue-400 mr-3"></i>
                                                                <div>
                                                                    <div class="font-medium"><?php echo htmlspecialchars($method['bank_name']); ?></div>
                                                                    <div class="text-xs text-gray-400">Bank Transfer</div>
                                                                </div>
                                                            </div>
                                                            <?php if ($method['is_default'] == 1): ?>
                                                                <span class="text-xs bg-blue-500/20 text-blue-400 px-2 py-1 rounded">Default</span>
                                                            <?php endif; ?>
                                                        </div>
                                                    </div>
                                                <?php endforeach; ?>
                                            </div>
                                        </div>
                                        <?php endif; ?>
                                        
                                        <?php if (empty($payment_methods)): ?>
                                            <div class="text-center py-8 text-gray-400">
                                                <i class="fas fa-exclamation-triangle text-3xl mb-3"></i>
                                                <p>No payment methods available for withdrawal.</p>
                                                <p class="text-sm mt-2">Please contact support for assistance.</p>
                                            </div>
                                        <?php endif; ?>
                                        
                                        <input type="hidden" name="payment_method_id" id="payment_method_id" required>
                                        <div id="paymentMethodError" class="text-red-400 text-sm mt-2 hidden">
                                            <i class="fas fa-exclamation-circle mr-1"></i> Please select a payment method
                                        </div>
                                    </div>
                                    
                                    <!-- Payment Details (Dynamic based on selection) -->
                                    <div id="paymentDetails" class="hidden">
                                        <div class="border-t border-gray-700/50 pt-6 mt-6">
                                            <h4 class="text-lg font-bold mb-4">Payment Details</h4>
                                            
                                            <!-- Crypto Wallet Address Input -->
                                            <div id="cryptoWalletField" class="form-group hidden">
                                                <label class="form-label">Your Wallet Address</label>
                                                <input type="text" 
                                                       name="wallet_address" 
                                                       id="wallet_address"
                                                       class="form-input" 
                                                       placeholder="Enter your wallet address to receive funds">
                                                <p class="text-xs text-gray-400 mt-2">
                                                    <i class="fas fa-info-circle mr-1"></i>
                                                    Enter the wallet address where you want to receive the funds
                                                </p>
                                            </div>
                                            
                                            <!-- Bank Details Input -->
                                            <div id="bankDetailsField" class="form-group hidden">
                                                <label class="form-label">Your Bank Account Details</label>
                                                <textarea name="bank_details" 
                                                          id="bank_details"
                                                          class="form-input" 
                                                          rows="4"
                                                          placeholder="Enter your bank account details (Account Name, Account Number, Bank Name, etc.)"></textarea>
                                                <p class="text-xs text-gray-400 mt-2">
                                                    <i class="fas fa-info-circle mr-1"></i>
                                                    Include all necessary bank details for the transfer
                                                </p>
                                            </div>
                                            
                                            <!-- Summary -->
                                            <div class="bg-gray-800/30 rounded-lg p-4 mt-6">
                                                <h5 class="font-bold mb-3">Withdrawal Summary</h5>
                                                <div class="space-y-2 text-sm">
                                                    <div class="flex justify-between">
                                                        <span class="text-gray-400">Amount:</span>
                                                        <span id="summaryAmount" class="font-medium">$0.00</span>
                                                    </div>
                                                    <?php if (isset($site_settings['withdrawal_fee_percent']) && floatval($site_settings['withdrawal_fee_percent']) > 0): ?>
                                                    <div class="flex justify-between" id="withdrawalFeeSummaryRow">
                                                        <span class="text-gray-400">Withdrawal Fee (<?php echo $site_settings['withdrawal_fee_percent']; ?>%):</span>
                                                        <span id="summaryWithdrawalFee" class="text-blue-400">$0.00</span>
                                                    </div>
                                                    <?php endif; ?>
                                                    <?php if ($upgrade_fee > 0): ?>
                                                    <div class="flex justify-between">
                                                        <span class="text-gray-400">Upgrade Fee:</span>
                                                        <span id="summaryUpgradeFee" class="text-yellow-400">$<?php echo number_format($upgrade_fee, 2); ?></span>
                                                    </div>
                                                    <?php endif; ?>
                                                    <?php if ($tax_fee > 0): ?>
                                                    <div class="flex justify-between">
                                                        <span class="text-gray-400">Tax Fee:</span>
                                                        <span id="summaryTaxFee" class="text-red-400">$<?php echo number_format($tax_fee, 2); ?></span>
                                                    </div>
                                                    <?php endif; ?>
                                                    <div class="flex justify-between border-t border-gray-700/50 pt-2">
                                                        <span class="text-gray-400">Net Amount:</span>
                                                        <span id="summaryNet" class="font-bold text-green-400">$0.00</span>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <!-- PIN Status Notice -->
                                    <?php if ($has_withdrawal_pin || $has_upgrade_pin || $has_tax_pin): ?>
                                    <div class="alert-warning mt-6">
                                        <i class="fas fa-key"></i>
                                        <div>
                                            <p class="font-medium">PIN Verification Required</p>
                                            <p class="text-sm">
                                                <?php 
                                                $pin_count = 0;
                                                if ($has_withdrawal_pin) $pin_count++;
                                                if ($has_upgrade_pin && $upgrade_fee > 0) $pin_count++;
                                                if ($has_tax_pin && $tax_fee > 0) $pin_count++;
                                                echo "You will need to verify " . $pin_count . " PIN" . ($pin_count > 1 ? "s" : "") . " after submitting this form.";
                                                ?>
                                            </p>
                                        </div>
                                    </div>
                                    <?php endif; ?>
                                    
                                    <!-- Submit Button -->
                                    <div class="mt-8 pt-6 border-t border-gray-700/50">
                                        <button type="submit" name="submit_withdrawal" class="btn-danger w-full">
                                            <i class="fas fa-paper-plane mr-2"></i> 
                                            <?php if ($has_withdrawal_pin || $has_upgrade_pin || $has_tax_pin): ?>
                                                Submit & Verify PIN
                                            <?php else: ?>
                                                Submit Withdrawal Request
                                            <?php endif; ?>
                                        </button>
                                    </div>
                                </form>
                            </div>
                            
                            <!-- Recent Withdrawals -->
                            <div class="glass-card p-6 animate-fade-in" style="animation-delay: 0.1s">
                                <div class="flex items-center justify-between mb-6">
                                    <h3 class="text-xl font-bold flex items-center">
                                        <i class="fas fa-history mr-3 text-blue-400"></i> Recent Withdrawals
                                    </h3>
                                    <a href="statement.php?type=withdrawal" class="text-sm text-blue-400 hover:text-blue-300">
                                        View All <i class="fas fa-arrow-right ml-1"></i>
                                    </a>
                                </div>
                                
                                <?php if (!empty($recent_withdrawals)): ?>
                                    <div class="overflow-x-auto">
                                        <table class="w-full">
                                            <thead>
                                                <tr class="text-left text-sm text-gray-400 border-b border-gray-700/50">
                                                    <th class="pb-3">Date</th>
                                                    <th class="pb-3">Amount</th>
                                                    <th class="pb-3">Method</th>
                                                    <th class="pb-3">Status</th>
                                                    <th class="pb-3">TX ID</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach ($recent_withdrawals as $withdrawal): ?>
                                                    <tr class="border-b border-gray-700/30 hover:bg-gray-800/30">
                                                        <td class="py-3 text-sm"><?php echo date('M d, Y', strtotime($withdrawal['created_at'])); ?></td>
                                                        <td class="py-3 font-medium">$<?php echo number_format($withdrawal['amount'], 2); ?></td>
                                                        <td class="py-3 text-sm">
                                                            <?php 
                                                            if ($withdrawal['payment_type'] == 'crypto') {
                                                                echo htmlspecialchars($withdrawal['wallet_name'] ?? 'Crypto');
                                                            } else {
                                                                echo htmlspecialchars($withdrawal['bank_name'] ?? 'Bank');
                                                            }
                                                            ?>
                                                        </td>
                                                        <td class="py-3">
                                                            <?php
                                                            $status_class = 'status-pending';
                                                            $status_text = 'Pending';
                                                            if ($withdrawal['status'] == 'processing') {
                                                                $status_class = 'status-processing';
                                                                $status_text = 'Processing';
                                                            } elseif ($withdrawal['status'] == 'completed') {
                                                                $status_class = 'status-completed';
                                                                $status_text = 'Completed';
                                                            } elseif ($withdrawal['status'] == 'rejected') {
                                                                $status_class = 'status-rejected';
                                                                $status_text = 'Rejected';
                                                            }
                                                            ?>
                                                            <span class="status-badge <?php echo $status_class; ?>">
                                                                <?php echo $status_text; ?>
                                                            </span>
                                                        </td>
                                                        <td class="py-3 text-sm font-mono">
                                                            <?php echo substr($withdrawal['transaction_id'], 0, 8) . '...'; ?>
                                                        </td>
                                                    </tr>
                                                <?php endforeach; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                <?php else: ?>
                                    <div class="text-center py-8 text-gray-400">
                                        <i class="fas fa-wallet text-3xl mb-3"></i>
                                        <p>No recent withdrawals found.</p>
                                        <p class="text-sm mt-2">Your withdrawal history will appear here.</p>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                        
                        <!-- Right Column: Information & Stats -->
                        <div>
                            <!-- Account Balance Card -->
                            <div class="danger-card p-6 mb-6 animate-fade-in" style="animation-delay: 0.2s">
                                <div class="flex items-start justify-between mb-6">
                                    <div>
                                        <p class="text-gray-400 text-sm mb-1">Available Balance</p>
                                        <h3 class="text-3xl font-bold">$<?php echo number_format($account_balance, 2); ?></h3>
                                    </div>
                                    <div class="w-14 h-14 bg-gradient-to-br from-red-500/20 to-pink-500/20 rounded-xl flex items-center justify-center">
                                        <i class="fas fa-wallet text-2xl text-red-400"></i>
                                    </div>
                                </div>
                                <div class="space-y-3">
                                    <div class="flex justify-between items-center">
                                        <span class="text-gray-400">Total Withdrawals</span>
                                        <span class="font-semibold text-green-400">$<?php echo number_format($total_withdrawals, 2); ?></span>
                                    </div>
                                    <div class="flex justify-between items-center">
                                        <span class="text-gray-400">Last Withdrawal</span>
                                        <span class="font-semibold"><?php echo $last_withdrawal_date; ?></span>
                                    </div>
                                    <?php if ($upgrade_fee > 0): ?>
                                    <div class="flex justify-between items-center">
                                        <span class="text-gray-400">Upgrade Fee</span>
                                        <span class="font-semibold text-yellow-400">$<?php echo number_format($upgrade_fee, 2); ?></span>
                                    </div>
                                    <?php endif; ?>
                                    <?php if ($tax_fee > 0): ?>
                                    <div class="flex justify-between items-center">
                                        <span class="text-gray-400">Tax Fee</span>
                                        <span class="font-semibold text-red-400">$<?php echo number_format($tax_fee, 2); ?></span>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                            
                            <!-- PIN Status Card -->
                            <div class="glass-card p-6 mb-6 animate-fade-in" style="animation-delay: 0.3s">
                                <h3 class="text-xl font-bold mb-4 flex items-center">
                                    <i class="fas fa-key mr-3 text-purple-400"></i> PIN Status
                                </h3>
                                <div class="space-y-4">
                                    <!-- Withdrawal PIN Status -->
                                    <div class="flex items-center justify-between">
                                        <div class="flex items-center">
                                            <div class="w-10 h-10 bg-blue-500/20 rounded-lg flex items-center justify-center mr-3">
                                                <i class="fas fa-key text-blue-400"></i>
                                            </div>
                                            <div>
                                                <p class="font-medium">Withdrawal PIN</p>
                                                <p class="text-xs text-gray-400">Required for all withdrawals</p>
                                            </div>
                                        </div>
                                        <span class="px-3 py-1 rounded-full text-xs font-medium <?php echo $user['withdrawal_pin_status'] == 'Set' ? 'bg-green-500/20 text-green-400' : 'bg-red-500/20 text-red-400'; ?>">
                                            <?php echo $user['withdrawal_pin_status']; ?>
                                        </span>
                                    </div>
                                    
                                    <!-- Upgrade PIN Status -->
                                    <div class="flex items-center justify-between">
                                        <div class="flex items-center">
                                            <div class="w-10 h-10 bg-yellow-500/20 rounded-lg flex items-center justify-center mr-3">
                                                <i class="fas fa-level-up-alt text-yellow-400"></i>
                                            </div>
                                            <div>
                                                <p class="font-medium">Upgrade PIN</p>
                                                <p class="text-xs text-gray-400">Fee: $<?php echo number_format($upgrade_fee, 2); ?></p>
                                            </div>
                                        </div>
                                        <span class="px-3 py-1 rounded-full text-xs font-medium <?php echo $user['upgrade_pin_status'] == 'Set' ? 'bg-green-500/20 text-green-400' : 'bg-gray-500/20 text-gray-400'; ?>">
                                            <?php echo $user['upgrade_pin_status']; ?>
                                        </span>
                                    </div>
                                    
                                    <!-- Tax PIN Status -->
                                    <div class="flex items-center justify-between">
                                        <div class="flex items-center">
                                            <div class="w-10 h-10 bg-red-500/20 rounded-lg flex items-center justify-center mr-3">
                                                <i class="fas fa-percentage text-red-400"></i>
                                            </div>
                                            <div>
                                                <p class="font-medium">Tax PIN</p>
                                                <p class="text-xs text-gray-400">Fee: $<?php echo number_format($tax_fee, 2); ?></p>
                                            </div>
                                        </div>
                                        <span class="px-3 py-1 rounded-full text-xs font-medium <?php echo $user['tax_pin_status'] == 'Set' ? 'bg-green-500/20 text-green-400' : 'bg-gray-500/20 text-gray-400'; ?>">
                                            <?php echo $user['tax_pin_status']; ?>
                                        </span>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Withdrawal Instructions -->
                            <div class="glass-card p-6 mb-6 animate-fade-in" style="animation-delay: 0.4s">
                                <h3 class="text-xl font-bold mb-4 flex items-center">
                                    <i class="fas fa-info-circle mr-3 text-yellow-400"></i> Important Notes
                                </h3>
                                <div class="space-y-3">
                                    <div class="flex items-start gap-3">
                                        <i class="fas fa-clock text-blue-400 mt-1"></i>
                                        <div>
                                            <p class="font-medium text-sm">Processing Time</p>
                                            <p class="text-xs text-gray-400">Crypto: 1-24 hours • Bank: 1-5 business days</p>
                                        </div>
                                    </div>
                                    <div class="flex items-start gap-3">
                                        <i class="fas fa-exclamation-triangle text-yellow-400 mt-1"></i>
                                        <div>
                                            <p class="font-medium text-sm">Minimum Withdrawal</p>
                                            <p class="text-xs text-gray-400">Minimum withdrawal amount is $<?php echo number_format($site_settings['min_withdrawal_amount'] ?? 50, 2); ?></p>
                                        </div>
                                    </div>
                                    <div class="flex items-start gap-3">
                                        <i class="fas fa-shield-alt text-green-400 mt-1"></i>
                                        <div>
                                            <p class="font-medium text-sm">Secure Transactions</p>
                                            <p class="text-xs text-gray-400">All transactions are encrypted and secure</p>
                                        </div>
                                    </div>
                                    <div class="flex items-start gap-3">
                                        <i class="fas fa-headset text-purple-400 mt-1"></i>
                                        <div>
                                            <p class="font-medium text-sm">Need Help?</p>
                                            <p class="text-xs text-gray-400">Contact support if you have any issues</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Quick Withdrawal Amounts -->
                            <div class="glass-card p-6 animate-fade-in" style="animation-delay: 0.5s">
                                <h3 class="text-xl font-bold mb-4 flex items-center">
                                    <i class="fas fa-bolt mr-3 text-purple-400"></i> Quick Amounts
                                </h3>
                                <div class="grid grid-cols-2 gap-3">
                                    <button type="button" onclick="setWithdrawalAmount(<?php echo $site_settings['min_withdrawal_amount'] ?? 50; ?>)" class="btn-secondary py-3">
                                        $<?php echo number_format($site_settings['min_withdrawal_amount'] ?? 50, 0); ?>
                                    </button>
                                    <button type="button" onclick="setWithdrawalAmount(100)" class="btn-secondary py-3">
                                        $100
                                    </button>
                                    <button type="button" onclick="setWithdrawalAmount(500)" class="btn-secondary py-3">
                                        $500
                                    </button>
                                    <button type="button" onclick="setWithdrawalAmount(1000)" class="btn-secondary py-3">
                                        $1,000
                                    </button>
                                    <button type="button" onclick="setWithdrawalAmount(5000)" class="btn-secondary py-3">
                                        $5,000
                                    </button>
                                    <button type="button" onclick="setWithdrawalAmount(10000)" class="btn-secondary py-3">
                                        $10,000
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endif; ?>
            
            <!-- Footer -->
            <div class="mt-8 text-center">
                <p class="text-gray-500 text-sm">
                    Need assistance with your withdrawal? 
                    <a href="support.php" class="text-blue-400 hover:text-blue-300">Contact Support</a>
                </p>
                <p class="text-gray-600 text-xs mt-2">
                    All withdrawals are subject to verification. Processing times may vary.
                </p>
            </div>
        </div>
    </div>

    <!-- JavaScript -->
    <script>
        // Mobile menu toggle functionality
        const menuToggle = document.getElementById('menuToggle');
        const closeSidebar = document.getElementById('closeSidebar');
        const sidebar = document.getElementById('sidebar');
        const sidebarOverlay = document.getElementById('sidebarOverlay');
        const body = document.body;

        // Function to toggle sidebar
        function toggleSidebar() {
            sidebar.classList.toggle('active');
            sidebarOverlay.classList.toggle('active');
            
            if (sidebar.classList.contains('active')) {
                body.classList.add('sidebar-open');
                body.style.overflow = 'hidden';
            } else {
                body.classList.remove('sidebar-open');
                body.style.overflow = '';
            }
        }

        // Function to close sidebar
        function closeSidebarFunc() {
            sidebar.classList.remove('active');
            sidebarOverlay.classList.remove('active');
            body.classList.remove('sidebar-open');
            body.style.overflow = '';
        }

        // Event listeners for mobile menu
        if (menuToggle) menuToggle.addEventListener('click', toggleSidebar);
        if (closeSidebar) closeSidebar.addEventListener('click', closeSidebarFunc);
        if (sidebarOverlay) sidebarOverlay.addEventListener('click', closeSidebarFunc);

        // Handle window resize
        window.addEventListener('resize', function() {
            if (window.innerWidth >= 1024) {
                sidebar.classList.add('active');
                sidebarOverlay.classList.remove('active');
                body.classList.remove('sidebar-open');
                body.style.overflow = '';
            } else {
                if (!sidebar.classList.contains('active')) {
                    sidebar.classList.remove('active');
                    sidebarOverlay.classList.remove('active');
                    body.classList.remove('sidebar-open');
                    body.style.overflow = '';
                }
            }
        });

        // Initialize sidebar state on load
        document.addEventListener('DOMContentLoaded', function() {
            if (window.innerWidth >= 1024) {
                sidebar.classList.add('active');
            }
            
            // Set active nav item
            document.querySelectorAll('.nav-item').forEach(nav => {
                const href = nav.getAttribute('href');
                if (href && href.includes('withdraw.php')) {
                    nav.classList.add('active');
                } else {
                    nav.classList.remove('active');
                }
            });
            
            // Initialize PIN inputs
            initializePinInput('withdrawal');
            initializePinInput('upgrade');
            initializePinInput('tax');
            
            // Initialize withdrawal amount display if on withdrawal form
            <?php if (empty($withdrawal_data)): ?>
                updateWithdrawalAmountDisplay(document.getElementById('amount').value);
                <?php if ($default_crypto): ?>
                    setTimeout(() => {
                        selectPaymentMethod(<?php echo $default_crypto['id']; ?>, 'crypto');
                    }, 100);
                <?php elseif ($default_bank): ?>
                    setTimeout(() => {
                        selectPaymentMethod(<?php echo $default_bank['id']; ?>, 'bank');
                    }, 100);
                <?php endif; ?>
            <?php endif; ?>
        });

        // Escape key closes sidebar
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape' && sidebar.classList.contains('active')) {
                closeSidebarFunc();
            }
        });

        // PIN Input functionality
        function initializePinInput(pinType) {
            const pinInputs = document.querySelectorAll(`#${pinType}PinForm .pin-input`);
            const fullPinInput = document.getElementById(`full_${pinType}_pin`);
            
            if (!pinInputs.length || !fullPinInput) return;
            
            pinInputs.forEach((input, index) => {
                input.addEventListener('input', function(e) {
                    // Only allow numbers
                    this.value = this.value.replace(/[^0-9]/g, '');
                    
                    // Move to next input if current is filled
                    if (this.value.length === 1) {
                        if (index < pinInputs.length - 1) {
                            pinInputs[index + 1].focus();
                        }
                    }
                    
                    // Update hidden full PIN field
                    updateFullPin(pinType);
                });
                
                input.addEventListener('keydown', function(e) {
                    // Handle backspace
                    if (e.key === 'Backspace' && this.value === '') {
                        if (index > 0) {
                            pinInputs[index - 1].focus();
                            pinInputs[index - 1].value = '';
                            updateFullPin(pinType);
                        }
                    }
                });
                
                input.addEventListener('paste', function(e) {
                    e.preventDefault();
                    const pastedData = e.clipboardData.getData('text');
                    const numbers = pastedData.replace(/[^0-9]/g, '');
                    
                    // Fill inputs with pasted numbers
                    for (let i = 0; i < Math.min(numbers.length, pinInputs.length); i++) {
                        pinInputs[i].value = numbers[i];
                    }
                    
                    updateFullPin(pinType);
                    
                    // Focus last filled input
                    const lastIndex = Math.min(numbers.length - 1, pinInputs.length - 1);
                    pinInputs[lastIndex].focus();
                });
            });
            
            function updateFullPin(type) {
                let pin = '';
                const inputs = document.querySelectorAll(`#${type}PinForm .pin-input`);
                inputs.forEach(input => {
                    pin += input.value;
                });
                document.getElementById(`full_${type}_pin`).value = pin;
            }
        }

        // Withdrawal amount functionality
        function setWithdrawalAmount(amount) {
            const amountInput = document.getElementById('amount');
            const maxWithdrawal = parseFloat(<?php echo min($site_settings['max_withdrawal_amount'] ?? 50000, $account_balance); ?>);
            
            if (amount > maxWithdrawal) {
                amount = maxWithdrawal;
                showNotification('Amount set to maximum available', 'warning');
            }
            
            amountInput.value = amount;
            updateWithdrawalAmountDisplay(amount);
        }
        
        function updateWithdrawalAmountDisplay(value) {
            const amount = parseFloat(value) || 0;
            const min = parseFloat(<?php echo $site_settings['min_withdrawal_amount'] ?? 50; ?>);
            const max = parseFloat(<?php echo min($site_settings['max_withdrawal_amount'] ?? 50000, $account_balance); ?>);
            const withdrawalFeePercent = parseFloat(<?php echo $site_settings['withdrawal_fee_percent'] ?? 0; ?>);
            const upgradeFee = parseFloat(<?php echo $upgrade_fee; ?>);
            const taxFee = parseFloat(<?php echo $tax_fee; ?>);
            
            // Calculate fees
            const withdrawalFeeAmount = (amount * withdrawalFeePercent) / 100;
            const totalFees = withdrawalFeeAmount + upgradeFee + taxFee;
            const netAmount = amount - totalFees;
            
            // Update display
            document.getElementById('amountDisplay').textContent = '$' + amount.toLocaleString('en-US', {
                minimumFractionDigits: 2,
                maximumFractionDigits: 2
            });
            
            // Update progress bar
            const progress = Math.min(100, (amount / max) * 100);
            document.getElementById('amountProgress').style.width = progress + '%';
            
            // Color coding
            if (amount < min) {
                document.getElementById('amountProgress').style.background = '#f56565';
                document.getElementById('amountDisplay').classList.add('text-red-400');
                document.getElementById('amountDisplay').classList.remove('text-green-400');
            } else if (amount > max) {
                document.getElementById('amountProgress').style.background = '#f56565';
                document.getElementById('amountDisplay').classList.add('text-red-400');
                document.getElementById('amountDisplay').classList.remove('text-green-400');
            } else {
                document.getElementById('amountProgress').style.background = 'linear-gradient(90deg, #667eea, #764ba2)';
                document.getElementById('amountDisplay').classList.remove('text-red-400');
                document.getElementById('amountDisplay').classList.add('text-green-400');
            }
            
            // Update fee display
            let feeHtml = '';
            
            if (withdrawalFeePercent > 0) {
                feeHtml += `
                    <div class="flex justify-between text-sm">
                        <span class="text-gray-400">Withdrawal Fee (${withdrawalFeePercent}%):</span>
                        <span class="text-blue-400">-$${withdrawalFeeAmount.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})}</span>
                    </div>
                `;
            }
            
            if (upgradeFee > 0) {
                feeHtml += `
                    <div class="flex justify-between text-sm">
                        <span class="text-gray-400">Upgrade Fee:</span>
                        <span class="text-yellow-400">-$${upgradeFee.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})}</span>
                    </div>
                `;
            }
            
            if (taxFee > 0) {
                feeHtml += `
                    <div class="flex justify-between text-sm">
                        <span class="text-gray-400">Tax Fee:</span>
                        <span class="text-red-400">-$${taxFee.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})}</span>
                    </div>
                `;
            }
            
            if (feeHtml) {
                feeHtml += `
                    <div class="flex justify-between text-sm mt-1 border-t border-gray-700/50 pt-2">
                        <span class="text-gray-400">Net Amount:</span>
                        <span class="text-green-400 font-bold">$${netAmount.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})}</span>
                    </div>
                `;
                document.getElementById('feeDisplay').innerHTML = feeHtml;
            } else {
                document.getElementById('feeDisplay').innerHTML = `
                    <div class="text-sm text-gray-400">No fees applied</div>
                `;
            }
            
            // Update summary
            document.getElementById('summaryAmount').textContent = '$' + amount.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2});
            
            if (withdrawalFeePercent > 0) {
                document.getElementById('summaryWithdrawalFee').textContent = '-$' + withdrawalFeeAmount.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2});
                document.getElementById('withdrawalFeeSummaryRow').classList.remove('hidden');
            }
            
            if (upgradeFee > 0) {
                document.getElementById('summaryUpgradeFee').textContent = '-$' + upgradeFee.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2});
            }
            
            if (taxFee > 0) {
                document.getElementById('summaryTaxFee').textContent = '-$' + taxFee.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2});
            }
            
            document.getElementById('summaryNet').textContent = '$' + netAmount.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2});
        }
        
        let selectedMethodId = null;
        let selectedMethodType = null;
        
        function selectPaymentMethod(methodId, methodType) {
            // Remove selection from all cards
            document.querySelectorAll('.payment-method-card').forEach(card => {
                card.classList.remove('selected');
            });
            
            // Add selection to clicked card
            event.currentTarget.classList.add('selected');
            
            // Set hidden input value
            document.getElementById('payment_method_id').value = methodId;
            selectedMethodId = methodId;
            selectedMethodType = methodType;
            
            // Hide error if shown
            document.getElementById('paymentMethodError').classList.add('hidden');
            
            // Show payment details
            showPaymentDetails(methodType);
        }
        
        function showPaymentDetails(methodType) {
            const paymentDetails = document.getElementById('paymentDetails');
            const cryptoWalletField = document.getElementById('cryptoWalletField');
            const bankDetailsField = document.getElementById('bankDetailsField');
            
            // Show payment details section
            paymentDetails.classList.remove('hidden');
            
            // Hide all fields first
            cryptoWalletField.classList.add('hidden');
            bankDetailsField.classList.add('hidden');
            
            // Show appropriate field
            if (methodType === 'crypto') {
                cryptoWalletField.classList.remove('hidden');
                document.getElementById('wallet_address').focus();
            } else if (methodType === 'bank') {
                bankDetailsField.classList.remove('hidden');
                document.getElementById('bank_details').focus();
            }
            
            // Update summary
            updateWithdrawalAmountDisplay(document.getElementById('amount').value);
        }
        
        // Form validation
        const withdrawalForm = document.getElementById('withdrawalForm');
        if (withdrawalForm) {
            withdrawalForm.addEventListener('submit', function(e) {
                const amount = parseFloat(document.getElementById('amount').value) || 0;
                const min = parseFloat(<?php echo $site_settings['min_withdrawal_amount'] ?? 50; ?>);
                const max = parseFloat(<?php echo min($site_settings['max_withdrawal_amount'] ?? 50000, $account_balance); ?>);
                const balance = parseFloat(<?php echo $account_balance; ?>);
                const methodId = document.getElementById('payment_method_id').value;
                const methodType = selectedMethodType;
                
                let hasError = false;
                
                // Validate amount
                if (amount < min) {
                    showFieldError('amount', `Minimum withdrawal is $${min}`);
                    hasError = true;
                } else if (amount > max) {
                    showFieldError('amount', `Maximum withdrawal is $${max}`);
                    hasError = true;
                } else if (amount > balance) {
                    showFieldError('amount', `Insufficient balance. Available: $${balance.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})}`);
                    hasError = true;
                }
                
                // Validate payment method
                if (!methodId) {
                    document.getElementById('paymentMethodError').classList.remove('hidden');
                    hasError = true;
                }
                
                // Validate wallet address for crypto
                if (methodType === 'crypto') {
                    const walletAddress = document.getElementById('wallet_address').value.trim();
                    if (!walletAddress) {
                        showFieldError('wallet_address', 'Please enter your wallet address');
                        hasError = true;
                    } else if (walletAddress.length < 20) {
                        showFieldError('wallet_address', 'Please enter a valid wallet address');
                        hasError = true;
                    }
                }
                
                // Validate bank details for bank transfer
                if (methodType === 'bank') {
                    const bankDetails = document.getElementById('bank_details').value.trim();
                    if (!bankDetails) {
                        showFieldError('bank_details', 'Please enter your bank account details');
                        hasError = true;
                    } else if (bankDetails.length < 10) {
                        showFieldError('bank_details', 'Please enter complete bank details');
                        hasError = true;
                    }
                }
                
                if (hasError) {
                    e.preventDefault();
                    showNotification('Please fix the errors above', 'error');
                    document.querySelector('.alert-error')?.scrollIntoView({ behavior: 'smooth', block: 'center' });
                } else {
                    // Confirm withdrawal
                    const withdrawalFeePercent = parseFloat(<?php echo $site_settings['withdrawal_fee_percent'] ?? 0; ?>);
                    const upgradeFee = parseFloat(<?php echo $upgrade_fee; ?>);
                    const taxFee = parseFloat(<?php echo $tax_fee; ?>);
                    
                    const withdrawalFeeAmount = (amount * withdrawalFeePercent) / 100;
                    const totalFees = withdrawalFeeAmount + upgradeFee + taxFee;
                    const netAmount = amount - totalFees;
                    
                    let confirmationMessage = `Are you sure you want to withdraw $${amount.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})}?\n`;
                    
                    if (totalFees > 0) {
                        confirmationMessage += `\nFees:\n`;
                        if (withdrawalFeeAmount > 0) {
                            confirmationMessage += `- Withdrawal Fee: $${withdrawalFeeAmount.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})}\n`;
                        }
                        if (upgradeFee > 0) {
                            confirmationMessage += `- Upgrade Fee: $${upgradeFee.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})}\n`;
                        }
                        if (taxFee > 0) {
                            confirmationMessage += `- Tax Fee: $${taxFee.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})}\n`;
                        }
                        confirmationMessage += `\nNet Amount: $${netAmount.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})}\n`;
                    }
                    
                    <?php if ($has_withdrawal_pin || $has_upgrade_pin || $has_tax_pin): ?>
                    confirmationMessage += `\nYou will need to verify your PIN(s) after submission.`;
                    <?php endif; ?>
                    
                    confirmationMessage += `\nThis action cannot be undone.`;
                    
                    const confirmation = confirm(confirmationMessage);
                    if (!confirmation) {
                        e.preventDefault();
                    }
                }
            });
        }
        
        // PIN form validation
        const pinForms = ['withdrawalPinForm', 'upgradePinForm', 'taxPinForm'];
        pinForms.forEach(formId => {
            const pinForm = document.getElementById(formId);
            if (pinForm) {
                pinForm.addEventListener('submit', function(e) {
                    const pinType = formId.replace('PinForm', '');
                    const pin = document.getElementById(`full_${pinType}_pin`).value;
                    
                    if (pin.length < 4) {
                        e.preventDefault();
                        showNotification('PIN must be at least 4 digits', 'error');
                        document.querySelectorAll(`#${formId} .pin-input`).forEach(input => {
                            input.classList.add('shake');
                            setTimeout(() => input.classList.remove('shake'), 500);
                        });
                    }
                });
            }
        });
        
        function showFieldError(fieldId, message) {
            const field = document.getElementById(fieldId);
            if (!field) return;
            
            const errorDiv = document.createElement('div');
            errorDiv.className = 'error-message text-red-400 text-sm mt-1 flex items-center gap-1';
            errorDiv.innerHTML = `<i class="fas fa-exclamation-circle"></i> ${message}`;
            
            const existingError = field.parentNode.querySelector('.error-message');
            if (existingError) existingError.remove();
            
            field.parentNode.appendChild(errorDiv);
            field.classList.add('border-red-500');
            
            field.addEventListener('input', function() {
                errorDiv.remove();
                this.classList.remove('border-red-500');
            }, { once: true });
        }
        
        function showNotification(message, type = 'info') {
            const notification = document.createElement('div');
            notification.className = `fixed top-6 right-6 px-4 py-3 rounded-xl shadow-xl z-50 ${
                type === 'success' ? 'bg-green-600' : 
                type === 'error' ? 'bg-red-600' : 
                type === 'warning' ? 'bg-yellow-600' : 'bg-blue-600'
            } text-white`;
            notification.innerHTML = `
                <div class="flex items-center gap-3">
                    <i class="fas fa-${type === 'success' ? 'check-circle' : type === 'error' ? 'exclamation-circle' : type === 'warning' ? 'exclamation-triangle' : 'info-circle'}"></i>
                    <span>${message}</span>
                </div>
            `;
            
            document.body.appendChild(notification);
            
            setTimeout(() => {
                notification.style.opacity = '0';
                notification.style.transform = 'translateX(100%)';
                setTimeout(() => notification.remove(), 300);
            }, 3000);
        }
        
        // Auto-submit when complete step is reached
        <?php if ($current_pin_step == 'complete'): ?>
        document.addEventListener('DOMContentLoaded', function() {
            setTimeout(() => {
                const processForm = document.getElementById('processWithdrawalForm');
                if (processForm) {
                    processForm.submit();
                }
            }, 2000);
        });
        <?php endif; ?>
    </script>
</body>
</html>