<?php
$page_title = "Deposit Funds";
require_once '../config/config.php';
require_once '../includes/user_auth.php';
require_once '../includes/functions.php';

// Ensure Auth is initialized
if (!isset($auth)) {
    $auth = new Auth();
}

$user_id = $auth->getCurrentUserId();
if (!$user_id) {
    header("Location: ../login.php");
    exit();
}
$functions = new InvestmentFunctions();
$user = $functions->getUserById($user_id);
$user_data = $user; // Ensure user data is available for header

$payment_methods = [
    'bitcoin' => ['name' => 'Bitcoin', 'icon' => 'fab fa-bitcoin', 'color' => 'text-orange-500'],
  //  'ethereum' => ['name' => 'Ethereum', 'icon' => 'fab fa-ethereum', 'color' => 'text-purple-500'],
    'usdt' => ['name' => 'USDT', 'icon' => 'fas fa-coins', 'color' => 'text-green-500'],
    // 'bank' => ['name' => 'Bank Transfer', 'icon' => 'fas fa-university', 'color' => 'text-blue-500'],
    // 'paypal' => ['name' => 'PayPal', 'icon' => 'fab fa-paypal', 'color' => 'text-blue-400'],
    // 'skrill' => ['name' => 'Skrill', 'icon' => 'fas fa-money-bill-wave', 'color' => 'text-red-500'],
    // 'perfect_money' => ['name' => 'Perfect Money', 'icon' => 'fas fa-wallet', 'color' => 'text-green-500']
];

$deposit_addresses = [
    'bitcoin' => 'bc1qdxvh25ruxz3u34czxnwdca6uese3zr7ndj2r5p',
  //  'ethereum' => '0x742d35Cc6634C0532925a3b844Bc9e0F7d5A5c7a',
  //  'usdt_erc20' => '0x742d35Cc6634C0532925a3b844Bc9e0F7d5A5c7a',
    'usdt_trc20' => 'TXvJhuvb19T7o4CuM93qU4hUe9enVgLCeE'
];


if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $amount = floatval($_POST['amount']);
    $method = $functions->sanitize($_POST['method']);
    
    if ($method === 'usdt' && isset($_POST['network'])) {
        $method .= '_' . $functions->sanitize($_POST['network']);
    }
    
    if ($amount < 100) {
        $error = "Minimum deposit is $100";
    } elseif ($amount > 1000000000) {
        $error = "Maximum deposit is $1,000,000,000";
    } else {
        // Redirect to payment page with details
        $params = [
            'amount' => $amount,
            'method' => $method
        ];
        header("Location: deposit-payment.php?" . http_build_query($params));
        exit();
    }
}
require_once '../includes/header_user.php'; ?>

<div class="container mx-auto px-4 py-8">
    <div class="max-w-4xl mx-auto">
        <div class="mb-8">
            <h1 class="text-3xl font-bold text-gray-800">Deposit Funds</h1>
            <p class="text-gray-600">Add funds to your investment account</p>
        </div>
        
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
            <!-- Deposit Form -->
            <div class="lg:col-span-2">
                <div class="bg-white rounded-xl shadow-lg p-6 mb-8">
                    <?php if (isset($error)): ?>
                    <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
                        <?php echo $error; ?>
                    </div>
                    <?php endif; ?>
                    
                    <?php if (isset($success)): ?>
                    <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded mb-4">
                        <?php echo $success; ?>
                    </div>
                    <?php endif; ?>
                    
                    <form method="POST" action="" class="space-y-6">
                        <!-- Amount -->
                        <div>
                            <label class="block text-gray-700 font-semibold mb-2">Deposit Amount (USD)</label>
                            <div class="relative">
                                <span class="absolute left-3 top-3 text-gray-500">$</span>
                                <input type="number" name="amount" step="0.01" min="10" max="100000" required
                                       class="w-full pl-8 pr-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
                                       placeholder="Enter amount">
                            </div>
                            <div class="flex justify-between mt-2 text-sm">
                                <span class="text-gray-500">Min: $100.00</span>
                                <span class="text-gray-500">Max: $1,000,000.00</span>
                            </div>
                        </div>
                        
                        <!-- Payment Method -->
                        <div>
                            <label class="block text-gray-700 font-semibold mb-2">Select Payment Method</label>
                            <div class="grid grid-cols-2 md:grid-cols-3 gap-4">
                                <?php foreach ($payment_methods as $key => $method): ?>
                                <label class="relative">
                                    <input type="radio" name="method" value="<?php echo $key; ?>" 
                                           class="hidden peer" <?php echo $key === 'bitcoin' ? 'checked' : ''; ?> onchange="toggleNetworkSelection(this.value)">
                                    <div class="border-2 border-gray-200 rounded-lg p-4 text-center cursor-pointer peer-checked:border-purple-500 peer-checked:bg-purple-50 hover:border-gray-300">
                                        <i class="<?php echo $method['icon']; ?> <?php echo $method['color']; ?> text-2xl mb-2"></i>
                                        <p class="font-medium"><?php echo $method['name']; ?></p>
                                    </div>
                                </label>
                                <?php endforeach; ?>
                            </div>
                            <p class="text-sm text-gray-500 mt-4">If your desired payment option is not listed, please <a href="support.php" class="text-purple-600 hover:underline">contact support</a>.</p>
                        </div>

                        <!-- Network Selection (for USDT) -->
                        <div id="network-selection" class="hidden">
                            <label class="block text-gray-700 font-semibold mb-2">Select USDT Network</label>
                            <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
                                <label class="relative">
                                    <input type="radio" name="network" value="erc20" class="hidden peer" checked onchange="updateAddress('erc20')">
                                    <div class="border-2 border-gray-200 rounded-lg p-4 text-center cursor-pointer peer-checked:border-purple-500 peer-checked:bg-purple-50 hover:border-gray-300">
                                        <p class="font-medium text-sm">ERC-20</p>
                                        <p class="text-xs text-gray-500">Ethereum</p>
                                    </div>
                                </label>
                                <label class="relative">
                                    <input type="radio" name="network" value="trc20" class="hidden peer" onchange="updateAddress('trc20')">
                                    <div class="border-2 border-gray-200 rounded-lg p-4 text-center cursor-pointer peer-checked:border-purple-500 peer-checked:bg-purple-50 hover:border-gray-300">
                                        <p class="font-medium text-sm">TRC-20</p>
                                        <p class="text-xs text-gray-500">Tron</p>
                                    </div>
                                </label>
                                <label class="relative">
                                    <input type="radio" name="network" value="bep20" class="hidden peer" onchange="updateAddress('bep20')">
                                    <div class="border-2 border-gray-200 rounded-lg p-4 text-center cursor-pointer peer-checked:border-purple-500 peer-checked:bg-purple-50 hover:border-gray-300">
                                        <p class="font-medium text-sm">BEP-20</p>
                                        <p class="text-xs text-gray-500">Binance</p>
                                    </div>
                                </label>
                                <label class="relative">
                                    <input type="radio" name="network" value="solana" class="hidden peer" onchange="updateAddress('solana')">
                                    <div class="border-2 border-gray-200 rounded-lg p-4 text-center cursor-pointer peer-checked:border-purple-500 peer-checked:bg-purple-50 hover:border-gray-300">
                                        <p class="font-medium text-sm">Solana</p>
                                        <p class="text-xs text-gray-500">SOL</p>
                                    </div>
                                </label>
                            </div>
                        </div>
                        
                        <!-- Current Balance -->
                        <div class="bg-gray-50 rounded-lg p-4">
                            <div class="flex justify-between items-center">
                                <div>
                                    <p class="text-gray-600">Current Balance</p>
                                    <p class="text-2xl font-bold text-green-600">$<?php echo number_format($user['balance'], 2); ?></p>
                                </div>
                                <a href="dashboard.php" class="text-purple-600 hover:text-purple-800">
                                    <i class="fas fa-home mr-1"></i> Dashboard
                                </a>
                            </div>
                        </div>
                        
                        <!-- Submit Button -->
                        <button type="submit" 
                                class="w-full bg-gradient-to-r from-purple-600 to-blue-600 text-white font-bold py-3 px-4 rounded-lg hover:opacity-90 transition duration-300">
                            <i class="fas fa-arrow-right mr-2"></i> Proceed to Payment
                        </button>
                    </form>
                </div>
                
                <!-- Deposit History -->
                <div class="bg-white rounded-xl shadow-lg p-6">
                    <h3 class="text-xl font-bold mb-4">Recent Deposits</h3>
                    <?php
                    $deposits = $functions->getTransactions($user_id, 'deposit', 5);
                    if (count($deposits) > 0): ?>
                    <div class="overflow-x-auto">
                        <table class="w-full">
                            <thead>
                                <tr class="bg-gray-50">
                                    <th class="p-3 text-left">Date</th>
                                    <th class="p-3 text-left">Amount</th>
                                    <th class="p-3 text-left">Method</th>
                                    <th class="p-3 text-left">Status</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($deposits as $deposit): ?>
                                <tr class="border-b border-gray-100">
                                    <td class="p-3"><?php echo date('M d, Y', strtotime($deposit['created_at'])); ?></td>
                                    <td class="p-3 font-semibold">$<?php echo number_format($deposit['amount'], 2); ?></td>
                                    <td class="p-3">
                                        <span class="capitalize"><?php echo $deposit['method']; ?></span>
                                    </td>
                                    <td class="p-3">
                                        <span class="px-2 py-1 text-xs rounded-full <?php 
                                            echo $deposit['status'] === 'completed' ? 'bg-green-100 text-green-800' :
                                                ($deposit['status'] === 'pending' ? 'bg-yellow-100 text-yellow-800' : 
                                                'bg-red-100 text-red-800');
                                        ?>">
                                            <?php echo ucfirst($deposit['status']); ?>
                                        </span>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <?php else: ?>
                    <p class="text-gray-500 text-center py-4">No deposit history yet</p>
                    <?php endif; ?>
                </div>
            </div>
            
            <!-- Payment Instructions -->
            <div>
                <div class="bg-white rounded-xl shadow-lg p-6 mb-6">
                    <h3 class="text-xl font-bold mb-4">Payment Instructions</h3>
                    <div class="space-y-4">
                        <div class="flex items-start space-x-3 hidden" id="usdt-instructions">
                            <div class="bg-purple-100 p-2 rounded-full">
                                <i class="fas fa-wallet text-purple-600"></i>
                            </div>
                            <div>
                                <p class="font-semibold">USDT Deposit (<span id="network-name">ERC-20</span>)</p>
                                <p class="text-sm text-gray-600">Send USDT to the address below</p>
                                <div class="mt-2 bg-gray-100 p-3 rounded">
                                    <code class="text-sm break-all" id="wallet-address"><?php echo $deposit_addresses['usdt_erc20']; ?></code>
                                    <button type="button" onclick="copyAddress()" 
                                            class="mt-2 text-xs bg-gray-800 text-white px-2 py-1 rounded">
                                        Copy Address
                                    </button>
                                </div>
                            </div>
                        </div>
                        
                        <div class="flex items-start space-x-3 hidden" id="bitcoin-instructions">
                            <div class="bg-orange-100 p-2 rounded-full">
                                <i class="fab fa-bitcoin text-orange-500"></i>
                            </div>
                            <div>
                                <p class="font-semibold">Bitcoin Deposit</p>
                                <p class="text-sm text-gray-600">Send BTC to the address below</p>
                                <div class="mt-2 bg-gray-100 p-3 rounded">
                                    <code class="text-sm break-all" id="bitcoin-wallet-address"><?php echo $deposit_addresses['bitcoin']; ?></code>
                                    <button type="button" onclick="copyToClipboard('<?php echo $deposit_addresses['bitcoin']; ?>')" 
                                            class="mt-2 text-xs bg-gray-800 text-white px-2 py-1 rounded">
                                        Copy Address
                                    </button>
                                </div>
                            </div>
                        </div>

                        <div class="flex items-start space-x-3 hidden" id="ethereum-instructions">
                            <div class="bg-purple-100 p-2 rounded-full">
                                <i class="fab fa-ethereum text-purple-500"></i>
                            </div>
                            <div>
                                <p class="font-semibold">Ethereum Deposit</p>
                                <p class="text-sm text-gray-600">Send ETH to the address below</p>
                                <div class="mt-2 bg-gray-100 p-3 rounded">
                                    <code class="text-sm break-all" id="ethereum-wallet-address"><?php echo $deposit_addresses['ethereum']; ?></code>
                                    <button type="button" onclick="copyToClipboard('<?php echo $deposit_addresses['ethereum']; ?>')" 
                                            class="mt-2 text-xs bg-gray-800 text-white px-2 py-1 rounded">
                                        Copy Address
                                    </button>
                                </div>
                            </div>
                        </div>
                        
                        <div class="border-t pt-4">
                            <p class="text-sm text-gray-600">
                                <i class="fas fa-info-circle mr-1"></i>
                                Deposits are processed within 1-24 hours after confirmation
                            </p>
                        </div>
                    </div>
                </div>
                
                <!-- Important Notes -->
                <div class="bg-yellow-50 border border-yellow-200 rounded-xl p-6">
                    <h4 class="font-bold text-yellow-800 mb-3">
                        <i class="fas fa-exclamation-triangle mr-2"></i>
                        Important Notes
                    </h4>
                    <ul class="space-y-2 text-sm text-yellow-700">
                        <li>• Send only the exact amount</li>
                        <li>• Include your user ID in the memo</li>
                        <li>• Contact support for any issues</li>
                        <li>• Do not send from exchange wallets</li>
                        <li>• Minimum 3 confirmations required</li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Notification Container -->
<div id="notification-container" class="fixed top-4 right-4 z-50 space-y-2"></div>

<script>
    const addresses = {
        'erc20': '<?php echo $deposit_addresses['usdt_erc20']; ?>',
        'trc20': '<?php echo $deposit_addresses['usdt_trc20']; ?>'
    };

    function copyToClipboard(text) {
        navigator.clipboard.writeText(text).then(function() {
            showNotification('Address copied to clipboard!', 'success');
        });
    }

    function copyAddress() {
        const address = document.getElementById('wallet-address').innerText;
        copyToClipboard(address);
    }

    function toggleNetworkSelection(method) {
        const networkSelection = document.getElementById('network-selection');
        const usdtInstructions = document.getElementById('usdt-instructions');
        const bitcoinInstructions = document.getElementById('bitcoin-instructions');
        const ethereumInstructions = document.getElementById('ethereum-instructions');

        // Hide all
        networkSelection.classList.add('hidden');
        usdtInstructions.classList.add('hidden');
        bitcoinInstructions.classList.add('hidden');
        ethereumInstructions.classList.add('hidden');
        
        if (method === 'usdt') {
            networkSelection.classList.remove('hidden');
            usdtInstructions.classList.remove('hidden');
        } else if (method === 'bitcoin') {
            bitcoinInstructions.classList.remove('hidden');
        } else if (method === 'ethereum') {
            ethereumInstructions.classList.remove('hidden');
        } else {
            networkSelection.classList.add('hidden');
        }
    }

    function updateAddress(network) {
        document.getElementById('network-name').innerText = network === 'erc20' ? 'ERC-20' : 'TRC-20';
        document.getElementById('wallet-address').innerText = addresses[network];
    }
    
    // Update amount display
    document.querySelector('input[name="amount"]').addEventListener('input', function(e) {
        const amount = parseFloat(e.target.value) || 0;
        // You can add fee calculation logic here if needed
    });

    // Notification function
    function showNotification(message, type = 'info') {
        const container = document.getElementById('notification-container');
        const notification = document.createElement('div');
        
        // Tailwind classes for styling
        const baseClasses = 'transform transition-all duration-300 ease-in-out translate-x-full bg-white rounded-lg shadow-lg p-4 flex items-center space-x-3 min-w-[300px] border-l-4';
        const typeClasses = type === 'success' ? 'border-green-500' : (type === 'error' ? 'border-red-500' : 'border-blue-500');
        const iconClass = type === 'success' ? 'fa-check-circle text-green-500' : (type === 'error' ? 'fa-exclamation-circle text-red-500' : 'fa-info-circle text-blue-500');
        
        notification.className = `${baseClasses} ${typeClasses}`;
        notification.innerHTML = `
            <i class="fas ${iconClass} text-xl"></i>
            <div class="flex-1">
                <p class="text-sm font-medium text-gray-900">${message}</p>
            </div>
            <button onclick="this.parentElement.remove()" class="text-gray-400 hover:text-gray-500">
                <i class="fas fa-times"></i>
            </button>
        `;

        container.appendChild(notification);

        // Animate in
        requestAnimationFrame(() => {
            notification.classList.remove('translate-x-full');
        });

        // Auto dismiss
        setTimeout(() => {
            notification.classList.add('translate-x-full');
            setTimeout(() => {
                notification.remove();
            }, 300);
        }, 3000);
    }

    // Initialize
    toggleNetworkSelection(document.querySelector('input[name="method"]:checked').value);
</script>

<?php require_once '../includes/footer.php'; ?>