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

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

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['invest'])) {
    $plan_id = intval($_POST['plan_id']);
    $amount = floatval($_POST['amount']);
    
    // Get plan details
    $plan_stmt = $conn->prepare("SELECT * FROM copy_trade_plans WHERE id = ? AND status = 'active'");
    $plan_stmt->bind_param("i", $plan_id);
    $plan_stmt->execute();
    $plan_result = $plan_stmt->get_result();
    
    if ($plan_result->num_rows === 0) {
        $message = "Invalid investment plan selected";
        $message_type = "error";
    } else {
        $plan = $plan_result->fetch_assoc();
        
        // Validation
        if ($amount <= 0) {
            $message = "Please enter a valid amount";
            $message_type = "error";
        } elseif ($amount < $plan['min_investment']) {
            $message = "Minimum investment for this plan is $" . number_format($plan['min_investment'], 2);
            $message_type = "error";
        } elseif ($amount > $plan['max_investment']) {
            $message = "Maximum investment for this plan is $" . number_format($plan['max_investment'], 2);
            $message_type = "error";
        } elseif ($amount > $user['account_balance']) {
            $message = "Insufficient balance. Your available balance is $" . number_format($user['account_balance'], 2);
            $message_type = "error";
        } else {
            // Insert investment
            $insert_stmt = $conn->prepare("
                INSERT INTO copy_trade_investments 
                (user_id, plan_id, amount, status) 
                VALUES (?, ?, ?, 'pending')
            ");
            
            $insert_stmt->bind_param("iid", $user_id, $plan_id, $amount);
            
            if ($insert_stmt->execute()) {
                // Deduct from account balance
                $new_balance = $user['account_balance'] - $amount;
                $update_balance = $conn->prepare("UPDATE users SET account_balance = ? WHERE id = ?");
                $update_balance->bind_param("di", $new_balance, $user_id);
                $update_balance->execute();
                $update_balance->close();
                
                // Create notification if notifications table exists
                $check_notif_table = $conn->query("SHOW TABLES LIKE 'notifications'");
                if ($check_notif_table->num_rows > 0) {
                    $notif_title = "Investment Submitted";
                    $notif_message = "Your investment of $" . number_format($amount, 2) . " in {$plan['plan_name']} has been submitted and is pending admin approval.";
                    $notif_stmt = $conn->prepare("INSERT INTO notifications (user_id, title, message, notification_type) VALUES (?, ?, ?, 'investment')");
                    $notif_stmt->bind_param("iss", $user_id, $notif_title, $notif_message);
                    $notif_stmt->execute();
                    $notif_stmt->close();
                }
                
                $message = "Investment submitted successfully! Waiting for approval.";
                $message_type = "success";
                
                // Refresh user data
                $user['account_balance'] = $new_balance;
            } else {
                $message = "Error processing investment. Please try again.";
                $message_type = "error";
            }
            $insert_stmt->close();
        }
    }
    $plan_stmt->close();
}

// Fetch active copy trade plans
$plans_query = "SELECT * FROM copy_trade_plans WHERE status = 'active' ORDER BY min_investment ASC";
$plans_result = $conn->query($plans_query);
$plans = [];
if ($plans_result) {
    while ($row = $plans_result->fetch_assoc()) {
        $row['features'] = json_decode($row['features'], true);
        $plans[] = $row;
    }
}

// Fetch user's investments
$investments_stmt = $conn->prepare("
    SELECT ci.*, cp.plan_name, cp.profit_percentage, cp.duration_days 
    FROM copy_trade_investments ci
    JOIN copy_trade_plans cp ON ci.plan_id = cp.id
    WHERE ci.user_id = ? 
    ORDER BY ci.created_at DESC 
    LIMIT 10
");
$investments_stmt->bind_param("i", $user_id);
$investments_stmt->execute();
$investments_result = $investments_stmt->get_result();
$investments_stmt->close();

// Calculate investment statistics - FIXED QUERY for your table structure
$stats = [
    'total_invested' => 0,
    'active_investments' => 0,
    'pending_investments' => 0,
    'completed_investments' => 0
];

// Since there's no profit_earned column, we'll just track investments
$stats_stmt = $conn->prepare("
    SELECT 
        COALESCE(SUM(CASE WHEN status IN ('active', 'pending', 'completed') THEN amount ELSE 0 END), 0) as total_invested,
        COUNT(CASE WHEN status = 'active' THEN 1 END) as active_investments,
        COUNT(CASE WHEN status = 'pending' THEN 1 END) as pending_investments,
        COUNT(CASE WHEN status = 'completed' THEN 1 END) as completed_investments
    FROM copy_trade_investments 
    WHERE user_id = ?
");
$stats_stmt->bind_param("i", $user_id);
$stats_stmt->execute();
$stats_result = $stats_stmt->get_result();
if ($row = $stats_result->fetch_assoc()) {
    $stats = $row;
}
$stats_stmt->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Copy Trading - <?php echo htmlspecialchars($site_settings['site_name'] ?? 'Trading Platform'); ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    
    <style>
        :root {
            --sidebar-width: 16rem;
            --primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            --success-gradient: linear-gradient(135deg, #38b2ac 0%, #319795 100%);
            --warning-gradient: linear-gradient(135deg, #ed8936 0%, #dd6b20 100%);
            --danger-gradient: linear-gradient(135deg, #f56565 0%, #e53e3e 100%);
            --info-gradient: linear-gradient(135deg, #4299e1 0%, #3182ce 100%);
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Inter', sans-serif;
            background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%);
            min-height: 100vh;
            color: #e2e8f0;
        }
        
        /* Sidebar Styles */
        .sidebar {
            background: linear-gradient(180deg, #1e293b 0%, #0f172a 100%);
            width: var(--sidebar-width);
            height: 100vh;
            position: fixed;
            left: 0;
            top: 0;
            z-index: 1000;
            transform: translateX(-100%);
            transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            overflow-y: auto;
            box-shadow: 4px 0 20px rgba(0, 0, 0, 0.3);
            border-right: 1px solid rgba(255, 255, 255, 0.05);
        }
        
        .sidebar.active {
            transform: translateX(0);
        }
        
        @media (min-width: 1024px) {
            .sidebar {
                transform: translateX(0) !important;
            }
        }
        
        .sidebar-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.7);
            z-index: 999;
            backdrop-filter: blur(4px);
        }
        
        .sidebar-overlay.active {
            display: block;
        }
        
        /* Main Content */
        .main-content {
            width: 100%;
            min-height: 100vh;
            transition: margin-left 0.3s ease;
        }
        
        @media (min-width: 1024px) {
            .main-content {
                margin-left: var(--sidebar-width);
                width: calc(100% - var(--sidebar-width));
            }
        }
        
        .glass-card {
            background: rgba(30, 41, 59, 0.7);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.1);
            border-radius: 1.25rem;
            transition: all 0.3s ease;
        }
        
        .glass-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
            border-color: rgba(102, 126, 234, 0.3);
        }
        
        .plan-card {
            background: rgba(15, 23, 42, 0.6);
            border: 1px solid rgba(255, 255, 255, 0.05);
            border-radius: 1.25rem;
            transition: all 0.3s ease;
            overflow: hidden;
        }
        
        .plan-card:hover {
            transform: translateY(-4px);
            border-color: rgba(102, 126, 234, 0.3);
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.4);
        }
        
        .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;
        }
        
        .status-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 600;
        }
        
        .status-active {
            background: rgba(16, 185, 129, 0.2);
            color: #10b981;
        }
        
        .status-completed {
            background: rgba(102, 126, 234, 0.2);
            color: #667eea;
        }
        
        .status-pending {
            background: rgba(245, 158, 11, 0.2);
            color: #f59e0b;
        }
        
        .status-cancelled {
            background: rgba(239, 68, 68, 0.2);
            color: #ef4444;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .animate-fade-in {
            animation: fadeIn 0.5s ease-out;
        }
        
        .feature-tag {
            background: rgba(102, 126, 234, 0.1);
            border: 1px solid rgba(102, 126, 234, 0.2);
            color: #a5b4fc;
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            display: inline-flex;
            align-items: center;
            gap: 0.25rem;
        }
        
        .form-input {
            background: rgba(15, 23, 42, 0.6);
            border: 1px solid rgba(255, 255, 255, 0.1);
            border-radius: 0.75rem;
            padding: 0.75rem 1rem;
            color: white;
            width: 100%;
            transition: all 0.2s;
        }
        
        .form-input:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.2);
        }
        
        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            font-weight: 600;
            padding: 0.75rem 1.5rem;
            border-radius: 0.75rem;
            transition: all 0.2s;
            border: none;
            cursor: pointer;
            width: 100%;
        }
        
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px rgba(102, 126, 234, 0.4);
        }
        
        .btn-outline {
            background: transparent;
            border: 1px solid rgba(102, 126, 234, 0.5);
            color: #a5b4fc;
            font-weight: 500;
            padding: 0.5rem 1rem;
            border-radius: 0.75rem;
            transition: all 0.2s;
            cursor: pointer;
        }
        
        .btn-outline:hover {
            background: rgba(102, 126, 234, 0.1);
            border-color: #667eea;
        }
        
        /* Investment Modal */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.8);
            backdrop-filter: blur(8px);
            z-index: 2000;
            align-items: center;
            justify-content: center;
        }
        
        .modal.active {
            display: flex;
        }
        
        .modal-content {
            background: rgba(30, 41, 59, 0.95);
            border: 1px solid rgba(255, 255, 255, 0.1);
            border-radius: 1.5rem;
            max-width: 500px;
            width: 90%;
            max-height: 90vh;
            overflow-y: auto;
            animation: fadeIn 0.3s ease-out;
        }
        
        /* 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);
            cursor: pointer;
        }
        
        .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;
        }
        
        /* 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>
   
    <!-- Sidebar Overlay -->
    <div class="sidebar-overlay" id="sidebarOverlay"></div>

    <!-- 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">
                        Copy Trading
                    </h1>
                    <p class="text-gray-400 mt-1">
                        <i class="fas fa-copy mr-2"></i> Automatically copy trades from professional traders
                    </p>
                </div>
                <div class="flex items-center gap-3">
                    <div class="glass-card px-4 py-2">
                        <span class="text-sm text-gray-400">Balance:</span>
                        <span class="text-xl font-bold text-green-400 ml-2">$<?php echo number_format($user['account_balance'], 2); ?></span>
                    </div>
                </div>
            </div>
        </div>

        <!-- Alert Messages -->
        <?php if ($message): ?>
        <div class="mx-4 mt-4">
            <div class="p-4 rounded-xl <?php echo $message_type === 'success' ? 'bg-green-500/20 border-green-500/30' : 'bg-red-500/20 border-red-500/30'; ?> border">
                <div class="flex items-center gap-3">
                    <i class="fas fa-<?php echo $message_type === 'success' ? 'check-circle' : 'exclamation-circle'; ?> <?php echo $message_type === 'success' ? 'text-green-400' : 'text-red-400'; ?>"></i>
                    <span><?php echo htmlspecialchars($message); ?></span>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- Stats Cards -->
        <div class="p-6 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
            <div class="glass-card p-6">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm text-gray-400">Total Invested</p>
                        <p class="text-2xl font-bold text-white">$<?php echo number_format($stats['total_invested'], 2); ?></p>
                    </div>
                    <div class="w-12 h-12 bg-blue-500/20 rounded-xl flex items-center justify-center">
                        <i class="fas fa-dollar-sign text-blue-400 text-xl"></i>
                    </div>
                </div>
            </div>
            
            <div class="glass-card p-6">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm text-gray-400">Active Investments</p>
                        <p class="text-2xl font-bold text-white"><?php echo $stats['active_investments']; ?></p>
                    </div>
                    <div class="w-12 h-12 bg-green-500/20 rounded-xl flex items-center justify-center">
                        <i class="fas fa-chart-line text-green-400 text-xl"></i>
                    </div>
                </div>
            </div>
            
            <div class="glass-card p-6">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm text-gray-400">Pending</p>
                        <p class="text-2xl font-bold text-yellow-400"><?php echo $stats['pending_investments']; ?></p>
                    </div>
                    <div class="w-12 h-12 bg-yellow-500/20 rounded-xl flex items-center justify-center">
                        <i class="fas fa-clock text-yellow-400 text-xl"></i>
                    </div>
                </div>
            </div>
            
            <div class="glass-card p-6">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm text-gray-400">Completed</p>
                        <p class="text-2xl font-bold text-white"><?php echo $stats['completed_investments']; ?></p>
                    </div>
                    <div class="w-12 h-12 bg-purple-500/20 rounded-xl flex items-center justify-center">
                        <i class="fas fa-check-circle text-purple-400 text-xl"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- Investment Plans -->
        <div class="p-6">
            <h2 class="text-xl font-bold mb-6 flex items-center gap-2">
                <i class="fas fa-layer-group text-blue-400"></i>
                Available Copy Trading Plans
            </h2>
            
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                <?php foreach ($plans as $plan): ?>
                <div class="plan-card">
                    <?php if (!empty($plan['image_url'])): ?>
                    <div class="h-48 overflow-hidden">
                        <img src="../<?php echo htmlspecialchars($plan['image_url']); ?>" 
                             alt="<?php echo htmlspecialchars($plan['plan_name']); ?>"
                             class="w-full h-full object-cover">
                    </div>
                    <?php endif; ?>
                    
                    <div class="p-6">
                        <div class="flex items-start justify-between mb-4">
                            <div>
                                <h3 class="text-xl font-bold text-white mb-1"><?php echo htmlspecialchars($plan['plan_name']); ?></h3>
                            </div>
                            <div class="text-right">
                                <span class="profit-badge"><?php echo $plan['profit_percentage']; ?>% Return</span>
                            </div>
                        </div>
                        
                        <p class="text-gray-300 text-sm mb-4 line-clamp-2"><?php echo htmlspecialchars($plan['description']); ?></p>
                        
                        <div class="grid grid-cols-2 gap-4 mb-4">
                            <div>
                                <p class="text-xs text-gray-500">Min Investment</p>
                                <p class="text-lg font-bold text-white">$<?php echo number_format($plan['min_investment'], 2); ?></p>
                            </div>
                            <div>
                                <p class="text-xs text-gray-500">Max Investment</p>
                                <p class="text-lg font-bold text-white">$<?php echo number_format($plan['max_investment'], 2); ?></p>
                            </div>
                            <div>
                                <p class="text-xs text-gray-500">Duration</p>
                                <p class="text-lg font-bold text-white"><?php echo $plan['duration_days']; ?> days</p>
                            </div>
                            <div>
                                <p class="text-xs text-gray-500">Expected Return</p>
                                <p class="text-lg font-bold text-green-400">$<?php echo number_format($plan['min_investment'] * $plan['profit_percentage'] / 100, 2); ?> - $<?php echo number_format($plan['max_investment'] * $plan['profit_percentage'] / 100, 2); ?></p>
                            </div>
                        </div>
                        
                        <?php if (!empty($plan['features'])): ?>
                        <div class="mb-4">
                            <p class="text-xs text-gray-400 mb-2">Features:</p>
                            <div class="flex flex-wrap gap-2">
                                <?php foreach (array_slice($plan['features'], 0, 3) as $feature): ?>
                                <?php if (!empty($feature)): ?>
                                <span class="feature-tag">
                                    <i class="fas fa-check-circle text-xs"></i>
                                    <?php echo htmlspecialchars($feature); ?>
                                </span>
                                <?php endif; ?>
                                <?php endforeach; ?>
                                <?php if (count($plan['features']) > 3): ?>
                                <span class="feature-tag">+<?php echo count($plan['features']) - 3; ?> more</span>
                                <?php endif; ?>
                            </div>
                        </div>
                        <?php endif; ?>
                        
                        <button onclick="showInvestmentModal(<?php echo $plan['id']; ?>, '<?php echo htmlspecialchars($plan['plan_name']); ?>', <?php echo $plan['min_investment']; ?>, <?php echo $plan['max_investment']; ?>, <?php echo $plan['duration_days']; ?>, <?php echo $plan['profit_percentage']; ?>)" 
                                class="btn-primary">
                            <i class="fas fa-hand-holding-usd mr-2"></i>
                            Invest Now
                        </button>
                    </div>
                </div>
                <?php endforeach; ?>
                
                <?php if (empty($plans)): ?>
                <div class="col-span-3 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-layer-group text-gray-600 text-3xl"></i>
                    </div>
                    <h4 class="text-white font-medium mb-1">No investment plans available</h4>
                    <p class="text-gray-500 text-sm">Please check back later for new copy trading opportunities</p>
                </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Investment History -->
        <div class="p-6 pt-0">
            <div class="glass-card p-6">
                <div class="flex items-center justify-between mb-6">
                    <h3 class="text-xl font-bold flex items-center gap-2">
                        <i class="fas fa-history text-blue-400"></i>
                        Your Investments
                    </h3>
                </div>
                
                <?php if ($investments_result->num_rows > 0): ?>
                <div class="overflow-x-auto">
                    <table class="w-full">
                        <thead>
                            <tr class="text-left text-sm text-gray-400">
                                <th class="pb-3">Date</th>
                                <th class="pb-3">Plan</th>
                                <th class="pb-3">Amount</th>
                                <th class="pb-3">Status</th>
                                <th class="pb-3">Expected Return</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php while ($investment = $investments_result->fetch_assoc()): 
                                $status_class = '';
                                switch ($investment['status']) {
                                    case 'active':
                                        $status_class = 'status-active';
                                        break;
                                    case 'completed':
                                        $status_class = 'status-completed';
                                        break;
                                    case 'pending':
                                        $status_class = 'status-pending';
                                        break;
                                    case 'cancelled':
                                        $status_class = 'status-cancelled';
                                        break;
                                }
                                $expected_return = $investment['amount'] * $investment['profit_percentage'] / 100;
                            ?>
                            <tr class="border-t border-gray-800">
                                <td class="py-3 text-sm"><?php echo date('M d, Y', strtotime($investment['created_at'])); ?></td>
                                <td class="py-3 font-medium"><?php echo htmlspecialchars($investment['plan_name']); ?></td>
                                <td class="py-3 font-medium text-green-400">$<?php echo number_format($investment['amount'], 2); ?></td>
                                <td class="py-3">
                                    <span class="status-badge <?php echo $status_class; ?>">
                                        <?php echo ucfirst($investment['status']); ?>
                                    </span>
                                </td>
                                <td class="py-3 text-green-400">+$<?php echo number_format($expected_return, 2); ?></td>
                            </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
                <?php else: ?>
                <div class="text-center py-12">
                    <div class="w-20 h-20 bg-gray-800/50 rounded-full flex items-center justify-center mx-auto mb-4">
                        <i class="fas fa-history text-gray-600 text-3xl"></i>
                    </div>
                    <h4 class="text-white font-medium mb-1">No investments yet</h4>
                    <p class="text-gray-500 text-sm">Start copy trading by investing in a plan above</p>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Investment Modal -->
    <div class="modal" id="investmentModal">
        <div class="modal-content">
            <div class="p-6 border-b border-gray-800 flex items-center justify-between">
                <h3 class="text-xl font-bold flex items-center gap-2">
                    <i class="fas fa-hand-holding-usd text-blue-400"></i>
                    Invest in <span id="modalPlanName"></span>
                </h3>
                <button onclick="closeInvestmentModal()" class="text-gray-400 hover:text-white">
                    <i class="fas fa-times text-xl"></i>
                </button>
            </div>
            
            <form method="POST" action="" class="p-6 space-y-4">
                <input type="hidden" name="plan_id" id="modalPlanId">
                
                <div>
                    <label class="block text-sm font-medium text-gray-400 mb-2">Investment Amount ($)</label>
                    <input type="number" name="amount" id="modalAmount" class="form-input" 
                           placeholder="Enter amount" step="0.01" required oninput="updateSummary()">
                    <p class="text-xs text-gray-500 mt-2" id="modalRange"></p>
                </div>
                
                <div class="bg-gray-800/50 p-4 rounded-xl">
                    <h4 class="font-medium text-white mb-2">Investment Summary</h4>
                    <div class="space-y-2 text-sm">
                        <div class="flex justify-between">
                            <span class="text-gray-400">Plan:</span>
                            <span class="text-white" id="summaryPlanName"></span>
                        </div>
                        <div class="flex justify-between">
                            <span class="text-gray-400">Amount:</span>
                            <span class="text-white" id="summaryAmount">$0.00</span>
                        </div>
                        <div class="flex justify-between">
                            <span class="text-gray-400">Duration:</span>
                            <span class="text-white" id="summaryDuration"></span>
                        </div>
                        <div class="flex justify-between">
                            <span class="text-gray-400">Expected Return:</span>
                            <span class="text-green-400" id="summaryProfit">$0.00</span>
                        </div>
                    </div>
                </div>
                
                <div class="flex gap-3">
                    <button type="button" onclick="closeInvestmentModal()" class="btn-outline flex-1">
                        Cancel
                    </button>
                    <button type="submit" name="invest" class="btn-primary flex-1">
                        Confirm Investment
                    </button>
                </div>
                
                <p class="text-xs text-center text-gray-500 mt-4">
                    <i class="fas fa-info-circle mr-1"></i>
                    Your investment will be pending admin approval before activation
                </p>
            </form>
        </div>
    </div>

    <script>
        // Mobile menu functionality
        document.addEventListener('DOMContentLoaded', function() {
            const menuToggle = document.getElementById('menuToggle');
            const sidebar = document.querySelector('.sidebar');
            const sidebarOverlay = document.getElementById('sidebarOverlay');
            const body = document.body;
            
            if (menuToggle && sidebar && sidebarOverlay) {
                menuToggle.addEventListener('click', function(e) {
                    e.preventDefault();
                    sidebar.classList.toggle('active');
                    sidebarOverlay.classList.toggle('active');
                    body.style.overflow = sidebar.classList.contains('active') ? 'hidden' : '';
                });
                
                sidebarOverlay.addEventListener('click', function() {
                    sidebar.classList.remove('active');
                    sidebarOverlay.classList.remove('active');
                    body.style.overflow = '';
                });
            }
            
            // Close sidebar when clicking a nav link on mobile
            document.querySelectorAll('.nav-item').forEach(item => {
                item.addEventListener('click', function() {
                    if (window.innerWidth < 1024) {
                        setTimeout(() => {
                            sidebar.classList.remove('active');
                            sidebarOverlay.classList.remove('active');
                            body.style.overflow = '';
                        }, 200);
                    }
                });
            });
            
            // Handle window resize
            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 = '';
                }
            });
            
            // Initialize sidebar state
            if (window.innerWidth >= 1024) {
                sidebar.classList.add('active');
            }
            
            // Set active nav item
            const currentPage = window.location.pathname.split('/').pop() || 'copytrading.php';
            document.querySelectorAll('.nav-item').forEach(nav => {
                const href = nav.getAttribute('href');
                if (href && href.includes(currentPage)) {
                    nav.classList.add('active');
                }
            });
        });
        
        // Investment modal variables
        let currentPlan = {
            id: null,
            name: '',
            min: 0,
            max: 0,
            duration: 0,
            profit: 0
        };
        
        function showInvestmentModal(planId, planName, minAmount, maxAmount, duration, profit) {
            currentPlan.id = planId;
            currentPlan.name = planName;
            currentPlan.min = minAmount;
            currentPlan.max = maxAmount;
            currentPlan.duration = duration;
            currentPlan.profit = profit;
            
            document.getElementById('modalPlanId').value = planId;
            document.getElementById('modalPlanName').textContent = planName;
            document.getElementById('summaryPlanName').textContent = planName;
            document.getElementById('modalRange').textContent = 
                `Min: $${minAmount.toFixed(2)} | Max: $${maxAmount.toFixed(2)}`;
            document.getElementById('summaryDuration').textContent = duration + ' days';
            
            document.getElementById('investmentModal').classList.add('active');
        }
        
        function closeInvestmentModal() {
            document.getElementById('investmentModal').classList.remove('active');
            document.getElementById('modalAmount').value = '';
            updateSummary();
        }
        
        // Update summary when amount changes
        function updateSummary() {
            const amount = parseFloat(document.getElementById('modalAmount').value) || 0;
            document.getElementById('summaryAmount').textContent = '$' + amount.toFixed(2);
            
            if (currentPlan.profit > 0 && amount > 0) {
                const expectedProfit = (amount * currentPlan.profit) / 100;
                document.getElementById('summaryProfit').textContent = '+$' + expectedProfit.toFixed(2);
            } else {
                document.getElementById('summaryProfit').textContent = '$0.00';
            }
        }
        
        // Close modal when clicking outside
        window.addEventListener('click', function(e) {
            const modal = document.getElementById('investmentModal');
            if (e.target === modal) {
                closeInvestmentModal();
            }
        });
        
        // Escape key to close modal
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                closeInvestmentModal();
            }
        });
        
        // Form validation
        document.querySelector('form')?.addEventListener('submit', function(e) {
            const amount = parseFloat(document.querySelector('input[name="amount"]').value);
            const balance = <?php echo $user['account_balance']; ?>;
            
            if (amount > balance) {
                e.preventDefault();
                alert('Insufficient balance! Your available balance is $' + balance.toFixed(2));
            }
        });
    </script>
</body>
</html>