<?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 * 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();
}

// Check and create deposits table if it doesn't exist
$check_table = $conn->query("SHOW TABLES LIKE 'deposits'");
if ($check_table->num_rows === 0) {
    // Create deposits table
    $create_table_sql = "
        CREATE TABLE IF NOT EXISTS deposits (
            id INT PRIMARY KEY AUTO_INCREMENT,
            user_id INT NOT NULL,
            transaction_id VARCHAR(50) UNIQUE NOT NULL,
            amount DECIMAL(15,2) NOT NULL,
            payment_method_id INT NOT NULL,
            payment_type ENUM('crypto', 'bank') NOT NULL,
            transaction_hash VARCHAR(255),
            payment_proof VARCHAR(500),
            status ENUM('pending', 'completed', 'rejected') DEFAULT 'pending',
            admin_notes TEXT,
            verified_by INT,
            verified_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)) {
        error_log("Failed to create deposits table: " . $conn->error);
    }
}

// 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['enable_crypto_payments'] = '1';
    $site_settings['enable_bank_payments'] = '1';
    $site_settings['min_deposit_amount'] = '100';
    $site_settings['max_deposit_amount'] = '100000';
    $site_settings['deposit_instruction'] = 'Send exact amount to the wallet address below.';
}

// Fetch payment methods
$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';
});

// Handle deposit form submission
$success_message = '';
$error_message = '';
$selected_method = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_deposit'])) {
    $amount = floatval($_POST['amount'] ?? 0);
    $payment_method_id = intval($_POST['payment_method_id'] ?? 0);
    $transaction_hash = trim($_POST['transaction_hash'] ?? '');
    $payment_proof = $_FILES['payment_proof'] ?? null;
    
    // Validation
    $min_deposit = floatval($site_settings['min_deposit_amount'] ?? 100);
    $max_deposit = floatval($site_settings['max_deposit_amount'] ?? 100000);
    
    if ($amount < $min_deposit) {
        $error_message = "Minimum deposit amount is $" . number_format($min_deposit, 2);
    } elseif ($amount > $max_deposit) {
        $error_message = "Maximum deposit amount is $" . number_format($max_deposit, 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();
            
            // Handle file upload for payment proof
            $payment_proof_path = null;
            if ($payment_proof && $payment_proof['error'] === UPLOAD_ERR_OK) {
                $allowed_types = ['image/jpeg', 'image/png', 'image/jpg', 'application/pdf'];
                $max_size = 5 * 1024 * 1024; // 5MB
                
                if (!in_array($payment_proof['type'], $allowed_types)) {
                    $error_message = "Only JPG, PNG, and PDF files are allowed";
                } elseif ($payment_proof['size'] > $max_size) {
                    $error_message = "File size must be less than 5MB";
                } else {
                    $upload_dir = '../uploads/deposits/';
                    if (!file_exists($upload_dir)) {
                        mkdir($upload_dir, 0777, true);
                    }
                    
                    $file_extension = pathinfo($payment_proof['name'], PATHINFO_EXTENSION);
                    $filename = 'deposit_' . $user_id . '_' . time() . '.' . $file_extension;
                    $target_path = $upload_dir . $filename;
                    
                    if (move_uploaded_file($payment_proof['tmp_name'], $target_path)) {
                        $payment_proof_path = 'uploads/deposits/' . $filename;
                    } else {
                        $error_message = "Failed to upload payment proof";
                    }
                }
            }
            
            if (!$error_message) {
                // Generate unique transaction ID
                $transaction_id = 'DEP' . strtoupper(uniqid());
                
                // Insert deposit record
                $deposit_stmt = $conn->prepare("
                    INSERT INTO deposits 
                    (user_id, transaction_id, amount, payment_method_id, payment_type, 
                     transaction_hash, payment_proof, status, created_at, updated_at) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', NOW(), NOW())
                ");
                
                if ($deposit_stmt) {
                    // FIXED: Changed type string from "isdiss" to "isdisss" to match 7 parameters
                    $deposit_stmt->bind_param(
                        "isdisss",  // i=user_id, s=transaction_id, d=amount, i=payment_method_id, s=payment_type, s=transaction_hash, s=payment_proof_path
                        $user_id, 
                        $transaction_id, 
                        $amount, 
                        $payment_method_id,
                        $selected_method['payment_type'],
                        $transaction_hash,
                        $payment_proof_path
                    );
                    
                    if ($deposit_stmt->execute()) {
                        // Update user's total deposits and last deposit
                        $update_stmt = $conn->prepare("
                            UPDATE users SET 
                            total_deposits = total_deposits + ?, 
                            last_deposit = NOW(),
                            updated_at = NOW()
                            WHERE id = ?
                        ");
                        if ($update_stmt) {
                            $update_stmt->bind_param("di", $amount, $user_id);
                            $update_stmt->execute();
                            $update_stmt->close();
                        }
                        
                        $success_message = "Deposit request submitted successfully! Transaction ID: " . $transaction_id . ". Please wait for confirmation.";
                        
                        // Clear form
                        unset($_POST);
                        $_POST = array();
                    } else {
                        $error_message = "Failed to submit deposit request: " . $conn->error;
                    }
                    $deposit_stmt->close();
                } else {
                    $error_message = "Database error: Could not prepare deposit statement";
                }
            }
        }
    }
}

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

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

// Format dates
$last_deposit_date = $last_deposit ? date('M d, Y h:i A', strtotime($last_deposit)) : 'No deposits 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>Make Deposit - <?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%);
            --success-gradient: linear-gradient(135deg, #10b981 0%, #059669 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);
        }
        
        .gradient-card {
            background: linear-gradient(135deg, rgba(102, 126, 234, 0.15) 0%, rgba(118, 75, 162, 0.15) 100%);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(102, 126, 234, 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-success {
            background: var(--success-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-success:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px -5px rgba(16, 185, 129, 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;
        }
        
        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(-10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        /* 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);
        }
        
        /* Wallet Address Display */
        .wallet-address {
            background: rgba(0, 0, 0, 0.2);
            border: 1px solid rgba(255, 255, 255, 0.1);
            border-radius: 0.75rem;
            padding: 0.75rem 1rem;
            font-family: monospace;
            font-size: 0.9rem;
            word-break: break-all;
            position: relative;
        }
        
        .copy-btn {
            position: absolute;
            right: 0.5rem;
            top: 50%;
            transform: translateY(-50%);
            background: rgba(102, 126, 234, 0.2);
            color: #667eea;
            border: none;
            border-radius: 0.5rem;
            padding: 0.5rem 0.75rem;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .copy-btn:hover {
            background: rgba(102, 126, 234, 0.3);
        }
        
        /* 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-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);
        }
        
        /* Close button for mobile sidebar */
        .sidebar-close-btn {
            display: none;
        }
        
        @media (max-width: 1023px) {
            .sidebar-close-btn {
                display: block;
                position: absolute;
                top: 1rem;
                right: 1rem;
                z-index: 1001;
                width: 2.5rem;
                height: 2.5rem;
                background: rgba(255, 255, 255, 0.1);
                border-radius: 50%;
                display: flex;
                align-items: center;
                justify-content: center;
                border: none;
                color: white;
                cursor: pointer;
                transition: all 0.2s ease;
                backdrop-filter: blur(10px);
            }
            
            .sidebar-close-btn:hover {
                background: rgba(255, 255, 255, 0.2);
                transform: rotate(90deg);
            }
        }
        
        /* 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;
        }
    </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">
                            Make Deposit
                        </h2>
                        <p class="text-gray-400 mt-2">
                            Add funds to your account 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>

            <!-- Deposit 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; ?>
                
                <!-- Deposit Limits Info -->
                <div class="alert-info mb-6">
                    <i class="fas fa-info-circle"></i>
                    <div class="flex-1">
                        <span class="font-medium">Deposit Limits:</span> 
                        Minimum: <span class="font-bold">$<?php echo number_format($site_settings['min_deposit_amount'] ?? 100, 2); ?></span> • 
                        Maximum: <span class="font-bold">$<?php echo number_format($site_settings['max_deposit_amount'] ?? 100000, 2); ?></span>
                    </div>
                </div>

                <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
                    <!-- Left Column: Deposit Form -->
                    <div class="lg:col-span-2">
                        <div class="glass-card p-6 mb-6 animate-fade-in">
                            <h3 class="text-xl font-bold mb-6 flex items-center">
                                <i class="fas fa-money-bill-wave mr-3 text-green-400"></i> Deposit Form
                            </h3>
                            
                            <form method="POST" action="" enctype="multipart/form-data" id="depositForm">
                                <!-- Amount Input -->
                                <div class="form-group">
                                    <label class="form-label">Deposit 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_deposit_amount'] ?? 100; ?>"
                                               max="<?php echo $site_settings['max_deposit_amount'] ?? 100000; ?>"
                                               placeholder="Enter amount"
                                               required
                                               oninput="updateAmountDisplay(this.value)">
                                    </div>
                                    <div class="flex justify-between text-xs text-gray-400 mt-2">
                                        <span>Min: $<?php echo number_format($site_settings['min_deposit_amount'] ?? 100, 2); ?></span>
                                        <span id="amountDisplay">$0.00</span>
                                        <span>Max: $<?php echo number_format($site_settings['max_deposit_amount'] ?? 100000, 2); ?></span>
                                    </div>
                                    <div class="progress-bar">
                                        <div id="amountProgress" class="progress-fill" style="width: 0%"></div>
                                    </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) && ($site_settings['enable_crypto_payments'] ?? '1') == '1'): ?>
                                    <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 $index => $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">Send <?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) && ($site_settings['enable_bank_payments'] ?? '1') == '1'): ?>
                                    <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 at the moment.</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 Instructions</h4>
                                        <div id="cryptoInstructions" class="hidden">
                                            <!-- Crypto instructions will be loaded here -->
                                        </div>
                                        <div id="bankInstructions" class="hidden">
                                            <!-- Bank instructions will be loaded here -->
                                        </div>
                                        
                                        <!-- Transaction Hash (for crypto) -->
                                        <div id="transactionHashField" class="form-group hidden">
                                            <label class="form-label">Transaction Hash/ID</label>
                                            <input type="text" name="transaction_hash" class="form-input" placeholder="Enter your transaction hash">
                                            <p class="text-xs text-gray-400 mt-2">Required for crypto payments to verify your transaction</p>
                                        </div>
                                        
                                        <!-- Payment Proof Upload -->
                                        <div class="form-group">
                                            <label class="form-label">Payment Proof (Optional)</label>
                                            <input type="file" name="payment_proof" class="form-input" accept="image/*,.pdf">
                                            <p class="text-xs text-gray-400 mt-2">Upload screenshot or PDF receipt (Max 5MB, JPG, PNG, PDF)</p>
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- Submit Button -->
                                <div class="mt-8 pt-6 border-t border-gray-700/50">
                                    <button type="submit" name="submit_deposit" class="btn-success w-full">
                                        <i class="fas fa-paper-plane mr-2"></i> Submit Deposit Request
                                    </button>
                                </div>
                            </form>
                        </div>
                        
                        <!-- Recent Deposits -->
                        <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 Deposits
                                </h3>
                                <a href="statement.php?type=deposit" 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_deposits)): ?>
                                <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_deposits as $deposit): ?>
                                                <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($deposit['created_at'])); ?></td>
                                                    <td class="py-3 font-medium">$<?php echo number_format($deposit['amount'], 2); ?></td>
                                                    <td class="py-3 text-sm">
                                                        <?php 
                                                        if ($deposit['payment_type'] == 'crypto') {
                                                            echo htmlspecialchars($deposit['wallet_name'] ?? 'Crypto');
                                                        } else {
                                                            echo htmlspecialchars($deposit['bank_name'] ?? 'Bank');
                                                        }
                                                        ?>
                                                    </td>
                                                    <td class="py-3">
                                                        <?php
                                                        $status_class = 'status-pending';
                                                        $status_text = 'Pending';
                                                        if ($deposit['status'] == 'completed') {
                                                            $status_class = 'status-completed';
                                                            $status_text = 'Completed';
                                                        } elseif ($deposit['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($deposit['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 deposits found.</p>
                                    <p class="text-sm mt-2">Your deposit history will appear here.</p>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                    
                    <!-- Right Column: Information & Stats -->
                    <div>
                        <!-- Account Balance Card -->
                        <div class="gradient-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-blue-500/20 to-purple-500/20 rounded-xl flex items-center justify-center">
                                    <i class="fas fa-wallet text-2xl text-blue-400"></i>
                                </div>
                            </div>
                            <div class="space-y-3">
                                <div class="flex justify-between items-center">
                                    <span class="text-gray-400">Total Deposits</span>
                                    <span class="font-semibold text-green-400">$<?php echo number_format($total_deposits, 2); ?></span>
                                </div>
                                <div class="flex justify-between items-center">
                                    <span class="text-gray-400">Last Deposit</span>
                                    <span class="font-semibold"><?php echo $last_deposit_date; ?></span>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Deposit Instructions -->
                        <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-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-3 confirmations • 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">Send Exact Amount</p>
                                        <p class="text-xs text-gray-400">Always send the exact amount requested to avoid delays</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 Deposit Amounts -->
                        <div class="glass-card p-6 animate-fade-in" style="animation-delay: 0.4s">
                            <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="setAmount(<?php echo $site_settings['min_deposit_amount'] ?? 100; ?>)" class="btn-secondary py-3">
                                    $<?php echo number_format($site_settings['min_deposit_amount'] ?? 100, 0); ?>
                                </button>
                                <button type="button" onclick="setAmount(500)" class="btn-secondary py-3">
                                    $500
                                </button>
                                <button type="button" onclick="setAmount(1000)" class="btn-secondary py-3">
                                    $1,000
                                </button>
                                <button type="button" onclick="setAmount(5000)" class="btn-secondary py-3">
                                    $5,000
                                </button>
                                <button type="button" onclick="setAmount(10000)" class="btn-secondary py-3">
                                    $10,000
                                </button>
                                <button type="button" onclick="setAmount(50000)" class="btn-secondary py-3">
                                    $50,000
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Footer -->
                <div class="mt-8 text-center">
                    <p class="text-gray-500 text-sm">
                        Need assistance with your deposit? 
                        <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 deposits are subject to verification. Processing times may vary.
                    </p>
                </div>
            </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
        menuToggle.addEventListener('click', toggleSidebar);
        closeSidebar.addEventListener('click', closeSidebarFunc);
        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('deposit.php')) {
                    nav.classList.add('active');
                } else {
                    nav.classList.remove('active');
                }
            });
            
            // Auto-select default payment method
            <?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; ?>
        });

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

        // Deposit form functionality
        function setAmount(amount) {
            const amountInput = document.getElementById('amount');
            amountInput.value = amount;
            updateAmountDisplay(amount);
        }
        
        function updateAmountDisplay(value) {
            const amount = parseFloat(value) || 0;
            const min = parseFloat(<?php echo $site_settings['min_deposit_amount'] ?? 100; ?>);
            const max = parseFloat(<?php echo $site_settings['max_deposit_amount'] ?? 100000; ?>);
            
            // 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';
            } else if (amount > max) {
                document.getElementById('amountProgress').style.background = '#f56565';
            } else {
                document.getElementById('amountProgress').style.background = 'linear-gradient(90deg, #667eea, #764ba2)';
            }
        }
        
        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(methodId, methodType);
        }
        
        function showPaymentDetails(methodId, methodType) {
            const paymentDetails = document.getElementById('paymentDetails');
            const cryptoInstructions = document.getElementById('cryptoInstructions');
            const bankInstructions = document.getElementById('bankInstructions');
            const transactionHashField = document.getElementById('transactionHashField');
            
            // Show payment details section
            paymentDetails.classList.remove('hidden');
            
            // Hide all instruction sections first
            cryptoInstructions.classList.add('hidden');
            bankInstructions.classList.add('hidden');
            transactionHashField.classList.add('hidden');
            
            // Show appropriate instructions
            if (methodType === 'crypto') {
                cryptoInstructions.classList.remove('hidden');
                transactionHashField.classList.remove('hidden');
                loadCryptoInstructions(methodId);
            } else if (methodType === 'bank') {
                bankInstructions.classList.remove('hidden');
                loadBankInstructions(methodId);
            }
        }
        
        function loadCryptoInstructions(methodId) {
            const cryptoInstructions = document.getElementById('cryptoInstructions');
            
            const cryptoMethods = <?php echo json_encode(array_values($crypto_methods)); ?>;
            const method = cryptoMethods.find(m => m.id == methodId);
            
            if (method) {
                cryptoInstructions.innerHTML = `
                    <div class="mb-4">
                        <p class="text-sm text-gray-400 mb-3">${method.deposit_instruction || 'Send exact amount to the wallet address below.'}</p>
                        
                        <div class="mb-4">
                            <label class="form-label">Wallet Address</label>
                            <div class="wallet-address">
                                ${method.wallet_address}
                                <button type="button" onclick="copyToClipboard('${method.wallet_address}')" class="copy-btn">
                                    <i class="fas fa-copy"></i>
                                </button>
                            </div>
                        </div>
                        
                        <div class="grid grid-cols-2 gap-4 mb-4">
                            <div>
                                <label class="form-label">Network</label>
                                <div class="font-medium">${method.crypto_network}</div>
                            </div>
                            <div>
                                <label class="form-label">Wallet Name</label>
                                <div class="font-medium">${method.wallet_name}</div>
                            </div>
                        </div>
                        
                        <div class="alert-info">
                            <i class="fas fa-exclamation-circle"></i>
                            <div class="text-sm">
                                <strong>Important:</strong> Send ${method.crypto_network} only. Sending other coins may result in permanent loss.
                            </div>
                        </div>
                    </div>
                `;
            }
        }
        
        function loadBankInstructions(methodId) {
            const bankInstructions = document.getElementById('bankInstructions');
            
            const bankMethods = <?php echo json_encode(array_values($bank_methods)); ?>;
            const method = bankMethods.find(m => m.id == methodId);
            
            if (method) {
                bankInstructions.innerHTML = `
                    <div class="mb-4">
                        <p class="text-sm text-gray-400 mb-3">${method.deposit_instruction || 'Transfer funds to the bank account below and upload proof.'}</p>
                        
                        <div class="space-y-3">
                            <div>
                                <label class="form-label">Bank Name</label>
                                <div class="font-medium">${method.bank_name}</div>
                            </div>
                            
                            <div>
                                <label class="form-label">Account Name</label>
                                <div class="font-medium">${method.account_name}</div>
                            </div>
                            
                            <div>
                                <label class="form-label">Account Number</label>
                                <div class="font-medium font-mono">${method.account_number}</div>
                            </div>
                            
                            ${method.swift_code ? `
                            <div>
                                <label class="form-label">SWIFT Code</label>
                                <div class="font-medium">${method.swift_code}</div>
                            </div>
                            ` : ''}
                            
                            ${method.iban ? `
                            <div>
                                <label class="form-label">IBAN</label>
                                <div class="font-medium font-mono">${method.iban}</div>
                            </div>
                            ` : ''}
                            
                            ${method.branch_code ? `
                            <div>
                                <label class="form-label">Branch Code</label>
                                <div class="font-medium">${method.branch_code}</div>
                            </div>
                            ` : ''}
                            
                            ${method.branch_address ? `
                            <div>
                                <label class="form-label">Branch Address</label>
                                <div class="text-sm">${method.branch_address}</div>
                            </div>
                            ` : ''}
                        </div>
                        
                        <div class="alert-info mt-4">
                            <i class="fas fa-exclamation-circle"></i>
                            <div class="text-sm">
                                <strong>Important:</strong> Include your account ID (<?php echo $account_id; ?>) in the transfer reference.
                            </div>
                        </div>
                    </div>
                `;
            }
        }
        
        function copyToClipboard(text) {
            navigator.clipboard.writeText(text).then(() => {
                showNotification('Copied to clipboard!', 'success');
            }).catch(err => {
                const textArea = document.createElement('textarea');
                textArea.value = text;
                document.body.appendChild(textArea);
                textArea.select();
                document.execCommand('copy');
                document.body.removeChild(textArea);
                showNotification('Copied to clipboard!', 'success');
            });
        }
        
        // Form validation
        document.getElementById('depositForm').addEventListener('submit', function(e) {
            const amount = parseFloat(document.getElementById('amount').value) || 0;
            const min = parseFloat(<?php echo $site_settings['min_deposit_amount'] ?? 100; ?>);
            const max = parseFloat(<?php echo $site_settings['max_deposit_amount'] ?? 100000; ?>);
            const methodId = document.getElementById('payment_method_id').value;
            
            let hasError = false;
            
            // Validate amount
            if (amount < min) {
                showFieldError('amount', `Minimum deposit is $${min}`);
                hasError = true;
            } else if (amount > max) {
                showFieldError('amount', `Maximum deposit is $${max}`);
                hasError = true;
            }
            
            // Validate payment method
            if (!methodId) {
                document.getElementById('paymentMethodError').classList.remove('hidden');
                hasError = true;
            }
            
            if (hasError) {
                e.preventDefault();
                showNotification('Please fix the errors above', 'error');
            }
        });
        
        function showFieldError(fieldId, message) {
            const field = document.getElementById(fieldId);
            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' : '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' : '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);
        }
        
        // Initialize on page load
        document.addEventListener('DOMContentLoaded', function() {
            // Set default amount display
            const amountInput = document.getElementById('amount');
            if (amountInput.value) {
                updateAmountDisplay(amountInput.value);
            } else {
                amountInput.value = <?php echo $site_settings['min_deposit_amount'] ?? 100; ?>;
                updateAmountDisplay(amountInput.value);
            }
        });
    </script>
</body>
</html>