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

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

// Fetch admin data from admin_table
$admin_id = $_SESSION['admin_id'];
$query = "SELECT * FROM admin_table WHERE id = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param("i", $admin_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    session_destroy();
    header('Location: ../admin-login.php');
    exit();
}

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

// Ensure forex_trades table exists with proper structure
$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,
        updated_at TIMESTAMP NULL DEFAULT NULL ON UPDATE 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)
    )
");

// Initialize variables
$message = '';
$message_type = '';
$current_trade = null;
$edit_mode = false;
$show_actions_modal = false;
$selected_trade = null;

// Handle Trade Actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action_type'])) {
        $action_type = $_POST['action_type'];
        $trade_id = intval($_POST['trade_id']);
        
        switch($action_type) {
            case 'approve_trade':
                // Approve pending trade
                $trade_id = intval($_POST['trade_id']);
                
                // Get trade details
                $trade_query = "SELECT * FROM forex_trades WHERE id = ?";
                $trade_stmt = $conn->prepare($trade_query);
                $trade_stmt->bind_param("i", $trade_id);
                $trade_stmt->execute();
                $trade_result = $trade_stmt->get_result();
                $trade = $trade_result->fetch_assoc();
                $trade_stmt->close();
                
                if ($trade) {
                    // Update trade status to open
                    $update_query = "UPDATE forex_trades SET status = 'open', updated_at = NOW() WHERE id = ?";
                    $update_stmt = $conn->prepare($update_query);
                    $update_stmt->bind_param("i", $trade_id);
                    
                    if ($update_stmt->execute()) {
                        // Create notification for user
                        $notif_title = "Trade Approved";
                        $notif_message = "Your {$trade['trade_type']} trade of {$trade['currency_pair']} for $" . number_format($trade['amount'], 2) . " has been approved and is now open.";
                        
                        $notif_query = "INSERT INTO notifications (user_id, notification_type, title, message) 
                                       VALUES (?, 'trade', ?, ?)";
                        $notif_stmt = $conn->prepare($notif_query);
                        $notif_stmt->bind_param("iss", $trade['user_id'], $notif_title, $notif_message);
                        $notif_stmt->execute();
                        $notif_stmt->close();
                        
                        $message = "Trade approved successfully!";
                        $message_type = "success";
                    } else {
                        $message = "Error approving trade: " . $update_stmt->error;
                        $message_type = "error";
                    }
                    $update_stmt->close();
                }
                break;
                
            case 'reject_trade':
                // Reject pending trade and refund
                $trade_id = intval($_POST['trade_id']);
                $rejection_reason = trim($_POST['rejection_reason'] ?? 'Trade rejected by administrator');
                
                // Start transaction
                $conn->begin_transaction();
                
                try {
                    // Get trade details
                    $trade_query = "SELECT * FROM forex_trades WHERE id = ? FOR UPDATE";
                    $trade_stmt = $conn->prepare($trade_query);
                    $trade_stmt->bind_param("i", $trade_id);
                    $trade_stmt->execute();
                    $trade_result = $trade_stmt->get_result();
                    $trade = $trade_result->fetch_assoc();
                    $trade_stmt->close();
                    
                    if (!$trade) {
                        throw new Exception("Trade not found");
                    }
                    
                    // Refund amount to user
                    $refund_query = "UPDATE users SET account_balance = account_balance + ? WHERE id = ?";
                    $refund_stmt = $conn->prepare($refund_query);
                    $refund_stmt->bind_param("di", $trade['amount'], $trade['user_id']);
                    $refund_stmt->execute();
                    $refund_stmt->close();
                    
                    // Update trade status to cancelled
                    $update_query = "UPDATE forex_trades SET status = 'cancelled', admin_action = 'pending', updated_at = NOW() WHERE id = ?";
                    $update_stmt = $conn->prepare($update_query);
                    $update_stmt->bind_param("i", $trade_id);
                    $update_stmt->execute();
                    $update_stmt->close();
                    
                    // Create notification for user
                    $notif_title = "Trade Rejected";
                    $notif_message = "Your {$trade['trade_type']} trade of {$trade['currency_pair']} for $" . number_format($trade['amount'], 2) . " has been rejected. Reason: " . $rejection_reason . ". Amount has been refunded.";
                    
                    $notif_query = "INSERT INTO notifications (user_id, notification_type, title, message) 
                                   VALUES (?, 'trade', ?, ?)";
                    $notif_stmt = $conn->prepare($notif_query);
                    $notif_stmt->bind_param("iss", $trade['user_id'], $notif_title, $notif_message);
                    $notif_stmt->execute();
                    $notif_stmt->close();
                    
                    $conn->commit();
                    
                    $message = "Trade rejected and amount refunded successfully!";
                    $message_type = "success";
                    
                } catch (Exception $e) {
                    $conn->rollback();
                    $message = "Error rejecting trade: " . $e->getMessage();
                    $message_type = "error";
                }
                break;
                
            case 'close_trade':
                // Close an open trade with profit/loss
                $trade_id = intval($_POST['trade_id']);
                $exit_price = floatval($_POST['exit_price']);
                $admin_action = $_POST['admin_action']; // 'profit' or 'loss'
                
                // Start transaction
                $conn->begin_transaction();
                
                try {
                    // Get trade details
                    $trade_query = "SELECT * FROM forex_trades WHERE id = ? FOR UPDATE";
                    $trade_stmt = $conn->prepare($trade_query);
                    $trade_stmt->bind_param("i", $trade_id);
                    $trade_stmt->execute();
                    $trade_result = $trade_stmt->get_result();
                    $trade = $trade_result->fetch_assoc();
                    $trade_stmt->close();
                    
                    if (!$trade) {
                        throw new Exception("Trade not found");
                    }
                    
                    // Calculate profit/loss based on admin action
                    $amount = $trade['amount'];
                    $profit_loss = 0;
                    
                    if ($admin_action == 'profit') {
                        // For profit, check if amount or percentage is provided
                        if (isset($_POST['profit_amount']) && !empty($_POST['profit_amount'])) {
                            $profit_loss = floatval($_POST['profit_amount']);
                        } elseif (isset($_POST['profit_percentage']) && !empty($_POST['profit_percentage'])) {
                            $profit_percentage = floatval($_POST['profit_percentage']);
                            $profit_loss = ($amount * $profit_percentage) / 100;
                        } else {
                            throw new Exception("Please enter either a profit amount or percentage");
                        }
                        
                        if ($profit_loss <= 0) {
                            throw new Exception("Profit amount must be greater than zero");
                        }
                    } elseif ($admin_action == 'loss') {
                        // For loss, check if amount or percentage is provided
                        if (isset($_POST['loss_amount']) && !empty($_POST['loss_amount'])) {
                            $loss_amount = floatval($_POST['loss_amount']);
                            if ($loss_amount > $amount) {
                                throw new Exception("Loss amount cannot exceed the trade amount of $" . number_format($amount, 2));
                            }
                            $profit_loss = -$loss_amount;
                        } elseif (isset($_POST['loss_percentage']) && !empty($_POST['loss_percentage'])) {
                            $loss_percentage = floatval($_POST['loss_percentage']);
                            if ($loss_percentage > 100) {
                                throw new Exception("Loss percentage cannot exceed 100%");
                            }
                            $profit_loss = -($amount * $loss_percentage) / 100;
                        } else {
                            throw new Exception("Please enter either a loss amount or percentage");
                        }
                        
                        if ($profit_loss >= 0) {
                            throw new Exception("Loss amount must be greater than zero");
                        }
                    } else {
                        throw new Exception("Please select whether this trade resulted in profit or loss");
                    }
                    
                    // Update ONLY user's account_balance with profit/loss (no total_earnings update)
                    $balance_query = "UPDATE users SET account_balance = account_balance + ? WHERE id = ?";
                    $balance_stmt = $conn->prepare($balance_query);
                    $balance_stmt->bind_param("di", $profit_loss, $trade['user_id']);
                    $balance_stmt->execute();
                    $balance_stmt->close();
                    
                    // Update trade
                    $update_query = "UPDATE forex_trades SET 
                                    exit_price = ?, 
                                    profit_loss = ?,
                                    status = 'closed',
                                    admin_action = ?,
                                    closed_at = NOW(),
                                    updated_at = NOW() 
                                    WHERE id = ?";
                    $update_stmt = $conn->prepare($update_query);
                    $update_stmt->bind_param("ddsi", $exit_price, $profit_loss, $admin_action, $trade_id);
                    $update_stmt->execute();
                    $update_stmt->close();
                    
                    // Create notification for user
                    $notif_title = "Trade Closed";
                    $notif_message = "Your {$trade['trade_type']} trade of {$trade['currency_pair']} has been closed with " . 
                                    ($profit_loss >= 0 ? "profit" : "loss") . " of $" . number_format(abs($profit_loss), 2) . ".";
                    
                    $notif_query = "INSERT INTO notifications (user_id, notification_type, title, message) 
                                   VALUES (?, 'trade', ?, ?)";
                    $notif_stmt = $conn->prepare($notif_query);
                    $notif_stmt->bind_param("iss", $trade['user_id'], $notif_title, $notif_message);
                    $notif_stmt->execute();
                    $notif_stmt->close();
                    
                    $conn->commit();
                    
                    $message = "Trade closed successfully! " . ($profit_loss >= 0 ? "Profit" : "Loss") . ": $" . number_format(abs($profit_loss), 2);
                    $message_type = "success";
                    
                } catch (Exception $e) {
                    $conn->rollback();
                    $message = "Error closing trade: " . $e->getMessage();
                    $message_type = "error";
                }
                break;
                
            case 'delete_trade':
                // Delete a trade (use with caution)
                $trade_id = intval($_POST['trade_id']);
                $confirm_delete = isset($_POST['confirm_delete']) ? true : false;
                
                if (!$confirm_delete) {
                    $message = "Please confirm deletion";
                    $message_type = "error";
                    break;
                }
                
                // Check if trade is pending (only allow deletion of pending trades)
                $check_query = "SELECT status, user_id, amount FROM forex_trades WHERE id = ?";
                $check_stmt = $conn->prepare($check_query);
                $check_stmt->bind_param("i", $trade_id);
                $check_stmt->execute();
                $check_result = $check_stmt->get_result();
                $trade = $check_result->fetch_assoc();
                $check_stmt->close();
                
                if (!$trade) {
                    $message = "Trade not found";
                    $message_type = "error";
                    break;
                }
                
                if ($trade['status'] != 'pending' && $trade['status'] != 'cancelled') {
                    $message = "Only pending or cancelled trades can be deleted";
                    $message_type = "error";
                    break;
                }
                
                // If pending, refund amount
                if ($trade['status'] == 'pending') {
                    $refund_query = "UPDATE users SET account_balance = account_balance + ? WHERE id = ?";
                    $refund_stmt = $conn->prepare($refund_query);
                    $refund_stmt->bind_param("di", $trade['amount'], $trade['user_id']);
                    $refund_stmt->execute();
                    $refund_stmt->close();
                }
                
                // Delete the trade
                $delete_query = "DELETE FROM forex_trades WHERE id = ?";
                $delete_stmt = $conn->prepare($delete_query);
                $delete_stmt->bind_param("i", $trade_id);
                
                if ($delete_stmt->execute()) {
                    $message = "Trade deleted successfully" . ($trade['status'] == 'pending' ? " and amount refunded" : "");
                    $message_type = "success";
                } else {
                    $message = "Error deleting trade: " . $delete_stmt->error;
                    $message_type = "error";
                }
                $delete_stmt->close();
                break;
        }
    }
}

// Handle Quick Actions via GET
$actions = ['approve', 'reject', 'view', 'delete'];
foreach ($actions as $action) {
    if (isset($_GET[$action])) {
        $trade_id = intval($_GET[$action]);
        
        if ($action == 'view') {
            $show_actions_modal = true;
            $query = "SELECT t.*, u.username, u.full_name, u.email, u.account_balance 
                     FROM forex_trades t
                     JOIN users u ON t.user_id = u.id
                     WHERE t.id = ?";
            $stmt = $conn->prepare($query);
            $stmt->bind_param("i", $trade_id);
            $stmt->execute();
            $result = $stmt->get_result();
            $selected_trade = $result->fetch_assoc();
            $stmt->close();
        } elseif ($action == 'approve') {
            // Quick approve via GET
            $trade_query = "SELECT * FROM forex_trades WHERE id = ?";
            $trade_stmt = $conn->prepare($trade_query);
            $trade_stmt->bind_param("i", $trade_id);
            $trade_stmt->execute();
            $trade_result = $trade_stmt->get_result();
            $trade = $trade_result->fetch_assoc();
            $trade_stmt->close();
            
            if ($trade) {
                $update_query = "UPDATE forex_trades SET status = 'open', updated_at = NOW() WHERE id = ?";
                $update_stmt = $conn->prepare($update_query);
                $update_stmt->bind_param("i", $trade_id);
                
                if ($update_stmt->execute()) {
                    // Create notification
                    $notif_title = "Trade Approved";
                    $notif_message = "Your {$trade['trade_type']} trade of {$trade['currency_pair']} for $" . number_format($trade['amount'], 2) . " has been approved and is now open.";
                    
                    $notif_query = "INSERT INTO notifications (user_id, notification_type, title, message) 
                                   VALUES (?, 'trade', ?, ?)";
                    $notif_stmt = $conn->prepare($notif_query);
                    $notif_stmt->bind_param("iss", $trade['user_id'], $notif_title, $notif_message);
                    $notif_stmt->execute();
                    $notif_stmt->close();
                    
                    $message = "Trade approved successfully!";
                    $message_type = "success";
                } else {
                    $message = "Error approving trade: " . $update_stmt->error;
                    $message_type = "error";
                }
                $update_stmt->close();
            }
        }
    }
}

// Handle Edit Trade (load data)
if (isset($_GET['edit'])) {
    $trade_id = intval($_GET['edit']);
    if ($trade_id > 0) {
        $query = "SELECT t.*, u.username, u.full_name, u.email 
                 FROM forex_trades t
                 JOIN users u ON t.user_id = u.id
                 WHERE t.id = ?";
        $stmt = $conn->prepare($query);
        $stmt->bind_param("i", $trade_id);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($result->num_rows > 0) {
            $current_trade = $result->fetch_assoc();
            $edit_mode = true;
        }
        $stmt->close();
    }
}

// Handle Export Trades
if (isset($_GET['export'])) {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="forex_trades_' . date('Y-m-d') . '.csv"');
    
    $output = fopen('php://output', 'w');
    
    // Add BOM for UTF-8
    fputs($output, "\xEF\xBB\xBF");
    
    // CSV headers
    $headers = ['Trade ID', 'User', 'Username', 'Email', 'Currency Pair', 'Trade Type', 'Amount', 
                'Lot Size', 'Entry Price', 'Exit Price', 'Stop Loss', 'Take Profit', 
                'Profit/Loss', 'Status', 'Admin Action', 'Created At', 'Closed At'];
    fputcsv($output, $headers);
    
    // Fetch all trades
    $query = "SELECT t.*, u.full_name, u.username, u.email 
              FROM forex_trades t
              JOIN users u ON t.user_id = u.id
              ORDER BY t.created_at DESC";
    $result = $conn->query($query);
    
    while ($row = $result->fetch_assoc()) {
        $csv_row = [
            $row['id'],
            $row['full_name'] ?: 'N/A',
            $row['username'],
            $row['email'],
            $row['currency_pair'],
            $row['trade_type'],
            $row['amount'],
            $row['lot_size'],
            $row['entry_price'],
            $row['exit_price'] ?: 'N/A',
            $row['stop_loss'] ?: 'N/A',
            $row['take_profit'] ?: 'N/A',
            $row['profit_loss'] ? '$' . number_format($row['profit_loss'], 2) : 'N/A',
            ucfirst($row['status']),
            ucfirst($row['admin_action']),
            $row['created_at'],
            $row['closed_at'] ?: 'N/A'
        ];
        fputcsv($output, $csv_row);
    }
    
    fclose($output);
    exit();
}

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

// Build the query with filters
$where_conditions = [];
$params = [];
$param_types = '';

if (!empty($search)) {
    $where_conditions[] = "(u.username LIKE ? OR u.full_name LIKE ? OR u.email LIKE ? OR t.currency_pair LIKE ?)";
    $search_term = "%$search%";
    $params = array_merge($params, [$search_term, $search_term, $search_term, $search_term]);
    $param_types .= 'ssss';
}

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

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

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

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

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

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

$where_clause = '';
if (!empty($where_conditions)) {
    $where_clause = 'WHERE ' . implode(' AND ', $where_conditions);
}

// Get total trades count for pagination
$count_query = "SELECT COUNT(*) as total FROM forex_trades t
                JOIN users u ON t.user_id = u.id
                $where_clause";
if (!empty($params)) {
    $stmt = $conn->prepare($count_query);
    $stmt->bind_param($param_types, ...$params);
    $stmt->execute();
    $count_result = $stmt->get_result();
    $total_trades = $count_result->fetch_assoc()['total'];
    $stmt->close();
} else {
    $result = $conn->query($count_query);
    $total_trades = $result->fetch_assoc()['total'];
}

// 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;

// Get unique currency pairs for filter
$pairs_query = "SELECT DISTINCT currency_pair FROM forex_trades ORDER BY currency_pair";
$pairs_result = $conn->query($pairs_query);
$currency_pairs = [];
while ($row = $pairs_result->fetch_assoc()) {
    $currency_pairs[] = $row['currency_pair'];
}

// Get trades with pagination and filters
$query = "SELECT t.*, u.username, u.full_name, u.email, u.account_balance as user_balance
          FROM forex_trades t
          JOIN users u ON t.user_id = u.id
          $where_clause 
          ORDER BY 
            CASE 
                WHEN t.status = 'pending' THEN 1
                WHEN t.status = 'open' THEN 2
                ELSE 3
            END,
            t.created_at DESC 
          LIMIT ? OFFSET ?";

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

$stmt = $conn->prepare($query);
if (!empty($params)) {
    $stmt->bind_param($param_types, ...$params);
}
$stmt->execute();
$trades_result = $stmt->get_result();
$trades = [];
while ($row = $trades_result->fetch_assoc()) {
    $trades[] = $row;
}
$stmt->close();

// Get stats for dashboard
$stats_query = "SELECT 
    COUNT(*) as total_trades,
    SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending_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 = 'cancelled' THEN 1 ELSE 0 END) as cancelled_trades,
    SUM(CASE WHEN admin_action = 'profit' THEN 1 ELSE 0 END) as profit_trades,
    SUM(CASE WHEN admin_action = 'loss' THEN 1 ELSE 0 END) as loss_trades,
    SUM(CASE WHEN admin_action = 'pending' AND status != 'pending' THEN 1 ELSE 0 END) as pending_action_trades,
    SUM(amount) as total_invested,
    SUM(CASE WHEN status = 'closed' THEN profit_loss ELSE 0 END) as total_profit_loss,
    SUM(CASE WHEN profit_loss > 0 AND status = 'closed' THEN profit_loss ELSE 0 END) as total_profit,
    SUM(CASE WHEN profit_loss < 0 AND status = 'closed' THEN profit_loss ELSE 0 END) as total_loss,
    AVG(CASE WHEN status = 'closed' THEN profit_loss ELSE NULL END) as avg_profit_loss,
    COUNT(DISTINCT user_id) as active_traders
    FROM forex_trades";
$stats_result = $conn->query($stats_query);
$stats = $stats_result->fetch_assoc();

// Calculate win rate
$stats['win_rate'] = ($stats['profit_trades'] > 0 && $stats['closed_trades'] > 0) ? 
    round(($stats['profit_trades'] / $stats['closed_trades']) * 100, 2) : 0;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Forex Trades - Admin Panel</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">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: {
                            50: '#eff6ff',
                            100: '#dbeafe',
                            200: '#bfdbfe',
                            300: '#93c5fd',
                            400: '#60a5fa',
                            500: '#3b82f6',
                            600: '#2563eb',
                            700: '#1d4ed8',
                            800: '#1e40af',
                            900: '#1e3a8a',
                        }
                    },
                    fontFamily: {
                        'inter': ['Inter', 'system-ui', 'sans-serif'],
                    }
                }
            }
        }
    </script>
    <style>
        body {
            font-family: 'Inter', sans-serif;
            background: #f3f4f6;
        }
        
        .sidebar {
            transition: all 0.3s ease;
        }
        
        .main-content {
            transition: all 0.3s ease;
        }
        
        /* Tab styles */
        .tab-content {
            display: none;
        }
        
        .tab-content.active {
            display: block;
        }
        
        .tab-button.active {
            border-color: #3b82f6;
            color: #2563eb;
        }
        
        /* Status badges */
        .status-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 600;
        }
        
        .status-pending {
            background: rgba(245, 158, 11, 0.2);
            color: #f59e0b;
        }
        
        .status-open {
            background: rgba(16, 185, 129, 0.2);
            color: #10b981;
        }
        
        .status-closed {
            background: rgba(102, 126, 234, 0.2);
            color: #667eea;
        }
        
        .status-cancelled {
            background: rgba(239, 68, 68, 0.2);
            color: #ef4444;
        }
        
        .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;
        }
        
        /* Responsive adjustments */
        @media (max-width: 768px) {
            .mobile-hidden {
                display: none !important;
            }
            
            .mobile-block {
                display: block !important;
            }
            
            table {
                font-size: 0.875rem;
            }
        }
        
        /* Mobile menu */
        @media (max-width: 768px) {
            .sidebar {
                position: fixed;
                left: -100%;
                top: 0;
                z-index: 40;
                height: 100vh;
                transition: left 0.3s ease;
            }
            
            .sidebar.mobile-open {
                left: 0;
            }
            
            .main-content {
                margin-left: 0 !important;
            }
            
            .mobile-overlay {
                display: none;
                position: fixed;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                background: rgba(0, 0, 0, 0.5);
                z-index: 30;
            }
            
            .mobile-overlay.active {
                display: block;
            }
        }
    </style>
</head>
<body class="bg-gray-50 font-inter">
    
    <?php include("nav.php"); ?>

    <!-- Mobile Menu Toggle Button -->
    <button id="mobileMenuToggle" class="fixed top-4 left-4 z-30 bg-primary-600 text-white p-3 rounded-lg shadow-lg md:hidden">
        <i class="fas fa-bars"></i>
    </button>

    <!-- Mobile Menu Overlay -->
    <div id="mobileOverlay" class="mobile-overlay" onclick="closeMobileMenu()"></div>

    <!-- Main Content -->
    <div class="main-content ml-0 md:ml-64 pt-16 md:pt-0">
        <!-- Header -->
        <header class="bg-white shadow-sm border-b border-gray-200 px-4 md:px-8 py-4">
            <div class="flex items-center justify-between">
                <div>
                    <h2 class="text-xl md:text-2xl font-bold text-gray-800">Manage Forex Trades</h2>
                    <p class="text-sm md:text-base text-gray-600">Total Trades: <?php echo number_format($total_trades); ?></p>
                </div>
                
                <div class="flex items-center space-x-2 md:space-x-4">
                    <!-- Export Button -->
                    <a href="?export=csv<?php echo !empty($_GET) ? '&' . http_build_query(array_diff_key($_GET, ['export' => ''])) : ''; ?>" 
                       class="flex items-center space-x-1 md:space-x-2 px-3 md:px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition text-sm md:text-base">
                        <i class="fas fa-file-export"></i>
                        <span class="hidden md:inline">Export CSV</span>
                    </a>
                </div>
            </div>
        </header>

        <!-- Message Alert -->
        <?php if (!empty($message)): ?>
        <div class="mx-4 md:mx-8 mt-6">
            <div class="p-4 rounded-lg <?php echo $message_type == 'success' ? 'bg-green-100 text-green-700 border border-green-200' : 'bg-red-100 text-red-700 border border-red-200'; ?>">
                <div class="flex items-center justify-between">
                    <div class="flex items-center">
                        <i class="fas <?php echo $message_type == 'success' ? 'fa-check-circle' : 'fa-exclamation-circle'; ?> mr-2"></i>
                        <span class="text-sm md:text-base"><?php echo $message; ?></span>
                    </div>
                    <button onclick="this.parentElement.parentElement.remove()" class="text-gray-400 hover:text-gray-600">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- Trade Actions Modal -->
        <?php if ($show_actions_modal && $selected_trade): ?>
        <div id="actionsModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-2 md:p-4">
            <div class="bg-white rounded-lg shadow-xl w-full max-w-2xl max-h-[90vh] overflow-y-auto">
                <div class="p-4 md:p-6">
                    <div class="flex items-center justify-between mb-6">
                        <h3 class="text-lg md:text-xl font-bold text-gray-800">
                            Trade Actions: #<?php echo $selected_trade['id']; ?> - <?php echo htmlspecialchars($selected_trade['currency_pair']); ?>
                        </h3>
                        <button onclick="closeModal()" class="text-gray-400 hover:text-gray-600">
                            <i class="fas fa-times text-xl"></i>
                        </button>
                    </div>
                    
                    <!-- Trade Info Summary -->
                    <div class="grid grid-cols-2 md:grid-cols-3 gap-3 md:gap-4 mb-6">
                        <div class="bg-gray-50 p-3 rounded-lg">
                            <p class="text-xs text-gray-600">User</p>
                            <p class="text-sm font-semibold"><?php echo htmlspecialchars($selected_trade['full_name'] ?: $selected_trade['username']); ?></p>
                        </div>
                        <div class="bg-gray-50 p-3 rounded-lg">
                            <p class="text-xs text-gray-600">Type</p>
                            <p class="text-sm font-semibold <?php echo $selected_trade['trade_type'] == 'BUY' ? 'text-green-600' : 'text-red-600'; ?>">
                                <?php echo $selected_trade['trade_type']; ?>
                            </p>
                        </div>
                        <div class="bg-gray-50 p-3 rounded-lg">
                            <p class="text-xs text-gray-600">Amount</p>
                            <p class="text-sm font-semibold">$<?php echo number_format($selected_trade['amount'], 2); ?></p>
                        </div>
                        <div class="bg-gray-50 p-3 rounded-lg">
                            <p class="text-xs text-gray-600">Entry Price</p>
                            <p class="text-sm font-semibold"><?php echo number_format($selected_trade['entry_price'], 5); ?></p>
                        </div>
                        <div class="bg-gray-50 p-3 rounded-lg">
                            <p class="text-xs text-gray-600">Status</p>
                            <p class="text-sm">
                                <span class="status-badge status-<?php echo $selected_trade['status']; ?>">
                                    <?php echo ucfirst($selected_trade['status']); ?>
                                </span>
                            </p>
                        </div>
                        <div class="bg-gray-50 p-3 rounded-lg">
                            <p class="text-xs text-gray-600">Admin Action</p>
                            <p class="text-sm">
                                <?php if ($selected_trade['admin_action'] == 'profit'): ?>
                                <span class="profit-badge">Profit</span>
                                <?php elseif ($selected_trade['admin_action'] == 'loss'): ?>
                                <span class="loss-badge">Loss</span>
                                <?php else: ?>
                                <span class="status-badge status-pending">Pending</span>
                                <?php endif; ?>
                            </p>
                        </div>
                    </div>
                    
                    <!-- Tabs for different actions based on trade status -->
                    <div class="border-b border-gray-200 mb-6">
                        <nav class="-mb-px flex space-x-2 md:space-x-6 overflow-x-auto">
                            <?php if ($selected_trade['status'] == 'pending'): ?>
                            <button onclick="showTab('approve')" id="approveTab" class="tab-button py-2 px-1 border-b-2 border-primary-500 font-medium text-xs md:text-sm text-primary-600 active whitespace-nowrap">
                                <i class="fas fa-check-circle mr-1 md:mr-2"></i>Approve Trade
                            </button>
                            <button onclick="showTab('reject')" id="rejectTab" class="tab-button py-2 px-1 border-b-2 border-transparent font-medium text-xs md:text-sm text-gray-500 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap">
                                <i class="fas fa-times-circle mr-1 md:mr-2"></i>Reject Trade
                            </button>
                            <?php elseif ($selected_trade['status'] == 'open'): ?>
                            <button onclick="showTab('close')" id="closeTab" class="tab-button py-2 px-1 border-b-2 border-primary-500 font-medium text-xs md:text-sm text-primary-600 active whitespace-nowrap">
                                <i class="fas fa-lock mr-1 md:mr-2"></i>Close Trade
                            </button>
                            <?php endif; ?>
                            <button onclick="showTab('delete')" id="deleteTab" class="tab-button py-2 px-1 border-b-2 border-transparent font-medium text-xs md:text-sm text-gray-500 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap">
                                <i class="fas fa-trash mr-1 md:mr-2"></i>Delete Trade
                            </button>
                        </nav>
                    </div>
                    
                    <!-- Approve Trade Form (for pending trades) -->
                    <?php if ($selected_trade['status'] == 'pending'): ?>
                    <div id="approveTabContent" class="tab-content active">
                        <form method="POST" action="" class="space-y-4">
                            <input type="hidden" name="action_type" value="approve_trade">
                            <input type="hidden" name="trade_id" value="<?php echo $selected_trade['id']; ?>">
                            
                            <div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
                                <div class="flex">
                                    <i class="fas fa-info-circle text-blue-600 text-xl mr-3"></i>
                                    <div>
                                        <h4 class="font-medium text-blue-800">Approve Trade</h4>
                                        <p class="text-sm text-blue-600 mt-1">
                                            This will change the trade status to "open". The user will be notified.
                                        </p>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="pt-4 border-t border-gray-200">
                                <button type="submit" class="px-4 md:px-6 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition w-full md:w-auto">
                                    <i class="fas fa-check mr-2"></i>Approve Trade
                                </button>
                            </div>
                        </form>
                    </div>
                    
                    <!-- Reject Trade Form -->
                    <div id="rejectTabContent" class="tab-content">
                        <form method="POST" action="" class="space-y-4">
                            <input type="hidden" name="action_type" value="reject_trade">
                            <input type="hidden" name="trade_id" value="<?php echo $selected_trade['id']; ?>">
                            
                            <div class="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
                                <div class="flex">
                                    <i class="fas fa-exclamation-triangle text-yellow-600 text-xl mr-3"></i>
                                    <div>
                                        <h4 class="font-medium text-yellow-800">Reject Trade</h4>
                                        <p class="text-sm text-yellow-600 mt-1">
                                            This will cancel the trade and refund the amount to the user.
                                        </p>
                                    </div>
                                </div>
                            </div>
                            
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Rejection Reason</label>
                                <textarea name="rejection_reason" rows="3" required
                                          class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                                          placeholder="Explain why this trade is being rejected..."></textarea>
                            </div>
                            
                            <div class="pt-4 border-t border-gray-200">
                                <button type="submit" class="px-4 md:px-6 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition w-full md:w-auto">
                                    <i class="fas fa-times mr-2"></i>Reject & Refund
                                </button>
                            </div>
                        </form>
                    </div>
                    <?php endif; ?>
                    
                    <!-- Close Trade Form (for open trades) -->
                    <?php if ($selected_trade['status'] == 'open'): ?>
                    <div id="closeTabContent" class="tab-content active">
                        <form method="POST" action="" class="space-y-4" onsubmit="return validateCloseTrade()">
                            <input type="hidden" name="action_type" value="close_trade">
                            <input type="hidden" name="trade_id" value="<?php echo $selected_trade['id']; ?>">
                            
                            <div class="bg-green-50 border border-green-200 rounded-lg p-4">
                                <div class="flex">
                                    <i class="fas fa-info-circle text-green-600 text-xl mr-3"></i>
                                    <div>
                                        <h4 class="font-medium text-green-800">Close Trade</h4>
                                        <p class="text-sm text-green-600 mt-1">
                                            Select whether this trade resulted in profit or loss and enter the amount.
                                        </p>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="grid grid-cols-1 gap-4">
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">Admin Action</label>
                                    <select name="admin_action" id="admin_action" required onchange="toggleProfitLossFields()" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent">
                                        <option value="">Select Action</option>
                                        <option value="profit">Profit</option>
                                        <option value="loss">Loss</option>
                                    </select>
                                </div>
                                
                                <!-- Exit Price (optional, for reference) -->
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">Exit Price (Optional)</label>
                                    <input type="number" name="exit_price" step="0.00001" 
                                           value="<?php echo $selected_trade['entry_price']; ?>"
                                           class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent">
                                    <p class="text-xs text-gray-500 mt-1">For reference only, not used in calculations</p>
                                </div>
                                
                                <!-- Profit Fields (shown when profit selected) -->
                                <div id="profit_fields" style="display: none;">
                                    <div class="bg-blue-50 border border-blue-200 rounded-lg p-4 mb-4">
                                        <div class="flex items-center">
                                            <i class="fas fa-info-circle text-blue-600 mr-2"></i>
                                            <p class="text-sm text-blue-700">The original trade amount ($<?php echo number_format($selected_trade['amount'], 2); ?>) will be returned plus the profit amount.</p>
                                        </div>
                                    </div>
                                    
                                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                        <div>
                                            <label class="block text-sm font-medium text-gray-700 mb-1">Profit Amount ($)</label>
                                            <input type="number" name="profit_amount" step="0.01" min="0.01" 
                                                   class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                                                   placeholder="Enter profit amount">
                                        </div>
                                        
                                        <div>
                                            <label class="block text-sm font-medium text-gray-700 mb-1">Or Profit Percentage (%)</label>
                                            <input type="number" name="profit_percentage" step="0.1" min="0.1" max="1000" 
                                                   class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                                                   placeholder="e.g., 10 for 10%">
                                        </div>
                                    </div>
                                    <p class="text-xs text-gray-500 mt-2">Enter either profit amount OR percentage. If both are entered, amount will be used.</p>
                                </div>
                                
                                <!-- Loss Fields (shown when loss selected) -->
                                <div id="loss_fields" style="display: none;">
                                    <div class="bg-red-50 border border-red-200 rounded-lg p-4 mb-4">
                                        <div class="flex items-center">
                                            <i class="fas fa-exclamation-triangle text-red-600 mr-2"></i>
                                            <p class="text-sm text-red-700">The original trade amount ($<?php echo number_format($selected_trade['amount'], 2); ?>) will be returned minus the loss amount.</p>
                                        </div>
                                    </div>
                                    
                                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                        <div>
                                            <label class="block text-sm font-medium text-gray-700 mb-1">Loss Amount ($)</label>
                                            <input type="number" name="loss_amount" step="0.01" min="0.01" 
                                                   class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                                                   placeholder="Enter loss amount">
                                        </div>
                                        
                                        <div>
                                            <label class="block text-sm font-medium text-gray-700 mb-1">Or Loss Percentage (%)</label>
                                            <input type="number" name="loss_percentage" step="0.1" min="0.1" max="100" 
                                                   class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                                                   placeholder="e.g., 5 for 5%">
                                        </div>
                                    </div>
                                    <p class="text-xs text-gray-500 mt-2">Enter either loss amount OR percentage. If both are entered, amount will be used.</p>
                                </div>
                            </div>
                            
                            <div class="text-sm text-gray-500 bg-gray-50 p-3 rounded-lg">
                                <i class="fas fa-calculator mr-1"></i>
                                <strong>Calculation Example:</strong><br>
                                - Trade Amount: $<?php echo number_format($selected_trade['amount'], 2); ?><br>
                                - If Profit 10%: User receives $<?php echo number_format($selected_trade['amount'] * 1.1, 2); ?> ($<?php echo number_format($selected_trade['amount'], 2); ?> + $<?php echo number_format($selected_trade['amount'] * 0.1, 2); ?> profit)<br>
                                - If Loss 5%: User receives $<?php echo number_format($selected_trade['amount'] * 0.95, 2); ?> ($<?php echo number_format($selected_trade['amount'], 2); ?> - $<?php echo number_format($selected_trade['amount'] * 0.05, 2); ?> loss)
                            </div>
                            
                            <div class="pt-4 border-t border-gray-200">
                                <button type="submit" class="px-4 md:px-6 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition w-full md:w-auto">
                                    <i class="fas fa-lock mr-2"></i>Close Trade
                                </button>
                            </div>
                        </form>
                    </div>
                    <?php endif; ?>
                    
                    <!-- Delete Trade Form (for all trades) -->
                    <div id="deleteTabContent" class="tab-content <?php echo ($selected_trade['status'] != 'pending' && $selected_trade['status'] != 'open') ? 'active' : ''; ?>">
                        <form method="POST" action="" class="space-y-4" onsubmit="return confirm('Are you absolutely sure you want to delete this trade? This action cannot be undone.')">
                            <input type="hidden" name="action_type" value="delete_trade">
                            <input type="hidden" name="trade_id" value="<?php echo $selected_trade['id']; ?>">
                            
                            <div class="bg-red-50 border border-red-200 rounded-lg p-4">
                                <div class="flex">
                                    <i class="fas fa-exclamation-triangle text-red-600 text-xl mr-3"></i>
                                    <div>
                                        <h4 class="font-medium text-red-800">Delete Trade</h4>
                                        <p class="text-sm text-red-600 mt-1">
                                            <?php if ($selected_trade['status'] == 'pending'): ?>
                                            This will delete the pending trade and refund the amount to the user.
                                            <?php elseif ($selected_trade['status'] == 'open'): ?>
                                            WARNING: This trade is still open! Deleting it will not refund the user.
                                            <?php else: ?>
                                            This will permanently remove this trade from the database.
                                            <?php endif; ?>
                                        </p>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="flex items-center">
                                <input type="checkbox" name="confirm_delete" id="confirm_delete" required class="h-4 w-4 text-red-600 focus:ring-red-500 border-gray-300 rounded">
                                <label for="confirm_delete" class="ml-2 block text-sm text-gray-700">
                                    I understand that this action cannot be undone
                                </label>
                            </div>
                            
                            <div class="pt-4 border-t border-gray-200">
                                <button type="submit" class="px-4 md:px-6 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition w-full md:w-auto">
                                    <i class="fas fa-trash mr-2"></i>Delete Trade
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- Stats Cards -->
        <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 md:gap-6 mx-4 md:mx-8 mt-6">
            <!-- Total Trades Card -->
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-4 md:p-6">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-medium text-gray-600">Total Trades</p>
                        <p class="text-2xl md:text-3xl font-bold text-gray-800 mt-2"><?php echo number_format($stats['total_trades']); ?></p>
                    </div>
                    <div class="w-10 h-10 md:w-12 md:h-12 bg-blue-100 rounded-lg flex items-center justify-center">
                        <i class="fas fa-chart-line text-blue-600 text-lg md:text-xl"></i>
                    </div>
                </div>
                <div class="mt-4 text-xs md:text-sm text-gray-500">
                    <i class="fas fa-users mr-1"></i>
                    <?php echo $stats['active_traders']; ?> active traders
                </div>
            </div>

            <!-- Pending Trades Card -->
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-4 md:p-6">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-medium text-gray-600">Pending Approval</p>
                        <p class="text-2xl md:text-3xl font-bold text-orange-600 mt-2"><?php echo number_format($stats['pending_trades']); ?></p>
                    </div>
                    <div class="w-10 h-10 md:w-12 md:h-12 bg-orange-100 rounded-lg flex items-center justify-center">
                        <i class="fas fa-clock text-orange-600 text-lg md:text-xl"></i>
                    </div>
                </div>
                <div class="mt-4 text-xs md:text-sm text-gray-500">
                    <i class="fas fa-hourglass-half mr-1"></i>
                    Awaiting admin action
                </div>
            </div>

            <!-- Open Trades Card -->
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-4 md:p-6">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-medium text-gray-600">Open Trades</p>
                        <p class="text-2xl md:text-3xl font-bold text-green-600 mt-2"><?php echo number_format($stats['open_trades']); ?></p>
                    </div>
                    <div class="w-10 h-10 md:w-12 md:h-12 bg-green-100 rounded-lg flex items-center justify-center">
                        <i class="fas fa-play-circle text-green-600 text-lg md:text-xl"></i>
                    </div>
                </div>
                <div class="mt-4 text-xs md:text-sm text-gray-500">
                    <i class="fas fa-dollar-sign mr-1"></i>
                    $<?php echo number_format($stats['total_invested'], 2); ?> invested
                </div>
            </div>

            <!-- Profit/Loss Card -->
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-4 md:p-6">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-medium text-gray-600">Net P/L</p>
                        <p class="text-2xl md:text-3xl font-bold <?php echo ($stats['total_profit_loss'] ?? 0) >= 0 ? 'text-green-600' : 'text-red-600'; ?> mt-2">
                            $<?php echo number_format(abs($stats['total_profit_loss'] ?? 0), 2); ?>
                        </p>
                    </div>
                    <div class="w-10 h-10 md:w-12 md:h-12 <?php echo ($stats['total_profit_loss'] ?? 0) >= 0 ? 'bg-green-100' : 'bg-red-100'; ?> rounded-lg flex items-center justify-center">
                        <i class="fas <?php echo ($stats['total_profit_loss'] ?? 0) >= 0 ? 'fa-arrow-up' : 'fa-arrow-down'; ?> <?php echo ($stats['total_profit_loss'] ?? 0) >= 0 ? 'text-green-600' : 'text-red-600'; ?> text-lg md:text-xl"></i>
                    </div>
                </div>
                <div class="mt-4 text-xs md:text-sm text-gray-500">
                    <span class="text-green-600">+$<?php echo number_format($stats['total_profit'] ?? 0, 2); ?></span> / 
                    <span class="text-red-600">-$<?php echo number_format(abs($stats['total_loss'] ?? 0), 2); ?></span>
                </div>
            </div>
        </div>

        <!-- Additional Stats Row -->
        <div class="grid grid-cols-2 lg:grid-cols-4 gap-4 mx-4 md:mx-8 mt-4">
            <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-3">
                <p class="text-xs text-gray-600">Win Rate</p>
                <p class="text-lg font-bold text-gray-800"><?php echo $stats['win_rate']; ?>%</p>
                <p class="text-xs text-gray-500"><?php echo $stats['profit_trades']; ?> wins / <?php echo $stats['loss_trades']; ?> losses</p>
            </div>
            <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-3">
                <p class="text-xs text-gray-600">Total Invested</p>
                <p class="text-lg font-bold text-gray-800">$<?php echo number_format($stats['total_invested'], 2); ?></p>
                <p class="text-xs text-gray-500">Avg: $<?php echo $stats['total_trades'] > 0 ? number_format($stats['total_invested'] / $stats['total_trades'], 2) : 0; ?></p>
            </div>
            <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-3">
                <p class="text-xs text-gray-600">Avg P/L</p>
                <p class="text-lg font-bold <?php echo ($stats['avg_profit_loss'] ?? 0) >= 0 ? 'text-green-600' : 'text-red-600'; ?>">
                    $<?php echo number_format(abs($stats['avg_profit_loss'] ?? 0), 2); ?>
                </p>
                <p class="text-xs text-gray-500">Per closed trade</p>
            </div>
            <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-3">
                <p class="text-xs text-gray-600">Pending Action</p>
                <p class="text-lg font-bold text-orange-600"><?php echo number_format($stats['pending_action_trades']); ?></p>
                <p class="text-xs text-gray-500">Trades needing admin</p>
            </div>
        </div>

        <!-- Filters and Search -->
        <div class="bg-white mx-4 md:mx-8 mt-6 rounded-lg shadow-sm border border-gray-200 p-4 md:p-6">
            <form method="GET" action="" class="space-y-4">
                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                    <!-- Search -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Search</label>
                        <div class="relative">
                            <input type="text" name="search" value="<?php echo htmlspecialchars($search); ?>" 
                                   placeholder="User or pair..." 
                                   class="w-full px-4 py-2 pl-10 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent">
                            <i class="fas fa-search absolute left-3 top-3 text-gray-400"></i>
                        </div>
                    </div>
                    
                    <!-- Status Filter -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Status</label>
                        <select name="status" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent">
                            <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="block text-sm font-medium text-gray-700 mb-1">Trade Type</label>
                        <select name="type" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent">
                            <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="block text-sm font-medium text-gray-700 mb-1">Currency Pair</label>
                        <select name="pair" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent">
                            <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>
                </div>
                
                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                    <!-- Admin Action Filter -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Admin Action</label>
                        <select name="admin_action" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent">
                            <option value="all" <?php echo $admin_action_filter == 'all' ? 'selected' : ''; ?>>All Actions</option>
                            <option value="pending" <?php echo $admin_action_filter == 'pending' ? 'selected' : ''; ?>>Pending</option>
                            <option value="profit" <?php echo $admin_action_filter == 'profit' ? 'selected' : ''; ?>>Profit</option>
                            <option value="loss" <?php echo $admin_action_filter == 'loss' ? 'selected' : ''; ?>>Loss</option>
                        </select>
                    </div>
                    
                    <!-- Date From -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Date From</label>
                        <input type="date" name="date_from" value="<?php echo $date_from; ?>" 
                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent">
                    </div>
                    
                    <!-- Date To -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Date To</label>
                        <input type="date" name="date_to" value="<?php echo $date_to; ?>" 
                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent">
                    </div>
                    
                    <div></div> <!-- Empty column for spacing -->
                </div>
                
                <div class="flex flex-col md:flex-row justify-between items-center space-y-4 md:space-y-0">
                    <div class="flex space-x-2">
                        <button type="submit" class="px-4 md:px-6 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition text-sm md:text-base">
                            <i class="fas fa-filter mr-2"></i>Apply Filters
                        </button>
                        <a href="manage-trades.php" class="px-4 md:px-6 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition text-sm md:text-base">
                            <i class="fas fa-times mr-2"></i>Clear
                        </a>
                    </div>
                    
                    <!-- Results Count -->
                    <div class="text-sm text-gray-600">
                        Showing <?php echo min($per_page, count($trades)); ?> of <?php echo number_format($total_trades); ?> trades
                    </div>
                </div>
            </form>
        </div>

        <!-- Trades Table -->
        <div class="bg-white mx-4 md:mx-8 my-6 rounded-lg shadow-sm border border-gray-200 overflow-hidden">
            <div class="overflow-x-auto">
                <table class="w-full min-w-[1200px]">
                    <thead class="bg-gray-50">
                        <tr class="text-left text-sm text-gray-500 border-b border-gray-200">
                            <th class="py-3 px-4 md:px-6 font-medium">Trade ID</th>
                            <th class="py-3 px-4 md:px-6 font-medium">User</th>
                            <th class="py-3 px-4 md:px-6 font-medium">Pair</th>
                            <th class="py-3 px-4 md:px-6 font-medium">Type</th>
                            <th class="py-3 px-4 md:px-6 font-medium">Amount</th>
                            <th class="py-3 px-4 md:px-6 font-medium">Lot Size</th>
                            <th class="py-3 px-4 md:px-6 font-medium">Entry</th>
                            <th class="py-3 px-4 md:px-6 font-medium">Exit</th>
                            <th class="py-3 px-4 md:px-6 font-medium">P/L</th>
                            <th class="py-3 px-4 md:px-6 font-medium">Status</th>
                            <th class="py-3 px-4 md:px-6 font-medium">Admin</th>
                            <th class="py-3 px-4 md:px-6 font-medium">Date</th>
                            <th class="py-3 px-4 md:px-6 font-medium">Actions</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-gray-200">
                        <?php if (empty($trades)): ?>
                        <tr>
                            <td colspan="13" class="py-8 text-center text-gray-500">
                                <i class="fas fa-chart-line text-3xl mb-2 block"></i>
                                No trades found
                            </td>
                        </tr>
                        <?php else: ?>
                        <?php foreach ($trades as $trade): ?>
                        <tr class="hover:bg-gray-50 transition">
                            <!-- Trade ID -->
                            <td class="py-4 px-4 md:px-6">
                                <span class="font-mono text-sm">#<?php echo $trade['id']; ?></span>
                            </td>
                            
                            <!-- User Info -->
                            <td class="py-4 px-4 md:px-6">
                                <div class="flex items-center">
                                    <div class="w-8 h-8 bg-primary-100 rounded-full flex items-center justify-center mr-2">
                                        <span class="text-primary-800 font-medium text-xs">
                                            <?php echo strtoupper(substr($trade['full_name'] ?: $trade['username'], 0, 1)); ?>
                                        </span>
                                    </div>
                                    <div>
                                        <p class="font-medium text-gray-800 text-sm">
                                            <?php echo htmlspecialchars($trade['full_name'] ?: $trade['username']); ?>
                                        </p>
                                        <p class="text-xs text-gray-500">@<?php echo htmlspecialchars($trade['username']); ?></p>
                                    </div>
                                </div>
                            </td>
                            
                            <!-- Pair -->
                            <td class="py-4 px-4 md:px-6">
                                <span class="font-medium"><?php echo htmlspecialchars($trade['currency_pair']); ?></span>
                            </td>
                            
                            <!-- Type -->
                            <td class="py-4 px-4 md:px-6">
                                <span class="<?php echo $trade['trade_type'] == 'BUY' ? 'text-green-600' : 'text-red-600'; ?> font-semibold text-sm">
                                    <?php echo $trade['trade_type']; ?>
                                </span>
                            </td>
                            
                            <!-- Amount -->
                            <td class="py-4 px-4 md:px-6">
                                <span class="font-medium">$<?php echo number_format($trade['amount'], 2); ?></span>
                            </td>
                            
                            <!-- Lot Size -->
                            <td class="py-4 px-4 md:px-6">
                                <?php echo number_format($trade['lot_size'], 2); ?>
                            </td>
                            
                            <!-- Entry Price -->
                            <td class="py-4 px-4 md:px-6 font-mono text-sm">
                                <?php echo number_format($trade['entry_price'], 5); ?>
                            </td>
                            
                            <!-- Exit Price -->
                            <td class="py-4 px-4 md:px-6 font-mono text-sm">
                                <?php echo $trade['exit_price'] ? number_format($trade['exit_price'], 5) : '-'; ?>
                            </td>
                            
                            <!-- Profit/Loss -->
                            <td class="py-4 px-4 md:px-6">
                                <?php if ($trade['profit_loss'] !== null): ?>
                                    <span class="<?php echo $trade['profit_loss'] >= 0 ? 'text-green-600' : 'text-red-600'; ?> font-semibold">
                                        <?php echo $trade['profit_loss'] >= 0 ? '+' : ''; ?>$<?php echo number_format(abs($trade['profit_loss']), 2); ?>
                                    </span>
                                <?php else: ?>
                                    -
                                <?php endif; ?>
                            </td>
                            
                            <!-- Status -->
                            <td class="py-4 px-4 md:px-6">
                                <span class="status-badge status-<?php echo $trade['status']; ?>">
                                    <?php echo ucfirst($trade['status']); ?>
                                </span>
                            </td>
                            
                            <!-- Admin Action -->
                            <td class="py-4 px-4 md:px-6">
                                <?php if ($trade['admin_action'] == 'profit'): ?>
                                <span class="profit-badge">Profit</span>
                                <?php elseif ($trade['admin_action'] == 'loss'): ?>
                                <span class="loss-badge">Loss</span>
                                <?php else: ?>
                                <span class="status-badge status-pending">Pending</span>
                                <?php endif; ?>
                            </td>
                            
                            <!-- Date -->
                            <td class="py-4 px-4 md:px-6">
                                <p class="text-sm text-gray-600"><?php echo date('M d, H:i', strtotime($trade['created_at'])); ?></p>
                            </td>
                            
                            <!-- Actions -->
                            <td class="py-4 px-4 md:px-6">
                                <div class="flex flex-wrap gap-1">
                                    <!-- Quick Actions -->
                                    <a href="?view=<?php echo $trade['id']; ?><?php echo !empty($_GET) ? '&' . http_build_query(array_diff_key($_GET, ['view' => ''])) : ''; ?>" 
                                       class="inline-flex items-center px-2 py-1 bg-primary-100 text-primary-700 rounded hover:bg-primary-200 transition text-xs"
                                       title="View/Manage">
                                        <i class="fas fa-eye mr-1"></i>
                                        <span class="hidden md:inline">Manage</span>
                                    </a>
                                    
                                    <?php if ($trade['status'] == 'pending'): ?>
                                    <a href="?approve=<?php echo $trade['id']; ?><?php echo !empty($_GET) ? '&' . http_build_query(array_diff_key($_GET, ['approve' => ''])) : ''; ?>" 
                                       class="inline-flex items-center px-2 py-1 bg-green-100 text-green-700 rounded hover:bg-green-200 transition text-xs"
                                       title="Approve"
                                       onclick="return confirm('Approve this trade?')">
                                        <i class="fas fa-check mr-1"></i>
                                        <span class="hidden md:inline">Approve</span>
                                    </a>
                                    <?php endif; ?>
                                    
                                    <?php if ($trade['status'] == 'pending' || $trade['status'] == 'cancelled'): ?>
                                    <a href="?delete=<?php echo $trade['id']; ?><?php echo !empty($_GET) ? '&' . http_build_query(array_diff_key($_GET, ['delete' => ''])) : ''; ?>" 
                                       class="inline-flex items-center px-2 py-1 bg-red-50 text-red-600 rounded hover:bg-red-100 transition text-xs"
                                       title="Delete"
                                       onclick="return confirm('Are you sure you want to delete this trade?')">
                                        <i class="fas fa-trash mr-1"></i>
                                        <span class="hidden md:inline">Delete</span>
                                    </a>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
            
            <!-- Pagination -->
            <?php if ($total_pages > 1): ?>
            <div class="px-4 md:px-6 py-4 border-t border-gray-200">
                <div class="flex flex-col md:flex-row items-center justify-between space-y-4 md:space-y-0">
                    <div class="text-sm text-gray-600">
                        Page <?php echo $current_page; ?> of <?php echo $total_pages; ?>
                    </div>
                    <div class="flex space-x-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="px-3 py-1 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition text-sm">
                            <i class="fas fa-chevron-left mr-1"></i> Previous
                        </a>
                        <?php endif; ?>
                        
                        <?php 
                        $start_page = max(1, $current_page - 2);
                        $end_page = min($total_pages, $current_page + 2);
                        
                        for ($page = $start_page; $page <= $end_page; $page++): 
                        ?>
                        <a href="?page=<?php echo $page; ?><?php echo !empty($_GET) ? '&' . http_build_query(array_diff_key($_GET, ['page' => ''])) : ''; ?>" 
                           class="px-3 py-1 border rounded-lg transition text-sm <?php echo $page == $current_page ? 'bg-primary-600 text-white border-primary-600' : 'border-gray-300 text-gray-700 hover:bg-gray-50'; ?>">
                            <?php echo $page; ?>
                        </a>
                        <?php endfor; ?>
                        
                        <?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="px-3 py-1 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition text-sm">
                            Next <i class="fas fa-chevron-right ml-1"></i>
                        </a>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <?php endif; ?>
        </div>
    </div>

<script>
    // Modal functions
    function closeModal() {
        const modal = document.getElementById('actionsModal');
        if (modal) {
            modal.remove();
            // Remove from URL
            const url = new URL(window.location);
            url.searchParams.delete('view');
            window.history.replaceState({}, '', url);
        }
    }

    // Tab switching for modal
    function showTab(tabName) {
        // Hide all tab contents
        const tabContents = document.querySelectorAll('.tab-content');
        tabContents.forEach(content => {
            content.classList.remove('active');
        });
        
        // Remove active from all tabs
        const tabs = document.querySelectorAll('.tab-button');
        tabs.forEach(tab => {
            tab.classList.remove('active', 'border-primary-500', 'text-primary-600');
            tab.classList.add('border-transparent', 'text-gray-500');
        });
        
        // Show selected tab content
        const selectedContent = document.getElementById(tabName + 'TabContent');
        if (selectedContent) {
            selectedContent.classList.add('active');
        }
        
        // Activate selected tab
        const selectedTab = document.getElementById(tabName + 'Tab');
        if (selectedTab) {
            selectedTab.classList.remove('border-transparent', 'text-gray-500');
            selectedTab.classList.add('active', 'border-primary-500', 'text-primary-600');
        }
    }

    // Toggle profit/loss fields based on selection
    function toggleProfitLossFields() {
        const action = document.getElementById('admin_action').value;
        const profitFields = document.getElementById('profit_fields');
        const lossFields = document.getElementById('loss_fields');
        
        if (profitFields) profitFields.style.display = 'none';
        if (lossFields) lossFields.style.display = 'none';
        
        if (action === 'profit' && profitFields) {
            profitFields.style.display = 'block';
        } else if (action === 'loss' && lossFields) {
            lossFields.style.display = 'block';
        }
    }

    // Initialize first tab as active
    <?php if ($show_actions_modal): ?>
    document.addEventListener('DOMContentLoaded', function() {
        <?php if ($selected_trade['status'] == 'pending'): ?>
        showTab('approve');
        <?php elseif ($selected_trade['status'] == 'open'): ?>
        showTab('close');
        <?php else: ?>
        showTab('delete');
        <?php endif; ?>
        
        // Initialize profit/loss fields if close tab is active
        if (document.getElementById('admin_action')) {
            toggleProfitLossFields();
        }
    });
    <?php endif; ?>

    // Validate close trade form
    function validateCloseTrade() {
        const adminAction = document.querySelector('select[name="admin_action"]').value;
        
        if (!adminAction) {
            alert('Please select whether this trade resulted in profit or loss');
            return false;
        }
        
        if (adminAction === 'profit') {
            const profitAmount = document.querySelector('input[name="profit_amount"]').value;
            const profitPercentage = document.querySelector('input[name="profit_percentage"]').value;
            
            if (!profitAmount && !profitPercentage) {
                alert('Please enter either a profit amount or percentage');
                return false;
            }
            
            if (profitAmount && parseFloat(profitAmount) <= 0) {
                alert('Please enter a valid profit amount greater than 0');
                return false;
            }
            
            if (profitPercentage && (parseFloat(profitPercentage) <= 0 || parseFloat(profitPercentage) > 1000)) {
                alert('Please enter a valid profit percentage between 0.1 and 1000');
                return false;
            }
        }
        
        if (adminAction === 'loss') {
            const lossAmount = document.querySelector('input[name="loss_amount"]').value;
            const lossPercentage = document.querySelector('input[name="loss_percentage"]').value;
            
            if (!lossAmount && !lossPercentage) {
                alert('Please enter either a loss amount or percentage');
                return false;
            }
            
            if (lossAmount && parseFloat(lossAmount) <= 0) {
                alert('Please enter a valid loss amount greater than 0');
                return false;
            }
            
            if (lossPercentage && (parseFloat(lossPercentage) <= 0 || parseFloat(lossPercentage) > 100)) {
                alert('Please enter a valid loss percentage between 0.1 and 100');
                return false;
            }
            
            // Check if loss amount exceeds trade amount
            const tradeAmount = <?php echo $selected_trade['amount']; ?>;
            if (lossAmount && parseFloat(lossAmount) > tradeAmount) {
                alert('Loss amount cannot exceed the trade amount ($' + tradeAmount.toFixed(2) + ')');
                return false;
            }
            
            if (lossPercentage && parseFloat(lossPercentage) > 100) {
                alert('Loss percentage cannot exceed 100%');
                return false;
            }
        }
        
        return confirm('Are you sure you want to close this trade? This action cannot be undone.');
    }

    // Close modal on escape key
    document.addEventListener('keydown', function(event) {
        if (event.key === 'Escape') {
            closeModal();
        }
    });

    // Close modal when clicking outside
    document.addEventListener('click', function(event) {
        const modal = document.getElementById('actionsModal');
        if (modal && event.target === modal) {
            closeModal();
        }
    });

    // Mobile menu functionality
    document.addEventListener('DOMContentLoaded', function() {
        const mobileMenuToggle = document.getElementById('mobileMenuToggle');
        const mobileOverlay = document.getElementById('mobileOverlay');
        const sidebar = document.querySelector('.sidebar');
        
        function openMobileMenu() {
            if (sidebar) sidebar.classList.add('mobile-open');
            if (mobileOverlay) mobileOverlay.classList.add('active');
            document.body.style.overflow = 'hidden';
        }
        
        function closeMobileMenu() {
            if (sidebar) sidebar.classList.remove('mobile-open');
            if (mobileOverlay) mobileOverlay.classList.remove('active');
            document.body.style.overflow = '';
        }
        
        if (mobileMenuToggle) {
            mobileMenuToggle.addEventListener('click', function(event) {
                event.stopPropagation();
                if (sidebar && sidebar.classList.contains('mobile-open')) {
                    closeMobileMenu();
                } else {
                    openMobileMenu();
                }
            });
        }
        
        if (mobileOverlay) {
            mobileOverlay.addEventListener('click', closeMobileMenu);
        }
        
        // Close mobile menu when clicking on a sidebar link
        const sidebarLinks = document.querySelectorAll('.sidebar a');
        sidebarLinks.forEach(link => {
            link.addEventListener('click', function() {
                if (window.innerWidth <= 768) {
                    closeMobileMenu();
                }
            });
        });
        
        // Handle window resize
        window.addEventListener('resize', function() {
            if (window.innerWidth > 768) {
                closeMobileMenu();
            }
        });
    });
</script>
    
</body>
</html>