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

// Function to get market price (simulated) - reused from trade.php
function getMarketPrice($pair) {
    $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;
}

// Handle filters
$status_filter = isset($_GET['status']) ? $_GET['status'] : '';
$type_filter = isset($_GET['type']) ? $_GET['type'] : '';
$pair_filter = isset($_GET['pair']) ? $_GET['pair'] : '';
$date_from = isset($_GET['date_from']) ? $_GET['date_from'] : '';
$date_to = isset($_GET['date_to']) ? $_GET['date_to'] : '';

// Build query with filters
$where_conditions = ["user_id = ?"];
$params = [$user_id];
$param_types = "i";

if (!empty($status_filter) && $status_filter != 'all') {
    $where_conditions[] = "status = ?";
    $params[] = $status_filter;
    $param_types .= 's';
}

if (!empty($type_filter) && $type_filter != 'all') {
    $where_conditions[] = "trade_type = ?";
    $params[] = $type_filter;
    $param_types .= 's';
}

if (!empty($pair_filter) && $pair_filter != 'all') {
    $where_conditions[] = "currency_pair = ?";
    $params[] = $pair_filter;
    $param_types .= 's';
}

if (!empty($date_from)) {
    $where_conditions[] = "DATE(created_at) >= ?";
    $params[] = $date_from;
    $param_types .= 's';
}

if (!empty($date_to)) {
    $where_conditions[] = "DATE(created_at) <= ?";
    $params[] = $date_to;
    $param_types .= 's';
}

$where_clause = implode(" AND ", $where_conditions);

// Get total count for pagination
$count_query = "SELECT COUNT(*) as total FROM forex_trades WHERE $where_clause";
$count_stmt = $conn->prepare($count_query);
$count_stmt->bind_param($param_types, ...$params);
$count_stmt->execute();
$count_result = $count_stmt->get_result();
$total_trades = $count_result->fetch_assoc()['total'];
$count_stmt->close();

// Pagination
$per_page = 20;
$total_pages = ceil($total_trades / $per_page);
$current_page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$offset = ($current_page - 1) * $per_page;

// Fetch trades with pagination
$query = "SELECT * FROM forex_trades 
          WHERE $where_clause 
          ORDER BY created_at DESC 
          LIMIT ? OFFSET ?";

$params[] = $per_page;
$params[] = $offset;
$param_types .= 'ii';

$trades_stmt = $conn->prepare($query);
$trades_stmt->bind_param($param_types, ...$params);
$trades_stmt->execute();
$trades_result = $trades_stmt->get_result();
$trades_stmt->close();

// Get unique currency pairs for filter
$pairs_query = "SELECT DISTINCT currency_pair FROM forex_trades WHERE user_id = ? ORDER BY currency_pair";
$pairs_stmt = $conn->prepare($pairs_query);
$pairs_stmt->bind_param("i", $user_id);
$pairs_stmt->execute();
$pairs_result = $pairs_stmt->get_result();
$currency_pairs = [];
while ($row = $pairs_result->fetch_assoc()) {
    $currency_pairs[] = $row['currency_pair'];
}
$pairs_stmt->close();

// Calculate comprehensive statistics
$stats_query = "SELECT 
    COUNT(*) as total_trades,
    SUM(CASE WHEN status = 'open' THEN 1 ELSE 0 END) as open_trades,
    SUM(CASE WHEN status = 'closed' THEN 1 ELSE 0 END) as closed_trades,
    SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending_trades,
    SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) as cancelled_trades,
    SUM(CASE WHEN status = 'closed' AND profit_loss > 0 THEN 1 ELSE 0 END) as winning_trades,
    SUM(CASE WHEN status = 'closed' AND profit_loss < 0 THEN 1 ELSE 0 END) as losing_trades,
    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(amount) as total_invested,
    AVG(CASE WHEN status = 'closed' THEN profit_loss ELSE NULL END) as avg_profit_loss,
    MAX(profit_loss) as biggest_win,
    MIN(profit_loss) as biggest_loss,
    SUM(CASE WHEN admin_action = 'profit' THEN 1 ELSE 0 END) as admin_profit,
    SUM(CASE WHEN admin_action = 'loss' THEN 1 ELSE 0 END) as admin_loss
    FROM forex_trades 
    WHERE user_id = ?";

$stats_stmt = $conn->prepare($stats_query);
$stats_stmt->bind_param("i", $user_id);
$stats_stmt->execute();
$stats_result = $stats_stmt->get_result();
$stats = $stats_result->fetch_assoc();
$stats_stmt->close();

// Calculate win rate
$stats['win_rate'] = ($stats['closed_trades'] > 0) ? 
    round(($stats['winning_trades'] / $stats['closed_trades']) * 100, 2) : 0;

// Calculate net profit/loss
$stats['net_profit_loss'] = ($stats['total_profit'] ?? 0) + ($stats['total_loss'] ?? 0);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Trade History - <?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%);
        }
        
        * {
            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);
        }
        
        .stat-card {
            background: rgba(15, 23, 42, 0.6);
            border: 1px solid rgba(255, 255, 255, 0.05);
            border-radius: 1rem;
            padding: 1.25rem;
        }
        
        .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;
        }
        
        .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);
        }
        
        .filter-input {
            background: rgba(15, 23, 42, 0.6);
            border: 1px solid rgba(255, 255, 255, 0.1);
            border-radius: 0.75rem;
            padding: 0.5rem 1rem;
            color: white;
            width: 100%;
            font-size: 0.875rem;
        }
        
        .filter-input:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.2);
        }
        
        .filter-label {
            display: block;
            margin-bottom: 0.25rem;
            font-size: 0.75rem;
            font-weight: 500;
            color: #94a3b8;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            font-weight: 600;
            padding: 0.5rem 1.25rem;
            border-radius: 0.75rem;
            transition: all 0.2s;
            border: none;
            cursor: pointer;
            font-size: 0.875rem;
        }
        
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px rgba(102, 126, 234, 0.4);
        }
        
        .btn-secondary {
            background: rgba(255, 255, 255, 0.05);
            color: #e2e8f0;
            font-weight: 500;
            padding: 0.5rem 1.25rem;
            border-radius: 0.75rem;
            transition: all 0.2s;
            border: 1px solid rgba(255, 255, 255, 0.1);
            cursor: pointer;
            font-size: 0.875rem;
        }
        
        .btn-secondary:hover {
            background: rgba(255, 255, 255, 0.1);
        }
        
       /* 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;
        }
        @media (min-width: 1024px) {
            .mobile-menu-btn {
                display: none;
            }
        }
        
        /* 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;
        }
    </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">
                        Trade History
                    </h1>
                    <p class="text-gray-400 mt-1">
                        <i class="fas fa-history mr-2"></i> View your complete trading history and performance
                    </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>
                    <a href="trade.php" class="btn-primary">
                        <i class="fas fa-plus mr-2"></i>New Trade
                    </a>
                </div>
            </div>
        </div>

        <!-- Statistics Cards -->
        <div class="grid grid-cols-2 lg:grid-cols-4 gap-4 mx-4 mt-6">
            <div class="stat-card">
                <p class="text-gray-400 text-sm">Total Trades</p>
                <p class="text-2xl font-bold text-white"><?php echo $stats['total_trades'] ?? 0; ?></p>
                <div class="flex gap-2 mt-2 text-xs">
                    <span class="text-green-400">Open: <?php echo $stats['open_trades'] ?? 0; ?></span>
                    <span class="text-blue-400">Closed: <?php echo $stats['closed_trades'] ?? 0; ?></span>
                </div>
            </div>
            
            <div class="stat-card">
                <p class="text-gray-400 text-sm">Win Rate</p>
                <p class="text-2xl font-bold text-purple-400"><?php echo $stats['win_rate']; ?>%</p>
                <div class="flex gap-2 mt-2 text-xs">
                    <span class="text-green-400">Wins: <?php echo $stats['winning_trades'] ?? 0; ?></span>
                    <span class="text-red-400">Losses: <?php echo $stats['losing_trades'] ?? 0; ?></span>
                </div>
            </div>
            
            <div class="stat-card">
                <p class="text-gray-400 text-sm">Net Profit/Loss</p>
                <p class="text-2xl font-bold <?php echo $stats['net_profit_loss'] >= 0 ? 'text-green-400' : 'text-red-400'; ?>">
                    $<?php echo number_format(abs($stats['net_profit_loss']), 2); ?>
                </p>
                <div class="flex gap-2 mt-2 text-xs">
                    <span class="text-green-400">+$<?php echo number_format($stats['total_profit'] ?? 0, 2); ?></span>
                    <span class="text-red-400">-$<?php echo number_format(abs($stats['total_loss'] ?? 0), 2); ?></span>
                </div>
            </div>
            
            <div class="stat-card">
                <p class="text-gray-400 text-sm">Total Invested</p>
                <p class="text-2xl font-bold text-white">$<?php echo number_format($stats['total_invested'] ?? 0, 2); ?></p>
                <div class="flex gap-2 mt-2 text-xs">
                    <span class="text-yellow-400">Avg P/L: $<?php echo number_format(abs($stats['avg_profit_loss'] ?? 0), 2); ?></span>
                </div>
            </div>
        </div>

        <!-- Filter Section -->
        <div class="glass-card mx-4 mt-6 p-6">
            <h3 class="text-lg font-semibold mb-4 flex items-center gap-2">
                <i class="fas fa-filter text-blue-400"></i>
                Filter Trades
            </h3>
            
            <form method="GET" action="" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4">
                <!-- Status Filter -->
                <div>
                    <label class="filter-label">Status</label>
                    <select name="status" class="filter-input">
                        <option value="all" <?php echo $status_filter == 'all' ? 'selected' : ''; ?>>All Status</option>
                        <option value="pending" <?php echo $status_filter == 'pending' ? 'selected' : ''; ?>>Pending</option>
                        <option value="open" <?php echo $status_filter == 'open' ? 'selected' : ''; ?>>Open</option>
                        <option value="closed" <?php echo $status_filter == 'closed' ? 'selected' : ''; ?>>Closed</option>
                        <option value="cancelled" <?php echo $status_filter == 'cancelled' ? 'selected' : ''; ?>>Cancelled</option>
                    </select>
                </div>
                
                <!-- Trade Type Filter -->
                <div>
                    <label class="filter-label">Trade Type</label>
                    <select name="type" class="filter-input">
                        <option value="all" <?php echo $type_filter == 'all' ? 'selected' : ''; ?>>All Types</option>
                        <option value="BUY" <?php echo $type_filter == 'BUY' ? 'selected' : ''; ?>>BUY</option>
                        <option value="SELL" <?php echo $type_filter == 'SELL' ? 'selected' : ''; ?>>SELL</option>
                    </select>
                </div>
                
                <!-- Currency Pair Filter -->
                <div>
                    <label class="filter-label">Currency Pair</label>
                    <select name="pair" class="filter-input">
                        <option value="all" <?php echo $pair_filter == 'all' ? 'selected' : ''; ?>>All Pairs</option>
                        <?php foreach ($currency_pairs as $pair): ?>
                        <option value="<?php echo htmlspecialchars($pair); ?>" <?php echo $pair_filter == $pair ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($pair); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <!-- Date From -->
                <div>
                    <label class="filter-label">Date From</label>
                    <input type="date" name="date_from" value="<?php echo $date_from; ?>" class="filter-input">
                </div>
                
                <!-- Date To -->
                <div>
                    <label class="filter-label">Date To</label>
                    <input type="date" name="date_to" value="<?php echo $date_to; ?>" class="filter-input">
                </div>
                
                <!-- Filter Actions -->
                <div class="md:col-span-2 lg:col-span-5 flex justify-end gap-2 mt-2">
                    <button type="submit" class="btn-primary">
                        <i class="fas fa-search mr-2"></i>Apply Filters
                    </button>
                    <a href="trade_history.php" class="btn-secondary">
                        <i class="fas fa-times mr-2"></i>Clear
                    </a>
                </div>
            </form>
        </div>

        <!-- Trades Table -->
        <div class="glass-card mx-4 my-6 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-list text-blue-400"></i>
                    Trade History
                </h3>
                <div class="text-sm text-gray-400">
                    Showing <?php echo $trades_result->num_rows; ?> of <?php echo $total_trades; ?> trades
                </div>
            </div>
            
            <?php if ($trades_result->num_rows > 0): ?>
            <div class="table-container">
                <table class="table">
                    <thead>
                        <tr>
                            <th>Date/Time</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, Y 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 number_format($trade['lot_size'], 2); ?></td>
                            <td class="font-mono text-sm"><?php echo number_format($trade['entry_price'], 5); ?></td>
                            <td class="font-mono text-sm">
                                <?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(abs($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>
            
            <!-- Pagination -->
            <?php if ($total_pages > 1): ?>
            <div class="flex flex-col sm:flex-row items-center justify-between gap-4 mt-6">
                <div class="text-sm text-gray-400">
                    Page <?php echo $current_page; ?> of <?php echo $total_pages; ?>
                </div>
                <div class="flex gap-2">
                    <?php if ($current_page > 1): ?>
                    <a href="?page=<?php echo $current_page - 1; ?><?php echo !empty($_GET) ? '&' . http_build_query(array_diff_key($_GET, ['page' => ''])) : ''; ?>" 
                       class="btn-secondary">
                        <i class="fas fa-chevron-left mr-2"></i>Previous
                    </a>
                    <?php endif; ?>
                    
                    <?php if ($current_page < $total_pages): ?>
                    <a href="?page=<?php echo $current_page + 1; ?><?php echo !empty($_GET) ? '&' . http_build_query(array_diff_key($_GET, ['page' => ''])) : ''; ?>" 
                       class="btn-secondary">
                        Next<i class="fas fa-chevron-right ml-2"></i>
                    </a>
                    <?php endif; ?>
                </div>
            </div>
            <?php endif; ?>
            
            <?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 found</h4>
                <p class="text-gray-500 text-sm mb-4"><?php echo $total_trades > 0 ? 'Try adjusting your filters' : 'Start trading to see your history'; ?></p>
                <?php if ($total_trades == 0): ?>
                <a href="trade.php" class="btn-primary inline-flex">
                    <i class="fas fa-plus mr-2"></i>Place Your First Trade
                </a>
                <?php endif; ?>
            </div>
            <?php endif; ?>
        </div>

        <!-- Performance Summary -->
        <?php if ($stats['closed_trades'] > 0): ?>
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mx-4 mb-6">
            <!-- Biggest Win -->
            <div class="stat-card">
                <p class="text-gray-400 text-sm">Biggest Win</p>
                <p class="text-2xl font-bold text-green-400">
                    +$<?php echo number_format(abs($stats['biggest_win'] ?? 0), 2); ?>
                </p>
            </div>
            
            <!-- Biggest Loss -->
            <div class="stat-card">
                <p class="text-gray-400 text-sm">Biggest Loss</p>
                <p class="text-2xl font-bold text-red-400">
                    -$<?php echo number_format(abs($stats['biggest_loss'] ?? 0), 2); ?>
                </p>
            </div>
            
            <!-- Admin Decisions -->
            <div class="stat-card">
                <p class="text-gray-400 text-sm">Total Profit/Loss</p>
                <div class="flex gap-4 mt-2">
                    <span class="text-green-400">Profit: <?php echo $stats['admin_profit'] ?? 0; ?></span>
                    <span class="text-red-400">Loss: <?php echo $stats['admin_loss'] ?? 0; ?></span>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>

    <script>
        // Mobile menu functionality
        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;
            
            if (!menuToggle || !closeSidebar || !sidebar || !sidebarOverlay) {
                console.error('Sidebar elements not found');
                return;
            }

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

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

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

            closeSidebar.addEventListener('click', function(e) {
                e.preventDefault();
                closeSidebarFunc();
            });

            sidebarOverlay.addEventListener('click', closeSidebarFunc);

            document.querySelectorAll('.nav-item').forEach(item => {
                item.addEventListener('click', function() {
                    if (window.innerWidth < 1024) {
                        setTimeout(closeSidebarFunc, 200);
                    }
                });
            });

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

            if (window.innerWidth >= 1024) {
                sidebar.classList.add('active');
            } else {
                sidebar.classList.remove('active');
            }

            // Set active nav item
            const currentPage = 'trade_history.php';
            document.querySelectorAll('.nav-item').forEach(nav => {
                const href = nav.getAttribute('href');
                if (href && href.includes('trade')) {
                    nav.classList.add('active');
                }
            });
        });
    </script>
</body>
</html>