<?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['email_verified']) && $user['email_verified'] == 0) {
    header("Location: verify.php?message=Please verify your email first");
    exit();
}

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 if trades table exists, create if not
$conn->query("
    CREATE TABLE IF NOT EXISTS forex_trades (
        id INT AUTO_INCREMENT PRIMARY KEY,
        user_id INT NOT NULL,
        currency_pair VARCHAR(20) NOT NULL,
        trade_type ENUM('BUY', 'SELL') NOT NULL,
        amount DECIMAL(15,2) NOT NULL,
        entry_price DECIMAL(15,5) NOT NULL,
        exit_price DECIMAL(15,5) NULL,
        lot_size DECIMAL(10,2) NOT NULL,
        stop_loss DECIMAL(15,5) NULL,
        take_profit DECIMAL(15,5) NULL,
        profit_loss DECIMAL(15,2) NULL,
        status ENUM('open', 'closed', 'pending', 'cancelled') DEFAULT 'pending',
        admin_action ENUM('profit', 'loss', 'pending') DEFAULT 'pending',
        closed_at DATETIME NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
        INDEX idx_user_status (user_id, status),
        INDEX idx_admin_action (admin_action)
    )
");

// Handle trade submission
$message = '';
$message_type = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['place_trade'])) {
    $currency_pair = mysqli_real_escape_string($conn, $_POST['currency_pair']);
    $trade_type = mysqli_real_escape_string($conn, $_POST['trade_type']);
    $amount = floatval($_POST['amount']);
    $lot_size = floatval($_POST['lot_size']);
    $stop_loss = isset($_POST['stop_loss']) && $_POST['stop_loss'] !== '' ? floatval($_POST['stop_loss']) : null;
    $take_profit = isset($_POST['take_profit']) && $_POST['take_profit'] !== '' ? floatval($_POST['take_profit']) : null;
    
    // Validation
    if ($amount <= 0) {
        $message = "Please enter a valid amount";
        $message_type = "error";
    } elseif ($amount > $user['account_balance']) {
        $message = "Insufficient balance. Your available balance is $" . number_format($user['account_balance'], 2);
        $message_type = "error";
    } elseif ($lot_size <= 0 || $lot_size > 10) {
        $message = "Lot size must be between 0.01 and 10.00";
        $message_type = "error";
    } else {
        // Get current market price for entry
        $entry_price = getMarketPrice($currency_pair);
        
        // Insert trade
        $insert_stmt = $conn->prepare("
            INSERT INTO forex_trades 
            (user_id, currency_pair, trade_type, amount, entry_price, lot_size, stop_loss, take_profit, status) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending')
        ");
        
        $insert_stmt->bind_param("issddddd", 
            $user_id, 
            $currency_pair, 
            $trade_type, 
            $amount, 
            $entry_price, 
            $lot_size, 
            $stop_loss, 
            $take_profit
        );
        
        if ($insert_stmt->execute()) {
            // Deduct from account balance
            $new_balance = $user['account_balance'] - $amount;
            $update_balance = $conn->prepare("UPDATE users SET account_balance = ? WHERE id = ?");
            $update_balance->bind_param("di", $new_balance, $user_id);
            $update_balance->execute();
            $update_balance->close();
            
            // Create notification
            $notif_title = "Trade Placed Successfully";
            $notif_message = "Your $trade_type trade of $amount on $currency_pair has been placed and is pending admin approval.";
            $notif_stmt = $conn->prepare("INSERT INTO notifications (user_id, title, message, notification_type) VALUES (?, ?, ?, 'trade')");
            $notif_stmt->bind_param("iss", $user_id, $notif_title, $notif_message);
            $notif_stmt->execute();
            $notif_stmt->close();
            
            $message = "Trade placed successfully! Waiting for admin approval.";
            $message_type = "success";
            
            // Refresh user data
            $user['account_balance'] = $new_balance;
        } else {
            $message = "Error placing trade. Please try again.";
            $message_type = "error";
        }
        $insert_stmt->close();
    }
}

// Function to get market price (simulated)
function getMarketPrice($pair) {
    // In production, this would connect to a real forex API
    // For demo, return simulated prices
    $prices = [
        'EUR/USD' => 1.0850 + (rand(-50, 50) / 10000),
        'GBP/USD' => 1.2650 + (rand(-50, 50) / 10000),
        'USD/JPY' => 148.50 + (rand(-50, 50) / 100),
        'USD/CHF' => 0.8750 + (rand(-50, 50) / 10000),
        'AUD/USD' => 0.6550 + (rand(-50, 50) / 10000),
        'USD/CAD' => 1.3450 + (rand(-50, 50) / 10000),
        'NZD/USD' => 0.6050 + (rand(-50, 50) / 10000),
        'EUR/GBP' => 0.8550 + (rand(-50, 50) / 10000),
        'EUR/JPY' => 160.50 + (rand(-50, 50) / 100),
        'GBP/JPY' => 187.50 + (rand(-50, 50) / 100)
    ];
    
    return isset($prices[$pair]) ? $prices[$pair] : 1.0000;
}

// Fetch user's trades
$trades_stmt = $conn->prepare("
    SELECT * FROM forex_trades 
    WHERE user_id = ? 
    ORDER BY created_at DESC 
    LIMIT 20
");
$trades_stmt->bind_param("i", $user_id);
$trades_stmt->execute();
$trades_result = $trades_stmt->get_result();
$trades_stmt->close();

// Calculate trade statistics
$stats = [
    'total_trades' => 0,
    'open_trades' => 0,
    'closed_trades' => 0,
    'total_profit' => 0,
    'total_loss' => 0,
    'win_rate' => 0
];

$stats_stmt = $conn->prepare("
    SELECT 
        COUNT(*) as total,
        SUM(CASE WHEN status = 'open' THEN 1 ELSE 0 END) as open,
        SUM(CASE WHEN status = 'closed' THEN 1 ELSE 0 END) as closed,
        SUM(CASE WHEN status = 'closed' AND profit_loss > 0 THEN profit_loss ELSE 0 END) as total_profit,
        SUM(CASE WHEN status = 'closed' AND profit_loss < 0 THEN profit_loss ELSE 0 END) as total_loss,
        SUM(CASE WHEN status = 'closed' AND profit_loss > 0 THEN 1 ELSE 0 END) as winning_trades,
        SUM(CASE WHEN status = 'closed' THEN 1 ELSE 0 END) as total_closed
    FROM forex_trades 
    WHERE user_id = ?
");
$stats_stmt->bind_param("i", $user_id);
$stats_stmt->execute();
$stats_result = $stats_stmt->get_result();
if ($row = $stats_result->fetch_assoc()) {
    $stats = $row;
    $stats['win_rate'] = ($stats['total_closed'] > 0) ? 
        round(($stats['winning_trades'] / $stats['total_closed']) * 100, 2) : 0;
}
$stats_stmt->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Forex Trading - <?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, #38b2ac 0%, #319795 100%);
            --warning-gradient: linear-gradient(135deg, #ed8936 0%, #dd6b20 100%);
            --danger-gradient: linear-gradient(135deg, #f56565 0%, #e53e3e 100%);
            --info-gradient: linear-gradient(135deg, #4299e1 0%, #3182ce 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));
            }
        }
        
        .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(-2px);
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
            border-color: rgba(102, 126, 234, 0.3);
        }
        
        .price-ticker {
            background: linear-gradient(90deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%);
            border: 1px solid rgba(102, 126, 234, 0.2);
            border-radius: 0.75rem;
            padding: 0.75rem 1rem;
        }
        
        .profit-badge {
            background: rgba(16, 185, 129, 0.2);
            color: #10b981;
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 600;
        }
        
        .loss-badge {
            background: rgba(239, 68, 68, 0.2);
            color: #ef4444;
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 600;
        }
        
        .pending-badge {
            background: rgba(245, 158, 11, 0.2);
            color: #f59e0b;
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 600;
        }
        
        .status-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 600;
        }
        
        .status-open {
            background: rgba(16, 185, 129, 0.2);
            color: #10b981;
        }
        
        .status-closed {
            background: rgba(102, 126, 234, 0.2);
            color: #667eea;
        }
        
        .status-pending {
            background: rgba(245, 158, 11, 0.2);
            color: #f59e0b;
        }
        
        .status-cancelled {
            background: rgba(239, 68, 68, 0.2);
            color: #ef4444;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .animate-fade-in {
            animation: fadeIn 0.5s ease-out;
        }
        
        @keyframes pulse {
            0% { box-shadow: 0 0 0 0 rgba(102, 126, 234, 0.4); }
            70% { box-shadow: 0 0 0 10px rgba(102, 126, 234, 0); }
            100% { box-shadow: 0 0 0 0 rgba(102, 126, 234, 0); }
        }
        
        .trading-pulse {
            animation: pulse 2s infinite;
        }
        
        .form-input {
            background: rgba(15, 23, 42, 0.6);
            border: 1px solid rgba(255, 255, 255, 0.1);
            border-radius: 0.75rem;
            padding: 0.75rem 1rem;
            color: white;
            width: 100%;
            transition: all 0.2s;
        }
        
        .form-input:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.2);
        }
        
        .form-input::placeholder {
            color: rgba(255, 255, 255, 0.3);
        }
        
        .form-label {
            display: block;
            margin-bottom: 0.5rem;
            font-size: 0.875rem;
            font-weight: 500;
            color: #94a3b8;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            font-weight: 600;
            padding: 0.75rem 1.5rem;
            border-radius: 0.75rem;
            transition: all 0.2s;
            border: none;
            cursor: pointer;
            width: 100%;
        }
        
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px rgba(102, 126, 234, 0.4);
        }
        
        .btn-primary:disabled {
            opacity: 0.5;
            cursor: not-allowed;
            transform: none;
        }
        
        .btn-buy {
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
        }
        
        .btn-sell {
            background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
        }
        
        .table-container {
            overflow-x: auto;
            border-radius: 1rem;
        }
        
        .table {
            width: 100%;
            border-collapse: collapse;
        }
        
        .table th {
            text-align: left;
            padding: 1rem;
            background: rgba(15, 23, 42, 0.8);
            font-weight: 600;
            font-size: 0.875rem;
            color: #94a3b8;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        }
        
        .table td {
            padding: 1rem;
            border-bottom: 1px solid rgba(255, 255, 255, 0.05);
        }
        
        .table tr:hover {
            background: rgba(255, 255, 255, 0.02);
        }
        
        .chart-container {
            height: 300px;
            width: 100%;
            background: rgba(15, 23, 42, 0.6);
            border-radius: 1rem;
            border: 1px solid rgba(255, 255, 255, 0.1);
            overflow: hidden;
        }
        
        /* Custom scrollbar */
        ::-webkit-scrollbar {
            width: 6px;
            height: 6px;
        }
        
        ::-webkit-scrollbar-track {
            background: rgba(255, 255, 255, 0.05);
        }
        
        ::-webkit-scrollbar-thumb {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 3px;
        }
        
        /* Alert styles */
        .alert {
            padding: 1rem;
            border-radius: 0.75rem;
            margin-bottom: 1.5rem;
        }
        
        .alert-success {
            background: rgba(16, 185, 129, 0.2);
            border: 1px solid rgba(16, 185, 129, 0.3);
            color: #10b981;
        }
        
        .alert-error {
            background: rgba(239, 68, 68, 0.2);
            border: 1px solid rgba(239, 68, 68, 0.3);
            color: #ef4444;
        }
        
        /* 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);
        }
        
        .mobile-menu-btn:hover {
            background: rgba(30, 41, 59, 1);
            transform: translateY(-2px);
        }
        
        @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;
        }
    </style>
</head>
<body>
  

    <!-- Include Sidebar -->
    <?php include("nav.php"); ?>

    <!-- Main Content -->
    <div class="main-content">
        <!-- Page Header -->
        <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-4">
                <div>
                    <h1 class="text-2xl lg:text-3xl font-bold bg-gradient-to-r from-blue-400 to-purple-400 bg-clip-text text-transparent">
                        Forex Trading
                    </h1>
                    <p class="text-gray-400 mt-1">
                        <i class="fas fa-chart-line mr-2"></i> Trade major, minor and exotic currency pairs
                    </p>
                </div>
                <div class="flex items-center gap-3">
                    <div class="glass-card px-4 py-2">
                        <span class="text-sm text-gray-400">Balance:</span>
                        <span class="text-xl font-bold text-green-400 ml-2">$<?php echo number_format($user['account_balance'], 2); ?></span>
                    </div>
                </div>
            </div>
        </div>

        <!-- TradingView Widget -->
        <div class="mx-4 mt-4">
            <div class="tradingview-widget-container">
                <div id="tradingview_chart"></div>
                <script type="text/javascript" src="https://s3.tradingview.com/tv.js"></script>
                <script type="text/javascript">
                new TradingView.widget({
                    "width": "100%",
                    "height": 400,
                    "symbol": "FX:EURUSD",
                    "interval": "5",
                    "timezone": "Etc/UTC",
                    "theme": "dark",
                    "style": "1",
                    "locale": "en",
                    "toolbar_bg": "#0f172a",
                    "enable_publishing": false,
                    "allow_symbol_change": true,
                    "container_id": "tradingview_chart"
                });
                </script>
            </div>
        </div>

        <!-- Alert Messages -->
        <?php if ($message): ?>
        <div class="mx-4 mt-4">
            <div class="alert alert-<?php echo $message_type === 'success' ? 'success' : 'error'; ?>">
                <div class="flex items-center gap-3">
                    <i class="fas fa-<?php echo $message_type === 'success' ? 'check-circle' : 'exclamation-circle'; ?>"></i>
                    <span><?php echo htmlspecialchars($message); ?></span>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- Trading Dashboard -->
        <div class="p-6">
            <!-- Market Prices Ticker -->
            <div class="grid grid-cols-2 md:grid-cols-5 gap-3 mb-8">
                <?php
                $major_pairs = ['EUR/USD', 'GBP/USD', 'USD/JPY', 'USD/CHF', 'AUD/USD'];
                foreach ($major_pairs as $pair):
                    $price = getMarketPrice($pair);
                ?>
                <div class="price-ticker">
                    <div class="text-xs text-gray-400"><?php echo $pair; ?></div>
                    <div class="font-bold text-white"><?php echo number_format($price, 5); ?></div>
                </div>
                <?php endforeach; ?>
            </div>

            <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-8">
                <!-- Place Trade Form -->
                <div class="lg:col-span-1">
                    <div class="glass-card p-6">
                        <h3 class="text-xl font-bold mb-6 flex items-center gap-2">
                            <i class="fas fa-hand-pointer text-blue-400"></i>
                            Place New Trade
                        </h3>
                        
                        <form method="POST" action="" class="space-y-5">
                            <!-- Currency Pair -->
                            <div>
                                <label class="form-label">Currency Pair</label>
                                <select name="currency_pair" class="form-input" required>
                                    <option value="EUR/USD">EUR/USD - Euro/US Dollar</option>
                                    <option value="GBP/USD">GBP/USD - British Pound/US Dollar</option>
                                    <option value="USD/JPY">USD/JPY - US Dollar/Japanese Yen</option>
                                    <option value="USD/CHF">USD/CHF - US Dollar/Swiss Franc</option>
                                    <option value="AUD/USD">AUD/USD - Australian Dollar/US Dollar</option>
                                    <option value="USD/CAD">USD/CAD - US Dollar/Canadian Dollar</option>
                                    <option value="NZD/USD">NZD/USD - New Zealand Dollar/US Dollar</option>
                                    <option value="EUR/GBP">EUR/GBP - Euro/British Pound</option>
                                    <option value="EUR/JPY">EUR/JPY - Euro/Japanese Yen</option>
                                    <option value="GBP/JPY">GBP/JPY - British Pound/Japanese Yen</option>
                                </select>
                            </div>
                            
                            <!-- Trade Type -->
                            <div>
                                <label class="form-label">Trade Type</label>
                                <div class="grid grid-cols-2 gap-3">
                                    <button type="button" onclick="setTradeType('BUY')" 
                                            class="btn-buy p-3 rounded-xl text-white font-semibold transition-all hover:scale-105" 
                                            style="background: linear-gradient(135deg, #10b981 0%, #059669 100%);">
                                        <i class="fas fa-arrow-up mr-2"></i>BUY
                                    </button>
                                    <button type="button" onclick="setTradeType('SELL')" 
                                            class="btn-sell p-3 rounded-xl text-white font-semibold transition-all hover:scale-105" 
                                            style="background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);">
                                        <i class="fas fa-arrow-down mr-2"></i>SELL
                                    </button>
                                    <input type="hidden" name="trade_type" id="trade_type" value="BUY">
                                </div>
                            </div>
                            
                            <!-- Amount -->
                            <div>
                                <label class="form-label">Amount ($)</label>
                                <input type="number" name="amount" class="form-input" 
                                       placeholder="Enter amount" min="10" max="<?php echo $user['account_balance']; ?>" 
                                       step="0.01" required>
                                <p class="text-xs text-gray-500 mt-1">Min: $10 | Max: $<?php echo number_format($user['account_balance'], 2); ?></p>
                            </div>
                            
                            <!-- Lot Size -->
                            <div>
                                <label class="form-label">Lot Size</label>
                                <input type="number" name="lot_size" class="form-input" 
                                       placeholder="0.01 to 10.00" min="0.01" max="10.00" 
                                       step="0.01" value="0.01" required>
                            </div>
                            
                            <!-- Stop Loss (Optional) -->
                            <div>
                                <label class="form-label">Stop Loss (Optional)</label>
                                <input type="number" name="stop_loss" class="form-input" 
                                       placeholder="Enter stop loss price" step="0.00001">
                            </div>
                            
                            <!-- Take Profit (Optional) -->
                            <div>
                                <label class="form-label">Take Profit (Optional)</label>
                                <input type="number" name="take_profit" class="form-input" 
                                       placeholder="Enter take profit price" step="0.00001">
                            </div>
                            
                            <!-- Submit Button -->
                            <button type="submit" name="place_trade" class="btn-primary">
                                <i class="fas fa-chart-line mr-2"></i>
                                Place Trade
                            </button>
                        </form>
                        
                        <div class="mt-4 text-xs text-gray-500 text-center">
                            <i class="fas fa-info-circle mr-1"></i>
                            All trades require admin approval before execution
                        </div>
                    </div>
                </div>
                
                <!-- Trade Statistics -->
                <div class="lg:col-span-2">
                    <div class="glass-card p-6 mb-6">
                        <h3 class="text-xl font-bold mb-6 flex items-center gap-2">
                            <i class="fas fa-chart-pie text-purple-400"></i>
                            Trading Statistics
                        </h3>
                        
                        <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
                            <div class="text-center p-4 bg-gray-800/50 rounded-xl">
                                <div class="text-2xl font-bold text-blue-400"><?php echo $stats['total'] ?? 0; ?></div>
                                <div class="text-xs text-gray-400 mt-1">Total Trades</div>
                            </div>
                            <div class="text-center p-4 bg-gray-800/50 rounded-xl">
                                <div class="text-2xl font-bold text-green-400"><?php echo $stats['open'] ?? 0; ?></div>
                                <div class="text-xs text-gray-400 mt-1">Open Trades</div>
                            </div>
                            <div class="text-center p-4 bg-gray-800/50 rounded-xl">
                                <div class="text-2xl font-bold text-purple-400"><?php echo $stats['win_rate']; ?>%</div>
                                <div class="text-xs text-gray-400 mt-1">Win Rate</div>
                            </div>
                            <div class="text-center p-4 bg-gray-800/50 rounded-xl">
                                <div class="text-2xl font-bold <?php echo ($stats['total_profit'] + $stats['total_loss']) >= 0 ? 'text-green-400' : 'text-red-400'; ?>">
                                    $<?php echo number_format(($stats['total_profit'] ?? 0) + ($stats['total_loss'] ?? 0), 2); ?>
                                </div>
                                <div class="text-xs text-gray-400 mt-1">Net P/L</div>
                            </div>
                        </div>
                        
                        <div class="grid grid-cols-2 gap-4 mt-4">
                            <div class="p-4 bg-gray-800/30 rounded-xl">
                                <div class="text-sm text-gray-400 mb-1">Total Profit</div>
                                <div class="text-xl font-bold text-green-400">$<?php echo number_format($stats['total_profit'] ?? 0, 2); ?></div>
                            </div>
                            <div class="p-4 bg-gray-800/30 rounded-xl">
                                <div class="text-sm text-gray-400 mb-1">Total Loss</div>
                                <div class="text-xl font-bold text-red-400">$<?php echo number_format(abs($stats['total_loss'] ?? 0), 2); ?></div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Trading Tips -->
                    <div class="glass-card p-6">
                        <h4 class="font-bold mb-4 flex items-center gap-2">
                            <i class="fas fa-lightbulb text-yellow-400"></i>
                            Trading Tips
                        </h4>
                        <ul class="space-y-2 text-sm text-gray-400">
                            <li class="flex items-start gap-2">
                                <i class="fas fa-check-circle text-green-400 mt-0.5"></i>
                                <span>Always use stop loss to manage your risk</span>
                            </li>
                            <li class="flex items-start gap-2">
                                <i class="fas fa-check-circle text-green-400 mt-0.5"></i>
                                <span>Start with small lot sizes (0.01) until you gain experience</span>
                            </li>
                            <li class="flex items-start gap-2">
                                <i class="fas fa-check-circle text-green-400 mt-0.5"></i>
                                <span>Never risk more than 1-2% of your account on a single trade</span>
                            </li>
                            <li class="flex items-start gap-2">
                                <i class="fas fa-check-circle text-green-400 mt-0.5"></i>
                                <span>Keep up with economic news that affects currency pairs</span>
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
            
            <!-- Trade History -->
            <div class="glass-card p-6">
                <div class="flex items-center justify-between mb-6">
                    <h3 class="text-xl font-bold flex items-center gap-2">
                        <i class="fas fa-history text-blue-400"></i>
                        Recent Trades
                    </h3>
                    <a href="trade-history.php" class="text-sm text-blue-400 hover:text-blue-300 flex items-center gap-1">
                        View Full History <i class="fas fa-arrow-right text-xs"></i>
                    </a>
                </div>
                
                <?php if ($trades_result->num_rows > 0): ?>
                <div class="table-container">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>Date</th>
                                <th>Pair</th>
                                <th>Type</th>
                                <th>Amount</th>
                                <th>Lot Size</th>
                                <th>Entry</th>
                                <th>Exit</th>
                                <th>P/L</th>
                                <th>Status</th>
                                <th>Profit/Loss</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php while ($trade = $trades_result->fetch_assoc()): 
                                $status_class = '';
                                switch ($trade['status']) {
                                    case 'open':
                                        $status_class = 'status-open';
                                        break;
                                    case 'closed':
                                        $status_class = 'status-closed';
                                        break;
                                    case 'pending':
                                        $status_class = 'status-pending';
                                        break;
                                    case 'cancelled':
                                        $status_class = 'status-cancelled';
                                        break;
                                }
                                
                                $admin_class = '';
                                $admin_text = '';
                                switch ($trade['admin_action']) {
                                    case 'profit':
                                        $admin_class = 'profit-badge';
                                        $admin_text = 'Profit';
                                        break;
                                    case 'loss':
                                        $admin_class = 'loss-badge';
                                        $admin_text = 'Loss';
                                        break;
                                    default:
                                        $admin_class = 'pending-badge';
                                        $admin_text = 'Pending';
                                }
                            ?>
                            <tr>
                                <td class="text-sm"><?php echo date('M d, H:i', strtotime($trade['created_at'])); ?></td>
                                <td class="font-medium"><?php echo htmlspecialchars($trade['currency_pair']); ?></td>
                                <td>
                                    <span class="<?php echo $trade['trade_type'] == 'BUY' ? 'text-green-400' : 'text-red-400'; ?> font-semibold">
                                        <?php echo $trade['trade_type']; ?>
                                    </span>
                                </td>
                                <td>$<?php echo number_format($trade['amount'], 2); ?></td>
                                <td><?php echo $trade['lot_size']; ?></td>
                                <td><?php echo number_format($trade['entry_price'], 5); ?></td>
                                <td>
                                    <?php echo $trade['exit_price'] ? number_format($trade['exit_price'], 5) : '-'; ?>
                                </td>
                                <td>
                                    <?php if ($trade['profit_loss'] !== null): ?>
                                        <span class="<?php echo $trade['profit_loss'] >= 0 ? 'text-green-400' : 'text-red-400'; ?> font-semibold">
                                            <?php echo $trade['profit_loss'] >= 0 ? '+' : ''; ?>$<?php echo number_format($trade['profit_loss'], 2); ?>
                                        </span>
                                    <?php else: ?>
                                        -
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <span class="status-badge <?php echo $status_class; ?>">
                                        <?php echo ucfirst($trade['status']); ?>
                                    </span>
                                </td>
                                <td>
                                    <span class="<?php echo $admin_class; ?>">
                                        <?php echo $admin_text; ?>
                                    </span>
                                </td>
                            </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
                <?php else: ?>
                <div class="text-center py-12">
                    <div class="w-20 h-20 bg-gray-800/50 rounded-full flex items-center justify-center mx-auto mb-4">
                        <i class="fas fa-chart-line text-gray-600 text-3xl"></i>
                    </div>
                    <h4 class="text-white font-medium mb-1">No trades yet</h4>
                    <p class="text-gray-500 text-sm">Place your first trade to get started</p>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

<script>
    // Mobile menu functionality - Simplified version
    document.addEventListener('DOMContentLoaded', function() {
        const menuToggle = document.getElementById('menuToggle');
        const closeSidebar = document.getElementById('closeSidebar');
        const sidebar = document.getElementById('sidebar');
        const sidebarOverlay = document.getElementById('sidebarOverlay');
        const body = document.body;
        
        // Check if elements exist
        if (!menuToggle || !closeSidebar || !sidebar || !sidebarOverlay) {
            console.error('Sidebar elements not found');
            return;
        }

        // Function to open sidebar
        function openSidebar() {
            sidebar.classList.add('active');
            sidebarOverlay.classList.add('active');
            body.style.overflow = 'hidden';
        }

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

        // Toggle sidebar on menu button click
        menuToggle.addEventListener('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            
            if (sidebar.classList.contains('active')) {
                closeSidebarFunc();
            } else {
                openSidebar();
            }
        });

        // Close sidebar when clicking close button
        closeSidebar.addEventListener('click', function(e) {
            e.preventDefault();
            closeSidebarFunc();
        });

        // Close sidebar when clicking overlay
        sidebarOverlay.addEventListener('click', closeSidebarFunc);

        // Close sidebar when clicking a nav link on mobile
        document.querySelectorAll('.nav-item').forEach(item => {
            item.addEventListener('click', function() {
                if (window.innerWidth < 1024) {
                    // Small delay to allow navigation
                    setTimeout(closeSidebarFunc, 200);
                }
            });
        });

        // Handle window resize
        window.addEventListener('resize', function() {
            if (window.innerWidth >= 1024) {
                // Desktop: show sidebar, hide overlay
                sidebar.classList.add('active');
                sidebarOverlay.classList.remove('active');
                body.style.overflow = '';
            } else {
                // Mobile: hide sidebar by default
                sidebar.classList.remove('active');
                sidebarOverlay.classList.remove('active');
                body.style.overflow = '';
            }
        });

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

        // Initialize sidebar state on load
        if (window.innerWidth >= 1024) {
            sidebar.classList.add('active');
        } else {
            sidebar.classList.remove('active');
        }

        // Set active nav item based on current page
        const currentPage = window.location.pathname.split('/').pop() || 'forex_trading.php';
        document.querySelectorAll('.nav-item').forEach(nav => {
            const href = nav.getAttribute('href');
            if (href && href.includes(currentPage)) {
                nav.classList.add('active');
            }
        });
    });

    // Your existing functions
    function setTradeType(type) {
        document.getElementById('trade_type').value = type;
    }

    // Form validation
    document.querySelector('form')?.addEventListener('submit', function(e) {
        const amount = parseFloat(document.querySelector('input[name="amount"]').value);
        const balance = <?php echo $user['account_balance']; ?>;
        
        if (amount > balance) {
            e.preventDefault();
            alert('Insufficient balance!');
        }
    });

    // Live price updates (simulated)
    setInterval(function() {
        const priceElements = document.querySelectorAll('.price-ticker .font-bold');
        priceElements.forEach(function(el) {
            const currentPrice = parseFloat(el.textContent);
            const change = (Math.random() - 0.5) * 0.001;
            const newPrice = currentPrice + change;
            el.textContent = newPrice.toFixed(5);
            
            // Color change based on price movement
            if (change > 0) {
                el.classList.remove('text-red-400');
                el.classList.add('text-green-400');
            } else if (change < 0) {
                el.classList.remove('text-green-400');
                el.classList.add('text-red-400');
            }
        });
    }, 3000);
</script>

</body>
</html>