<?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['account_status']) && $user['account_status'] != 'active') {
    $error_message = "Your account is " . $user['account_status'];
    header("Location: login.php?error=" . urlencode($error_message));
    exit();
}

// Check and create user_investments table if it doesn't exist
$check_table = $conn->query("SHOW TABLES LIKE 'user_investments'");
if ($check_table->num_rows === 0) {
    // Create user_investments table
    $create_table_sql = "
        CREATE TABLE IF NOT EXISTS user_investments (
            id INT PRIMARY KEY AUTO_INCREMENT,
            user_id INT NOT NULL,
            plan_id INT NOT NULL,
            amount DECIMAL(15,2) NOT NULL,
            expected_return DECIMAL(15,2) NOT NULL,
            actual_return DECIMAL(15,2) DEFAULT 0,
            status ENUM('active', 'completed', 'cancelled') DEFAULT 'active',
            start_date DATE NOT NULL,
            end_date DATE NOT NULL,
            next_payout_date DATE,
            transaction_id VARCHAR(50),
            payment_method VARCHAR(50),
            payment_proof VARCHAR(500),
            admin_notes TEXT,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            INDEX idx_user_id (user_id),
            INDEX idx_plan_id (plan_id),
            INDEX idx_status (status),
            INDEX idx_end_date (end_date),
            FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
            FOREIGN KEY (plan_id) REFERENCES investment_plans(id) ON DELETE CASCADE
        )
    ";
    
    if (!$conn->query($create_table_sql)) {
        error_log("Failed to create user_investments table: " . $conn->error);
    }
}

// Handle investment form submission
$success_message = '';
$error_message = '';
$selected_plan = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['invest'])) {
        $plan_id = intval($_POST['plan_id'] ?? 0);
        $amount = floatval($_POST['amount'] ?? 0);
        
        // Get investment plan details
        $plan_stmt = $conn->prepare("SELECT * FROM investment_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) {
            $error_message = "Selected investment plan is not available";
        } else {
            $selected_plan = $plan_result->fetch_assoc();
            $plan_stmt->close();
            
            // Validate amount against plan limits
            $min_amount = floatval($selected_plan['min_amount']);
            $max_amount = floatval($selected_plan['max_amount']);
            
            // CRITICAL: Check if user has sufficient account balance
            $user_balance = floatval($user['account_balance']);
            
            if ($amount < $min_amount) {
                $error_message = "Minimum investment for this plan is $" . number_format($min_amount, 2);
            } elseif ($amount > $max_amount) {
                $error_message = "Maximum investment for this plan is $" . number_format($max_amount, 2);
            } elseif ($amount > $user_balance) {
                // Show detailed balance information
                $error_message = "Insufficient balance! ";
                $error_message .= "Your account balance is $" . number_format($user_balance, 2);
                $error_message .= ". You need $" . number_format($amount - $user_balance, 2) . " more.";
            } else {
                // Calculate investment details
                $interest_rate = floatval($selected_plan['interest_rate']);
                $duration_days = intval($selected_plan['duration_days']);
                $compounding_interval = $selected_plan['compounding_interval'] ?? 'none';
                
                // Calculate expected return - UPDATED: Simple calculation based on your example
                $expected_return = calculateExpectedReturn($amount, $interest_rate);
                
                // Start transaction for data integrity
                $conn->begin_transaction();
                
                try {
                    // Re-check balance within transaction to prevent race conditions
                    $balance_check_stmt = $conn->prepare("SELECT account_balance FROM users WHERE id = ? FOR UPDATE");
                    $balance_check_stmt->bind_param("i", $user_id);
                    $balance_check_stmt->execute();
                    $balance_check_result = $balance_check_stmt->get_result();
                    $current_balance_row = $balance_check_result->fetch_assoc();
                    $current_balance = floatval($current_balance_row['account_balance']);
                    $balance_check_stmt->close();
                    
                    if ($amount > $current_balance) {
                        throw new Exception("Insufficient balance. Current balance: $" . number_format($current_balance, 2));
                    }
                    
                    // Generate transaction ID
                    $transaction_id = 'INV' . strtoupper(uniqid());
                    
                    // Calculate next payout date based on compounding interval
                    $next_payout_interval = getNextPayoutInterval($compounding_interval);
                    
                    // Insert investment record
                    $investment_stmt = $conn->prepare("
                        INSERT INTO user_investments 
                        (user_id, plan_id, amount, expected_return, actual_return, status,
                         start_date, end_date, next_payout_date, transaction_id)
                        VALUES (?, ?, ?, ?, 0, 'active', CURDATE(), 
                                DATE_ADD(CURDATE(), INTERVAL ? DAY), 
                                DATE_ADD(CURDATE(), INTERVAL ? DAY), ?)
                    ");
                    
                    $investment_stmt->bind_param("iidddis", 
                        $user_id, 
                        $plan_id, 
                        $amount, 
                        $expected_return,
                        $duration_days,
                        $next_payout_interval,
                        $transaction_id
                    );
                    
                    if (!$investment_stmt->execute()) {
                        throw new Exception("Failed to create investment: " . $conn->error);
                    }
                    $investment_stmt->close();
                    
                    // Deduct amount from user's account balance
                    $update_user_stmt = $conn->prepare("
                        UPDATE users SET 
                        account_balance = account_balance - ?,
                        investment_balance = investment_balance + ?,
                        total_invested = total_invested + ?,
                        updated_at = NOW()
                        WHERE id = ?
                    ");
                    $update_user_stmt->bind_param("dddi", $amount, $amount, $amount, $user_id);
                    
                    if (!$update_user_stmt->execute()) {
                        throw new Exception("Failed to update user balance: " . $conn->error);
                    }
                    $update_user_stmt->close();
                    
                    // Create transaction record
                    $create_transaction_stmt = $conn->prepare("
                        INSERT INTO transactions 
                        (user_id, amount, type, status, created_at)
                        VALUES (?, ?, 'investment', 'completed', NOW())
                    ");
                    $create_transaction_stmt->bind_param("id", $user_id, $amount);
                    
                    if (!$create_transaction_stmt->execute()) {
                        // If transactions table doesn't exist, continue without error
                        error_log("Note: Could not create transaction record");
                    }
                    $create_transaction_stmt->close();
                    
                    // Commit transaction
                    $conn->commit();
                    
                    // Update user data in session
                    $user['account_balance'] -= $amount;
                    $user['investment_balance'] = ($user['investment_balance'] ?? 0) + $amount;
                    $user['total_invested'] = ($user['total_invested'] ?? 0) + $amount;
                    
                    $profit = $expected_return - $amount;
                    $success_message = "Investment successful! ";
                    $success_message .= "You have invested $" . number_format($amount, 2) . " in " . htmlspecialchars($selected_plan['name']) . ". ";
                    $success_message .= "Expected return: $" . number_format($expected_return, 2) . " (Profit: $" . number_format($profit, 2) . ") after " . $duration_days . " days.";
                    
                    // Clear form
                    unset($_POST);
                    $_POST = array();
                    
                } catch (Exception $e) {
                    $conn->rollback();
                    $error_message = "Investment failed: " . $e->getMessage();
                }
            }
        }
    }
}

// UPDATED: Function to calculate expected return based on your example
// interest_rate is the total percentage return for the duration
function calculateExpectedReturn($principal, $interest_rate) {
    // Calculate profit: principal * (interest_rate / 100)
    $profit = $principal * ($interest_rate / 100);
    
    // Return principal + profit
    return $principal + $profit;
}

// Function to get next payout interval based on compounding
function getNextPayoutInterval($compounding_interval) {
    switch($compounding_interval) {
        case 'daily':
            return 1;
        case 'weekly':
            return 7;
        case 'monthly':
            return 30;
        case 'quarterly':
            return 90;
        case 'annually':
            return 365;
        case 'none':
        default:
            return 30; // Default monthly check
    }
}

// Function to process completed investments (to be called by cron job)
function processCompletedInvestments($conn) {
    $today = date('Y-m-d');
    
    // Find investments that ended today or earlier and are still active
    $query = "
        SELECT ui.*, u.account_balance 
        FROM user_investments ui
        JOIN users u ON ui.user_id = u.id
        WHERE ui.status = 'active' 
        AND ui.end_date <= ? 
        AND ui.actual_return = 0
    ";
    
    $stmt = $conn->prepare($query);
    $stmt->bind_param("s", $today);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $processed_count = 0;
    
    while ($investment = $result->fetch_assoc()) {
        // Calculate profit (expected_return - amount)
        $profit = $investment['expected_return'] - $investment['amount'];
        
        if ($profit > 0) {
            // Start transaction
            $conn->begin_transaction();
            
            try {
                // Update user's account balance and earnings
                $update_user = $conn->prepare("
                    UPDATE users SET 
                    account_balance = account_balance + ?,
                    total_earnings = total_earnings + ?,
                    updated_at = NOW()
                    WHERE id = ?
                ");
                $update_user->bind_param("ddi", $investment['expected_return'], $profit, $investment['user_id']);
                $update_user->execute();
                $update_user->close();
                
                // Mark investment as completed and update actual return
                $update_investment = $conn->prepare("
                    UPDATE user_investments SET 
                    status = 'completed',
                    actual_return = ?,
                    updated_at = NOW()
                    WHERE id = ?
                ");
                $update_investment->bind_param("di", $investment['expected_return'], $investment['id']);
                $update_investment->execute();
                $update_investment->close();
                
                // Create transaction record for the return
                $create_transaction = $conn->prepare("
                    INSERT INTO transactions 
                    (user_id, amount, type, status, description, created_at)
                    VALUES (?, ?, 'profit', 'completed', 'Investment return from plan ID: ?', NOW())
                ");
                $create_transaction->bind_param("idi", $investment['user_id'], $investment['expected_return'], $investment['plan_id']);
                $create_transaction->execute();
                $create_transaction->close();
                
                $conn->commit();
                $processed_count++;
                
                // Log successful processing
                error_log("Investment ID {$investment['id']} completed. User {$investment['user_id']} received {$investment['expected_return']}");
                
            } catch (Exception $e) {
                $conn->rollback();
                error_log("Failed to process investment ID {$investment['id']}: " . $e->getMessage());
            }
        }
    }
    
    $stmt->close();
    return $processed_count;
}

// Function to process daily interest (if using daily compounding)
function processDailyInterest($conn) {
    $today = date('Y-m-d');
    
    // Find active investments with daily compounding that need payout today
    $query = "
        SELECT ui.*, ip.interest_rate, ip.duration_days 
        FROM user_investments ui
        JOIN investment_plans ip ON ui.plan_id = ip.id
        WHERE ui.status = 'active' 
        AND ui.next_payout_date = ?
        AND ip.compounding_interval = 'daily'
    ";
    
    $stmt = $conn->prepare($query);
    $stmt->bind_param("s", $today);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $processed_count = 0;
    
    while ($investment = $result->fetch_assoc()) {
        // Calculate daily interest - Updated calculation
        // Total profit = amount * (interest_rate / 100)
        // Daily profit = total profit / duration_days
        $total_profit = $investment['amount'] * ($investment['interest_rate'] / 100);
        $daily_interest = $total_profit / $investment['duration_days'];
        
        if ($daily_interest > 0) {
            // Start transaction
            $conn->begin_transaction();
            
            try {
                // Update user's account balance and earnings
                $update_user = $conn->prepare("
                    UPDATE users SET 
                    account_balance = account_balance + ?,
                    total_earnings = total_earnings + ?,
                    updated_at = NOW()
                    WHERE id = ?
                ");
                $update_user->bind_param("ddi", $daily_interest, $daily_interest, $investment['user_id']);
                $update_user->execute();
                $update_user->close();
                
                // Update investment's actual return and next payout date
                $update_investment = $conn->prepare("
                    UPDATE user_investments SET 
                    actual_return = actual_return + ?,
                    next_payout_date = DATE_ADD(?, INTERVAL 1 DAY),
                    updated_at = NOW()
                    WHERE id = ?
                ");
                $update_investment->bind_param("dsi", $daily_interest, $today, $investment['id']);
                $update_investment->execute();
                $update_investment->close();
                
                // Create transaction record
                $create_transaction = $conn->prepare("
                    INSERT INTO transactions 
                    (user_id, amount, type, status, description, created_at)
                    VALUES (?, ?, 'profit', 'completed', 'Daily interest from investment ID: ?', NOW())
                ");
                $create_transaction->bind_param("idi", $investment['user_id'], $daily_interest, $investment['id']);
                $create_transaction->execute();
                $create_transaction->close();
                
                $conn->commit();
                $processed_count++;
                
            } catch (Exception $e) {
                $conn->rollback();
                error_log("Failed to process daily interest for investment ID {$investment['id']}: " . $e->getMessage());
            }
        }
    }
    
    $stmt->close();
    return $processed_count;
}

// Fetch all active investment plans
$plans = [];
$plan_query = "SELECT * FROM investment_plans WHERE status = 'active' ORDER BY min_amount ASC";
$plan_result = $conn->query($plan_query);

if ($plan_result) {
    while ($row = $plan_result->fetch_assoc()) {
        // Calculate example returns for display - USING UPDATED CALCULATION
        $example_min = calculateExpectedReturn(
            $row['min_amount'],
            $row['interest_rate']
        );
        
        $example_max = calculateExpectedReturn(
            $row['max_amount'],
            $row['interest_rate']
        );
        
        $row['example_min_return'] = $example_min;
        $row['example_max_return'] = $example_max;
        
        // Calculate profit for display
        $row['example_min_profit'] = $example_min - $row['min_amount'];
        $row['example_max_profit'] = $example_max - $row['max_amount'];
        
        $plans[] = $row;
    }
    $plan_result->free();
}

// Get user's active investments
$active_investments = [];
$investment_query = "
    SELECT ui.*, ip.name as plan_name, ip.interest_rate, ip.duration_days
    FROM user_investments ui
    JOIN investment_plans ip ON ui.plan_id = ip.id
    WHERE ui.user_id = ? AND ui.status = 'active'
    ORDER BY ui.created_at DESC
    LIMIT 10
";
$investment_stmt = $conn->prepare($investment_query);
$investment_stmt->bind_param("i", $user_id);
$investment_stmt->execute();
$investment_result = $investment_stmt->get_result();

while ($row = $investment_result->fetch_assoc()) {
    // Calculate days remaining
    $end_date = new DateTime($row['end_date']);
    $today = new DateTime();
    $days_remaining = $today->diff($end_date)->days;
    $row['days_remaining'] = $days_remaining;
    $row['progress_percentage'] = 100 - (($days_remaining / $row['duration_days']) * 100);
    
    // Calculate earned so far (this would normally come from earnings table)
    $row['earned_so_far'] = $row['actual_return'];
    
    // Calculate total expected profit
    $row['total_profit'] = $row['expected_return'] - $row['amount'];
    
    // Calculate daily expected profit
    $row['daily_profit'] = $row['total_profit'] / $row['duration_days'];
    
    $active_investments[] = $row;
}
$investment_stmt->close();

// Get user's investment stats
$stats_query = "
    SELECT 
        COUNT(*) as total_investments,
        SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) as active_investments,
        SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed_investments,
        COALESCE(SUM(amount), 0) as total_invested,
        COALESCE(SUM(expected_return - amount), 0) as total_expected_profit,
        COALESCE(SUM(actual_return), 0) as total_earnings
    FROM user_investments 
    WHERE user_id = ?
";
$stats_stmt = $conn->prepare($stats_query);
$stats_stmt->bind_param("i", $user_id);
$stats_stmt->execute();
$stats_result = $stats_stmt->get_result();
$investment_stats = $stats_result->fetch_assoc() ?? [
    'total_investments' => 0,
    'active_investments' => 0,
    'completed_investments' => 0,
    'total_invested' => 0,
    'total_expected_profit' => 0,
    'total_earnings' => 0
];
$stats_stmt->close();

// Get user's account balance
$account_balance = floatval($user['account_balance'] ?? 0);
$investment_balance = floatval($user['investment_balance'] ?? 0);
$total_invested = floatval($user['total_invested'] ?? 0);

// Format dates
$last_investment = $active_investments[0]['created_at'] ?? null;
$last_investment_date = $last_investment ? date('M d, Y', strtotime($last_investment)) : 'No investments yet';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Invest - 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, #10b981 0%, #059669 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));
            }
        }
        
        /* 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);
        }
        
        @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;
        }
        
        /* Card Styles */
        .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(-4px);
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
            border-color: rgba(102, 126, 234, 0.3);
        }
        
        .gradient-card {
            background: linear-gradient(135deg, rgba(102, 126, 234, 0.15) 0%, rgba(118, 75, 162, 0.15) 100%);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(102, 126, 234, 0.2);
            border-radius: 1.25rem;
        }
        
        /* Investment Plan Cards */
        .plan-card {
            background: rgba(255, 255, 255, 0.03);
            border: 1px solid rgba(255, 255, 255, 0.1);
            border-radius: 1rem;
            padding: 1.5rem;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .plan-card:hover {
            background: rgba(255, 255, 255, 0.05);
            border-color: #667eea;
            transform: translateY(-2px);
        }
        
        .plan-card.selected {
            background: rgba(102, 126, 234, 0.1);
            border-color: #667eea;
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.15);
        }
        
        .plan-badge {
            display: inline-flex;
            align-items: center;
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 500;
        }
        
        .plan-basic {
            background: rgba(59, 130, 246, 0.1);
            color: #3b82f6;
            border: 1px solid rgba(59, 130, 246, 0.2);
        }
        
        .plan-premium {
            background: rgba(168, 85, 247, 0.1);
            color: #a855f7;
            border: 1px solid rgba(168, 85, 247, 0.2);
        }
        
        .plan-professional {
            background: rgba(245, 158, 11, 0.1);
            color: #f59e0b;
            border: 1px solid rgba(245, 158, 11, 0.2);
        }
        
        /* Investment Progress Bar */
        .investment-progress {
            height: 6px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 3px;
            overflow: hidden;
            margin: 1rem 0;
        }
        
        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #667eea, #764ba2);
            border-radius: 3px;
        }
        
        /* Form Styles */
        .form-input {
            background: rgba(255, 255, 255, 0.05);
            border: 1px solid rgba(255, 255, 255, 0.1);
            border-radius: 0.75rem;
            padding: 0.875rem 1rem;
            color: #e2e8f0;
            font-size: 0.95rem;
            transition: all 0.2s ease;
            width: 100%;
        }
        
        .form-input:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
            background: rgba(255, 255, 255, 0.08);
        }
        
        .form-input::placeholder {
            color: #94a3b8;
        }
        
        .form-label {
            display: block;
            color: #cbd5e0;
            font-size: 0.875rem;
            font-weight: 500;
            margin-bottom: 0.5rem;
        }
        
        .form-group {
            margin-bottom: 1.5rem;
        }
        
        .btn-primary {
            background: var(--primary-gradient);
            color: white;
            border: none;
            border-radius: 0.75rem;
            padding: 0.875rem 1.75rem;
            font-weight: 600;
            font-size: 0.95rem;
            cursor: pointer;
            transition: all 0.2s ease;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 0.5rem;
        }
        
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px -5px rgba(102, 126, 234, 0.4);
        }
        
        .btn-primary:active {
            transform: translateY(0);
        }
        
        .btn-success {
            background: var(--success-gradient);
            color: white;
            border: none;
            border-radius: 0.75rem;
            padding: 0.875rem 1.75rem;
            font-weight: 600;
            font-size: 0.95rem;
            cursor: pointer;
            transition: all 0.2s ease;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 0.5rem;
        }
        
        .btn-success:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px -5px rgba(16, 185, 129, 0.4);
        }
        
        .btn-secondary {
            background: rgba(255, 255, 255, 0.05);
            color: #cbd5e0;
            border: 1px solid rgba(255, 255, 255, 0.1);
            border-radius: 0.75rem;
            padding: 0.875rem 1.75rem;
            font-weight: 500;
            font-size: 0.95rem;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .btn-secondary:hover {
            background: rgba(255, 255, 255, 0.1);
            color: #e2e8f0;
        }
        
        /* Alert Messages */
        .alert-success {
            background: rgba(72, 187, 120, 0.1);
            border: 1px solid rgba(72, 187, 120, 0.2);
            color: #48bb78;
            padding: 1rem 1.5rem;
            border-radius: 0.75rem;
            margin-bottom: 1.5rem;
            display: flex;
            align-items: center;
            gap: 0.75rem;
            animation: slideIn 0.3s ease-out;
        }
        
        .alert-error {
            background: rgba(245, 101, 101, 0.1);
            border: 1px solid rgba(245, 101, 101, 0.2);
            color: #f56565;
            padding: 1rem 1.5rem;
            border-radius: 0.75rem;
            margin-bottom: 1.5rem;
            display: flex;
            align-items: center;
            gap: 0.75rem;
            animation: slideIn 0.3s ease-out;
        }
        
        .alert-info {
            background: rgba(59, 130, 246, 0.1);
            border: 1px solid rgba(59, 130, 246, 0.2);
            color: #3b82f6;
            padding: 1rem 1.5rem;
            border-radius: 0.75rem;
            margin-bottom: 1.5rem;
            display: flex;
            align-items: center;
            gap: 0.75rem;
        }
        
        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(-10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        /* Close button for mobile sidebar */
        .sidebar-close-btn {
            display: none;
        }
        
        @media (max-width: 1023px) {
            .sidebar-close-btn {
                display: block;
                position: absolute;
                top: 1rem;
                right: 1rem;
                z-index: 1001;
                width: 2.5rem;
                height: 2.5rem;
                background: rgba(255, 255, 255, 0.1);
                border-radius: 50%;
                display: flex;
                align-items: center;
                justify-content: center;
                border: none;
                color: white;
                cursor: pointer;
                transition: all 0.2s ease;
                backdrop-filter: blur(10px);
            }
            
            .sidebar-close-btn:hover {
                background: rgba(255, 255, 255, 0.2);
                transform: rotate(90deg);
            }
        }
        
        /* Animations */
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .animate-fade-in {
            animation: fadeIn 0.5s ease-out;
        }
        
        /* Badge Styles */
        .status-badge {
            display: inline-flex;
            align-items: center;
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 500;
        }
        
        .status-active {
            background: rgba(72, 187, 120, 0.1);
            color: #48bb78;
            border: 1px solid rgba(72, 187, 120, 0.2);
        }
        
        .status-completed {
            background: rgba(59, 130, 246, 0.1);
            color: #3b82f6;
            border: 1px solid rgba(59, 130, 246, 0.2);
        }
        
        .status-cancelled {
            background: rgba(245, 101, 101, 0.1);
            color: #f56565;
            border: 1px solid rgba(245, 101, 101, 0.2);
        }
    </style>
</head>
<body class="text-white">
   <?php include("nav.php"); ?>

        <!-- Main Content -->
        <div class="main-content">
            <!-- Top Bar -->
            <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-6">
                    <div>
                        <h2 class="text-2xl lg:text-3xl font-bold bg-gradient-to-r from-blue-400 to-purple-400 bg-clip-text text-transparent">
                            Investment Plans
                        </h2>
                        <p class="text-gray-400 mt-2">
                            Grow your wealth with our carefully crafted investment plans
                        </p>
                    </div>
                    <div class="flex items-center gap-4">
                        <div class="hidden lg:block">
                            <div class="flex items-center gap-2 px-4 py-2 bg-gray-800/50 rounded-lg">
                                <i class="fas fa-wallet text-blue-400"></i>
                                <span class="text-sm">Balance: <span class="font-bold text-green-400">$<?php echo number_format($account_balance, 2); ?></span></span>
                            </div>
                        </div>
                        <a href="index.php" class="btn-secondary">
                            <i class="fas fa-arrow-left mr-2"></i> Back to Dashboard
                        </a>
                    </div>
                </div>
            </div>

            <!-- Investment Content -->
            <div class="p-6">
                <!-- Success/Error Messages -->
                <?php if ($success_message): ?>
                    <div class="alert-success">
                        <i class="fas fa-check-circle"></i>
                        <span><?php echo htmlspecialchars($success_message); ?></span>
                    </div>
                <?php endif; ?>
                
                <?php if ($error_message): ?>
                    <div class="alert-error">
                        <i class="fas fa-exclamation-circle"></i>
                        <span><?php echo htmlspecialchars($error_message); ?></span>
                    </div>
                <?php endif; ?>
                
                <!-- Balance Warning for Low Balance -->
                <?php if ($account_balance < 100): ?>
                    <div class="balance-warning">
                        <i class="fas fa-exclamation-triangle"></i>
                        <div class="flex-1">
                            <span class="font-medium">Low Balance Warning:</span> 
                            Your account balance is low ($<?php echo number_format($account_balance, 2); ?>). 
                            Consider <a href="deposit.php" class="text-yellow-300 hover:text-yellow-200 font-medium">adding funds</a> before investing.
                        </div>
                    </div>
                <?php endif; ?>
                
                <!-- Investment Stats -->
                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
                    <!-- Available Balance -->
                    <div class="glass-card p-6 animate-fade-in">
                        <div class="flex items-center justify-between mb-4">
                            <div>
                                <p class="text-gray-400 text-sm">Available Balance</p>
                                <h3 class="text-2xl font-bold mt-1">$<?php echo number_format($account_balance, 2); ?></h3>
                            </div>
                            <div class="w-12 h-12 bg-gradient-to-br from-blue-500/20 to-purple-500/20 rounded-xl flex items-center justify-center">
                                <i class="fas fa-wallet text-xl text-blue-400"></i>
                            </div>
                        </div>
                        <div class="text-sm text-gray-400">For new investments</div>
                    </div>
                    
                    <!-- Total Invested -->
                    <div class="glass-card p-6 animate-fade-in" style="animation-delay: 0.1s">
                        <div class="flex items-center justify-between mb-4">
                            <div>
                                <p class="text-gray-400 text-sm">Total Invested</p>
                                <h3 class="text-2xl font-bold mt-1">$<?php echo number_format($investment_stats['total_invested'], 2); ?></h3>
                            </div>
                            <div class="w-12 h-12 bg-gradient-to-br from-green-500/20 to-emerald-500/20 rounded-xl flex items-center justify-center">
                                <i class="fas fa-chart-line text-xl text-green-400"></i>
                            </div>
                        </div>
                        <div class="text-sm text-gray-400">All-time investments</div>
                    </div>
                    
                    <!-- Active Investments -->
                    <div class="glass-card p-6 animate-fade-in" style="animation-delay: 0.2s">
                        <div class="flex items-center justify-between mb-4">
                            <div>
                                <p class="text-gray-400 text-sm">Active Investments</p>
                                <h3 class="text-2xl font-bold mt-1"><?php echo $investment_stats['active_investments']; ?></h3>
                            </div>
                            <div class="w-12 h-12 bg-gradient-to-br from-yellow-500/20 to-orange-500/20 rounded-xl flex items-center justify-center">
                                <i class="fas fa-bolt text-xl text-yellow-400"></i>
                            </div>
                        </div>
                        <div class="text-sm text-gray-400">Currently running</div>
                    </div>
                    
                    <!-- Total Earnings -->
                    <div class="glass-card p-6 animate-fade-in" style="animation-delay: 0.3s">
                        <div class="flex items-center justify-between mb-4">
                            <div>
                                <p class="text-gray-400 text-sm">Total Earnings</p>
                                <h3 class="text-2xl font-bold mt-1">$<?php echo number_format($investment_stats['total_earnings'], 2); ?></h3>
                            </div>
                            <div class="w-12 h-12 bg-gradient-to-br from-purple-500/20 to-pink-500/20 rounded-xl flex items-center justify-center">
                                <i class="fas fa-money-bill-wave text-xl text-purple-400"></i>
                            </div>
                        </div>
                        <div class="text-sm text-gray-400">From all investments</div>
                    </div>
                </div>

                <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
                    <!-- Left Column: Investment Plans -->
                    <div class="lg:col-span-2">
                        <div class="glass-card p-6 mb-6 animate-fade-in">
                            <h3 class="text-xl font-bold mb-6 flex items-center">
                                <i class="fas fa-gem mr-3 text-yellow-400"></i> Available Investment Plans
                            </h3>
                            
                            <?php if (empty($plans)): ?>
                                <div class="text-center py-8 text-gray-400">
                                    <i class="fas fa-exclamation-circle text-3xl mb-3"></i>
                                    <p>No investment plans available at the moment.</p>
                                    <p class="text-sm mt-2">Please check back later or contact support.</p>
                                </div>
                            <?php else: ?>
                                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                                    <?php foreach ($plans as $plan): ?>
                                        <?php
                                        // Determine badge class based on plan name
                                        $badge_class = 'plan-basic';
                                        $plan_name_lower = strtolower($plan['name']);
                                        if (strpos($plan_name_lower, 'premium') !== false) {
                                            $badge_class = 'plan-premium';
                                        } elseif (strpos($plan_name_lower, 'professional') !== false || strpos($plan_name_lower, 'vip') !== false) {
                                            $badge_class = 'plan-professional';
                                        }
                                        
                                        // Check if user has enough balance for minimum investment
                                        $can_afford_min = $account_balance >= $plan['min_amount'];
                                        $can_afford_max = $account_balance >= $plan['max_amount'];
                                        
                                        // Determine card style based on affordability
                                        $card_style = '';
                                        $tooltip = '';
                                        if (!$can_afford_min) {
                                            $card_style = 'opacity-60 cursor-not-allowed';
                                            $tooltip = 'Insufficient balance for minimum investment';
                                            $needed_amount = $plan['min_amount'] - $account_balance;
                                        }
                                        ?>
                                        <div class="plan-card <?php echo $card_style; ?>" 
                                             onclick="<?php echo $can_afford_min ? 'selectPlan(' . $plan['id'] . ')' : 'showBalanceWarning(' . $plan['min_amount'] . ', ' . $needed_amount . ')'; ?>"
                                             title="<?php echo $tooltip; ?>">
                                            
                                            <?php if (!$can_afford_min): ?>
                                                <div class="insufficient-balance text-sm mb-3">
                                                    <i class="fas fa-exclamation-circle mr-2"></i>
                                                    Need <span class="amount-needed">$<?php echo number_format($needed_amount, 2); ?></span> more
                                                </div>
                                            <?php endif; ?>
                                            
                                            <div class="flex items-start justify-between mb-4">
                                                <div>
                                                    <h4 class="text-lg font-bold"><?php echo htmlspecialchars($plan['name']); ?></h4>
                                                    <span class="<?php echo $badge_class; ?> plan-badge mt-2">
                                                        <?php echo ucfirst($plan['compounding_interval'] ?? 'simple'); ?> interest
                                                    </span>
                                                </div>
                                                <div class="text-right">
                                                    <div class="text-2xl font-bold text-green-400"><?php echo $plan['interest_rate']; ?>%</div>
                                                    <div class="text-sm text-gray-400">Total Return</div>
                                                </div>
                                            </div>
                                            
                                            <div class="mb-4">
                                                <p class="text-gray-400 text-sm mb-3"><?php echo htmlspecialchars($plan['description']); ?></p>
                                            </div>
                                            
                                            <div class="space-y-3 mb-4">
                                                <div class="flex justify-between items-center">
                                                    <span class="text-gray-400 text-sm">Min Investment:</span>
                                                    <span class="font-medium <?php echo !$can_afford_min ? 'text-red-400' : ''; ?>">
                                                        $<?php echo number_format($plan['min_amount'], 2); ?>
                                                        <?php if (!$can_afford_min): ?>
                                                            <i class="fas fa-exclamation-circle ml-1"></i>
                                                        <?php endif; ?>
                                                    </span>
                                                </div>
                                                <div class="flex justify-between items-center">
                                                    <span class="text-gray-400 text-sm">Max Investment:</span>
                                                    <span class="font-medium <?php echo !$can_afford_max ? 'text-yellow-400' : ''; ?>">
                                                        $<?php echo number_format($plan['max_amount'], 2); ?>
                                                        <?php if (!$can_afford_max && $can_afford_min): ?>
                                                            <i class="fas fa-info-circle ml-1" title="Can't afford maximum"></i>
                                                        <?php endif; ?>
                                                    </span>
                                                </div>
                                                <div class="flex justify-between items-center">
                                                    <span class="text-gray-400 text-sm">Duration:</span>
                                                    <span class="font-medium"><?php echo $plan['duration_days']; ?> days</span>
                                                </div>
                                                <div class="flex justify-between items-center">
                                                    <span class="text-gray-400 text-sm">Compounding:</span>
                                                    <span class="font-medium"><?php echo ucfirst($plan['compounding_interval'] ?? 'none'); ?></span>
                                                </div>
                                            </div>
                                            
                                            <div class="border-t border-gray-700/50 pt-4">
                                                <div class="text-sm text-gray-400 mb-2">Example Returns (<?php echo $plan['duration_days']; ?> days):</div>
                                                <div class="grid grid-cols-2 gap-3">
                                                    <div class="bg-gray-800/50 rounded-lg p-3">
                                                        <div class="text-xs text-gray-400">Min Investment</div>
                                                        <div class="font-bold text-green-400">$<?php echo number_format($plan['example_min_return'], 2); ?></div>
                                                        <div class="text-xs text-gray-400 mt-1">
                                                            Profit: $<?php echo number_format($plan['example_min_profit'], 2); ?>
                                                        </div>
                                                    </div>
                                                    <div class="bg-gray-800/50 rounded-lg p-3">
                                                        <div class="text-xs text-gray-400">Max Investment</div>
                                                        <div class="font-bold text-green-400">$<?php echo number_format($plan['example_max_return'], 2); ?></div>
                                                        <div class="text-xs text-gray-400 mt-1">
                                                            Profit: $<?php echo number_format($plan['example_max_profit'], 2); ?>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            <?php endif; ?>
                        </div>
                        
                        <!-- Investment Form (Initially Hidden) -->
                        <div id="investmentForm" class="glass-card p-6 animate-fade-in hidden">
                            <h3 class="text-xl font-bold mb-6 flex items-center">
                                <i class="fas fa-paper-plane mr-3 text-green-400"></i> Invest Now
                            </h3>
                            
                            <form method="POST" action="" id="investForm">
                                <input type="hidden" name="plan_id" id="plan_id" required>
                                
                                <div class="form-group">
                                    <label class="form-label">Selected Plan</label>
                                    <div id="selectedPlanInfo" class="bg-gray-800/50 border border-gray-700 rounded-xl p-4">
                                        <!-- Plan info will be loaded here -->
                                    </div>
                                </div>
                                
                                <div class="form-group">
                                    <label class="form-label">Investment Amount (USD)</label>
                                    <div class="relative">
                                        <span class="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400">$</span>
                                        <input type="number" 
                                               name="amount" 
                                               id="investAmount"
                                               class="form-input pl-8"
                                               step="0.01"
                                               min="0"
                                               placeholder="Enter amount"
                                               required
                                               oninput="updateInvestmentAmount(this.value)">
                                    </div>
                                    <div class="flex justify-between text-xs text-gray-400 mt-2">
                                        <span id="minAmount">Min: $0.00</span>
                                        <span id="investAmountDisplay">$0.00</span>
                                        <span id="maxAmount">Max: $0.00</span>
                                    </div>
                                    <div class="investment-progress">
                                        <div id="investProgress" class="progress-fill" style="width: 0%"></div>
                                    </div>
                                    <div class="text-xs text-gray-400 mt-2">
                                        Available Balance: <span id="availableBalance" class="font-medium text-green-400">$<?php echo number_format($account_balance, 2); ?></span>
                                    </div>
                                    <div id="balanceWarning" class="text-xs text-red-400 mt-2 hidden">
                                        <i class="fas fa-exclamation-circle mr-1"></i>
                                        <span id="balanceWarningText"></span>
                                    </div>
                                </div>
                                
                                <div class="form-group">
                                    <label class="form-label">Expected Return</label>
                                    <div id="expectedReturn" class="bg-gray-800/50 border border-gray-700 rounded-xl p-4">
                                        <div class="text-center text-gray-400">
                                            Enter amount to see expected return
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="mt-8 pt-6 border-t border-gray-700/50">
                                    <div class="flex flex-col sm:flex-row gap-3">
                                        <button type="button" onclick="closeInvestmentForm()" class="btn-secondary flex-1">
                                            <i class="fas fa-times mr-2"></i> Cancel
                                        </button>
                                        <button type="submit" name="invest" class="btn-success flex-1" id="investButton">
                                            <i class="fas fa-check mr-2"></i> Confirm Investment
                                        </button>
                                    </div>
                                </div>
                            </form>
                        </div>
                        
                        <!-- Active Investments -->
                        <div class="glass-card p-6 animate-fade-in">
                            <div class="flex items-center justify-between mb-6">
                                <h3 class="text-xl font-bold flex items-center">
                                    <i class="fas fa-history mr-3 text-blue-400"></i> Active Investments
                                </h3>
                                <a href="investments.php" class="text-sm text-blue-400 hover:text-blue-300">
                                    View All <i class="fas fa-arrow-right ml-1"></i>
                                </a>
                            </div>
                            
                            <?php if (!empty($active_investments)): ?>
                                <div class="space-y-4">
                                  <!-- In the active investments loop, modify the display -->
<?php foreach ($active_investments as $investment): ?>
    <div class="bg-gray-800/50 border border-gray-700 rounded-xl p-4 hover:bg-gray-800/70 transition"
         data-investment-id="<?php echo $investment['id']; ?>">
        <div class="flex flex-col md:flex-row md:items-center justify-between gap-4">
            <div class="flex-1">
                <div class="flex items-start justify-between mb-2">
                    <div>
                        <h4 class="font-bold"><?php echo htmlspecialchars($investment['plan_name']); ?></h4>
                        <p class="text-sm text-gray-400">Investment: <span class="text-green-400 font-medium">$<?php echo number_format($investment['amount'], 2); ?></span></p>
                    </div>
                    <span class="status-badge status-active">Active</span>
                </div>
                
                <div class="mb-3">
                    <div class="flex justify-between text-sm mb-1">
                        <span class="text-gray-400">Progress</span>
                        <span><?php echo number_format($investment['progress_percentage'], 1); ?>%</span>
                    </div>
                    <div class="investment-progress">
                        <div class="progress-fill" style="width: <?php echo min(100, $investment['progress_percentage']); ?>%"></div>
                    </div>
                </div>
                
                <div class="grid grid-cols-2 md:grid-cols-4 gap-3">
                    <div>
                        <div class="text-xs text-gray-400">Start Date</div>
                        <div class="text-sm font-medium"><?php echo date('M d, Y', strtotime($investment['start_date'])); ?></div>
                    </div>
                    <div>
                        <div class="text-xs text-gray-400">End Date</div>
                        <div class="text-sm font-medium"><?php echo date('M d, Y', strtotime($investment['end_date'])); ?></div>
                    </div>
                    <div>
                        <div class="text-xs text-gray-400">Days Left</div>
                        <div class="text-sm font-medium" data-days-remaining><?php echo $investment['days_remaining']; ?></div>
                    </div>
                    <div>
                        <div class="text-xs text-gray-400">Earned So Far</div>
                        <div class="text-sm font-medium text-green-400" data-earned-amount>$<?php echo number_format($investment['actual_return'], 2); ?></div>
                    </div>
                </div>
                
                <div class="mt-3 grid grid-cols-2 gap-3">
                    <div>
                        <div class="text-xs text-gray-400">Expected Profit</div>
                        <div class="text-sm font-medium text-green-400">$<?php echo number_format($investment['total_profit'], 2); ?></div>
                    </div>
                    <div>
                        <div class="text-xs text-gray-400">Daily Profit</div>
                        <div class="text-sm font-medium text-green-400">$<?php echo number_format($investment['daily_profit'], 2); ?></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
<?php endforeach; ?>
                                </div>
                            <?php else: ?>
                                <div class="text-center py-8 text-gray-400">
                                    <i class="fas fa-chart-line text-3xl mb-3"></i>
                                    <p>No active investments found.</p>
                                    <p class="text-sm mt-2">Start investing to see your active investments here.</p>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                    
                    <!-- Right Column: Information & Stats -->
                    <div>
                        <!-- Investment Guide -->
                        <div class="glass-card p-6 mb-6 animate-fade-in" style="animation-delay: 0.2s">
                            <h3 class="text-xl font-bold mb-4 flex items-center">
                                <i class="fas fa-graduation-cap mr-3 text-blue-400"></i> Investment Guide
                            </h3>
                            <div class="space-y-4">
                                <div>
                                    <h4 class="font-medium text-sm mb-2">How It Works</h4>
                                    <ol class="text-sm text-gray-400 space-y-2 pl-4">
                                        <li class="list-decimal">Select an investment plan</li>
                                        <li class="list-decimal">Enter your investment amount</li>
                                        <li class="list-decimal">Funds are deducted from your balance</li>
                                        <li class="list-decimal">Earn returns over the duration</li>
                                        <li class="list-decimal">Receive total return at the end</li>
                                    </ol>
                                </div>
                                
                                <div>
                                    <h4 class="font-medium text-sm mb-2">Key Terms</h4>
                                    <div class="text-sm text-gray-400 space-y-2">
                                        <div>
                                            <span class="font-medium text-gray-300">Total Return:</span> Percentage return over the entire duration
                                        </div>
                                        <div>
                                            <span class="font-medium text-gray-300">Compounding:</span> Interest earned on interest (if applicable)
                                        </div>
                                        <div>
                                            <span class="font-medium text-gray-300">Duration:</span> Investment period in days
                                        </div>
                                        <div>
                                            <span class="font-medium text-gray-300">Principal:</span> Your initial investment amount
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Quick Tips -->
                        <div class="glass-card p-6 mb-6 animate-fade-in" style="animation-delay: 0.3s">
                            <h3 class="text-xl font-bold mb-4 flex items-center">
                                <i class="fas fa-lightbulb mr-3 text-yellow-400"></i> Investment Tips
                            </h3>
                            <div class="space-y-3">
                                <div class="flex items-start gap-3">
                                    <i class="fas fa-diversify text-green-400 mt-1"></i>
                                    <div>
                                        <p class="font-medium text-sm">Diversify</p>
                                        <p class="text-xs text-gray-400">Spread investments across different plans</p>
                                    </div>
                                </div>
                                <div class="flex items-start gap-3">
                                    <i class="fas fa-calendar-check text-blue-400 mt-1"></i>
                                    <div>
                                        <p class="font-medium text-sm">Long-term Focus</p>
                                        <p class="text-xs text-gray-400">Longer durations often yield better returns</p>
                                    </div>
                                </div>
                                <div class="flex items-start gap-3">
                                    <i class="fas fa-redo text-purple-400 mt-1"></i>
                                    <div>
                                        <p class="font-medium text-sm">Reinvest Profits</p>
                                        <p class="text-xs text-gray-400">Compound your earnings for exponential growth</p>
                                    </div>
                                </div>
                                <div class="flex items-start gap-3">
                                    <i class="fas fa-shield-alt text-red-400 mt-1"></i>
                                    <div>
                                        <p class="font-medium text-sm">Risk Management</p>
                                        <p class="text-xs text-gray-400">Only invest what you can afford to lose</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Quick Investment Amounts -->
                        <div class="glass-card p-6 animate-fade-in" style="animation-delay: 0.4s">
                            <h3 class="text-xl font-bold mb-4 flex items-center">
                                <i class="fas fa-bolt mr-3 text-purple-400"></i> Quick Amounts
                            </h3>
                            <div class="grid grid-cols-2 gap-3">
                                <button type="button" onclick="setInvestmentAmount(100)" class="btn-secondary py-3">
                                    $100
                                </button>
                                <button type="button" onclick="setInvestmentAmount(500)" class="btn-secondary py-3">
                                    $500
                                </button>
                                <button type="button" onclick="setInvestmentAmount(1000)" class="btn-secondary py-3">
                                    $1,000
                                </button>
                                <button type="button" onclick="setInvestmentAmount(5000)" class="btn-secondary py-3">
                                    $5,000
                                </button>
                                <button type="button" onclick="setInvestmentAmount(10000)" class="btn-secondary py-3">
                                    $10,000
                                </button>
                                <button type="button" onclick="setInvestmentAmount(25000)" class="btn-secondary py-3">
                                    $25,000
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Footer -->
                <div class="mt-8 text-center">
                    <p class="text-gray-500 text-sm">
                        Need assistance with investments? 
                        <a href="support.php" class="text-blue-400 hover:text-blue-300">Contact Support</a>
                    </p>
                    <p class="text-gray-600 text-xs mt-2">
                        Past performance is not indicative of future results. All investments carry risk.
                    </p>
                </div>
            </div>
        </div>
    </div>

       <!-- JavaScript -->
    <script>
        // Mobile menu toggle functionality
        const menuToggle = document.getElementById('menuToggle');
        const closeSidebar = document.getElementById('closeSidebar');
        const sidebar = document.getElementById('sidebar');
        const sidebarOverlay = document.getElementById('sidebarOverlay');
        const body = document.body;

        // Function to toggle sidebar
        function toggleSidebar() {
            sidebar.classList.toggle('active');
            sidebarOverlay.classList.toggle('active');
            
            if (sidebar.classList.contains('active')) {
                body.classList.add('sidebar-open');
                body.style.overflow = 'hidden';
            } else {
                body.classList.remove('sidebar-open');
                body.style.overflow = '';
            }
        }

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

        // Event listeners for mobile menu
        menuToggle.addEventListener('click', toggleSidebar);
        closeSidebar.addEventListener('click', closeSidebarFunc);
        sidebarOverlay.addEventListener('click', closeSidebarFunc);

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

        // Initialize sidebar state on load
        document.addEventListener('DOMContentLoaded', function() {
            if (window.innerWidth >= 1024) {
                sidebar.classList.add('active');
            }
            
            // Set active nav item
            document.querySelectorAll('.nav-item').forEach(nav => {
                const href = nav.getAttribute('href');
                if (href && href.includes('invest.php')) {
                    nav.classList.add('active');
                } else {
                    nav.classList.remove('active');
                }
            });
        });

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

        // Investment functionality
        let selectedPlan = null;
        const plans = <?php echo json_encode($plans); ?>;
        const userBalance = parseFloat(<?php echo $account_balance; ?>);
        
        function showBalanceWarning(minAmount, neededAmount) {
            showNotification(`Insufficient balance! You need $${neededAmount.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})} more to invest in this plan.`, 'error');
        }
        
        function selectPlan(planId) {
            // Remove selection from all cards
            document.querySelectorAll('.plan-card').forEach(card => {
                card.classList.remove('selected');
            });
            
            // Add selection to clicked card
            event.currentTarget.classList.add('selected');
            
            // Find the selected plan
            selectedPlan = plans.find(plan => plan.id == planId);
            
            if (selectedPlan) {
                // Check if user has enough balance for minimum investment
                if (userBalance < selectedPlan.min_amount) {
                    showNotification(`Insufficient balance! Minimum investment is $${selectedPlan.min_amount.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})}`, 'error');
                    return;
                }
                
                // Set hidden input value
                document.getElementById('plan_id').value = planId;
                
                // Show investment form
                document.getElementById('investmentForm').classList.remove('hidden');
                
                // Scroll to form
                document.getElementById('investmentForm').scrollIntoView({ 
                    behavior: 'smooth',
                    block: 'start'
                });
                
                // Update form with plan info
                updateInvestmentForm(selectedPlan);
                
                // Reset amount to minimum
                document.getElementById('investAmount').value = selectedPlan.min_amount;
                updateInvestmentAmount(selectedPlan.min_amount);
            }
        }
        
        function updateInvestmentForm(plan) {
            // Update selected plan info
            const planInfo = document.getElementById('selectedPlanInfo');
            planInfo.innerHTML = `
                <div class="flex items-start justify-between">
                    <div>
                        <h4 class="font-bold">${plan.name}</h4>
                        <p class="text-sm text-gray-400 mt-1">${plan.description}</p>
                    </div>
                    <div class="text-right">
                        <div class="text-xl font-bold text-green-400">${plan.interest_rate}% Return</div>
                        <div class="text-sm text-gray-400">${plan.duration_days} days</div>
                    </div>
                </div>
                <div class="grid grid-cols-2 gap-4 mt-4">
                    <div>
                        <div class="text-xs text-gray-400">Min Investment</div>
                        <div class="font-medium">$${parseFloat(plan.min_amount).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})}</div>
                    </div>
                    <div>
                        <div class="text-xs text-gray-400">Max Investment</div>
                        <div class="font-medium">$${parseFloat(plan.max_amount).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})}</div>
                    </div>
                    <div>
                        <div class="text-xs text-gray-400">Compounding</div>
                        <div class="font-medium">${plan.compounding_interval ? plan.compounding_interval.charAt(0).toUpperCase() + plan.compounding_interval.slice(1) : 'None'}</div>
                    </div>
                    <div>
                        <div class="text-xs text-gray-400">Example Return</div>
                        <div class="font-medium text-green-400">$${parseFloat(plan.example_min_return).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})}</div>
                    </div>
                </div>
            `;
            
            // Update min/max labels
            document.getElementById('minAmount').textContent = `Min: $${parseFloat(plan.min_amount).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})}`;
            document.getElementById('maxAmount').textContent = `Max: $${parseFloat(plan.max_amount).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})}`;
            
            // Set input min/max attributes
            const amountInput = document.getElementById('investAmount');
            amountInput.min = plan.min_amount;
            amountInput.max = plan.max_amount;
        }
        
        function setInvestmentAmount(amount) {
            if (!selectedPlan) {
                showNotification('Please select an investment plan first', 'error');
                return;
            }
            
            const min = parseFloat(selectedPlan.min_amount);
            const max = parseFloat(selectedPlan.max_amount);
            const clampedAmount = Math.max(min, Math.min(max, amount));
            
            document.getElementById('investAmount').value = clampedAmount;
            updateInvestmentAmount(clampedAmount);
        }
        
        function updateInvestmentAmount(value) {
            if (!selectedPlan) return;
            
            const amount = parseFloat(value) || 0;
            const min = parseFloat(selectedPlan.min_amount);
            const max = parseFloat(selectedPlan.max_amount);
            const balance = userBalance;
            
            // Update display
            document.getElementById('investAmountDisplay').textContent = '$' + amount.toLocaleString('en-US', {
                minimumFractionDigits: 2,
                maximumFractionDigits: 2
            });
            
            // Update progress bar
            const progress = Math.min(100, (amount / max) * 100);
            document.getElementById('investProgress').style.width = progress + '%';
            
            // Show/hide balance warning
            const balanceWarning = document.getElementById('balanceWarning');
            const balanceWarningText = document.getElementById('balanceWarningText');
            const investButton = document.getElementById('investButton');
            
            if (amount < min) {
                document.getElementById('investProgress').style.background = '#f56565';
                balanceWarning.classList.remove('hidden');
                balanceWarningText.textContent = `Amount below minimum investment ($${min.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})})`;
                investButton.disabled = true;
                investButton.classList.add('opacity-50', 'cursor-not-allowed');
            } else if (amount > max) {
                document.getElementById('investProgress').style.background = '#f56565';
                balanceWarning.classList.remove('hidden');
                balanceWarningText.textContent = `Amount exceeds maximum investment ($${max.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})})`;
                investButton.disabled = true;
                investButton.classList.add('opacity-50', 'cursor-not-allowed');
            } else if (amount > balance) {
                document.getElementById('investProgress').style.background = '#f56565';
                balanceWarning.classList.remove('hidden');
                const needed = amount - balance;
                balanceWarningText.textContent = `Insufficient balance. Need $${needed.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})} more`;
                investButton.disabled = true;
                investButton.classList.add('opacity-50', 'cursor-not-allowed');
            } else {
                document.getElementById('investProgress').style.background = 'linear-gradient(90deg, #667eea, #764ba2)';
                balanceWarning.classList.add('hidden');
                investButton.disabled = false;
                investButton.classList.remove('opacity-50', 'cursor-not-allowed');
            }
            
            // Update expected return with detailed ROI calculation
            updateExpectedReturn(amount);
        }
        
        function updateExpectedReturn(amount) {
            if (!selectedPlan) return;
            
            // Calculate all ROI metrics
            const roiResult = calculateDetailedROI(
                amount,
                selectedPlan.interest_rate,
                selectedPlan.duration_days,
                selectedPlan.compounding_interval
            );
            
            // Format dates for display
            const startDate = new Date();
            const endDate = new Date();
            endDate.setDate(startDate.getDate() + selectedPlan.duration_days);
            const startDateStr = startDate.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
            const endDateStr = endDate.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
            
            document.getElementById('expectedReturn').innerHTML = `
                <div class="roi-details">
                    <div class="mb-4">
                        <div class="text-sm text-gray-400">Investment Period</div>
                        <div class="text-sm font-medium">${startDateStr} - ${endDateStr} (${selectedPlan.duration_days} days)</div>
                    </div>
                    
                    <div class="mb-4">
                        <div class="text-sm text-gray-400">Principal Amount</div>
                        <div class="text-lg font-bold">$${amount.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})}</div>
                    </div>
                    
                    <div class="mb-4">
                        <div class="text-sm text-gray-400">Expected Return (After ${selectedPlan.duration_days} days)</div>
                        <div class="text-2xl font-bold text-green-400">$${roiResult.expectedReturn.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})}</div>
                    </div>
                    
                    <div class="grid grid-cols-2 gap-3 mb-4">
                        <div class="bg-gray-800/50 p-3 rounded-lg">
                            <div class="text-xs text-gray-400">Total Profit</div>
                            <div class="text-lg font-bold text-green-400">$${roiResult.profit.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})}</div>
                        </div>
                        <div class="bg-gray-800/50 p-3 rounded-lg">
                            <div class="text-xs text-gray-400">ROI</div>
                            <div class="text-lg font-bold text-green-400">${roiResult.roiPercentage.toFixed(2)}%</div>
                        </div>
                        <div class="bg-gray-800/50 p-3 rounded-lg">
                            <div class="text-xs text-gray-400">Daily ROI</div>
                            <div class="text-lg font-bold text-green-400">${roiResult.dailyROI.toFixed(4)}%</div>
                        </div>
                        <div class="bg-gray-800/50 p-3 rounded-lg">
                            <div class="text-xs text-gray-400">Daily Profit</div>
                            <div class="text-lg font-bold text-green-400">$${roiResult.dailyProfit.toFixed(2)}</div>
                        </div>
                    </div>
                    
                    <div class="bg-gray-900/50 rounded-lg p-4 mb-3">
                        <div class="text-sm font-medium text-gray-300 mb-2">Investment Details:</div>
                        <div class="text-xs text-gray-400 space-y-1">
                            <div class="flex justify-between">
                                <span>Total Return Rate:</span>
                                <span class="font-medium">${selectedPlan.interest_rate}%</span>
                            </div>
                            <div class="flex justify-between">
                                <span>Daily Return Rate:</span>
                                <span class="font-medium">${roiResult.dailyRate.toFixed(4)}%</span>
                            </div>
                            <div class="flex justify-between">
                                <span>Investment Days:</span>
                                <span class="font-medium">${selectedPlan.duration_days}</span>
                            </div>
                        </div>
                    </div>
                    
                    <div class="mt-4 text-xs text-gray-400">
                        <i class="fas fa-info-circle mr-1"></i>
                        Based on ${selectedPlan.interest_rate}% total return over ${selectedPlan.duration_days} days
                    </div>
                </div>
            `;
        }
        
        // UPDATED: ROI calculation function based on your example
        function calculateDetailedROI(principal, interestRate, durationDays, compoundingInterval) {
            // Calculate expected return using simple calculation
            const expectedReturn = calculateExpectedReturn(
                principal,
                interestRate,
                durationDays,
                compoundingInterval
            );
            
            // Calculate basic metrics
            const profit = expectedReturn - principal;
            const roiPercentage = (profit / principal) * 100;
            const dailyROI = roiPercentage / durationDays;
            const dailyProfit = profit / durationDays;
            
            // For display purposes - daily return rate
            const dailyRate = interestRate / durationDays;
            
            return {
                principal: principal,
                expectedReturn: expectedReturn,
                profit: profit,
                roiPercentage: roiPercentage,
                dailyROI: dailyROI,
                dailyProfit: dailyProfit,
                durationDays: durationDays,
                dailyRate: dailyRate,
                interestRate: interestRate
            };
        }
        
        // UPDATED: Expected return calculation based on your example
        function calculateExpectedReturn(principal, interestRate, durationDays, compoundingInterval) {
            // Simple calculation: principal + (principal * interestRate / 100)
            // This gives the total return regardless of compounding for now
            // If you want compounding, we'll need to adjust the formula
            
            const profit = principal * (interestRate / 100);
            
            if (compoundingInterval === 'none') {
                // Simple interest: return principal + profit
                return principal + profit;
            } else {
                // For compounding, we need to calculate based on the compounding interval
                // This is a simplified version - you might want to adjust based on your needs
                return principal + profit;
            }
        }
        
        // Add function to show ROI breakdown in a modal
        function showROIBreakdown() {
            if (!selectedPlan) return;
            
            const amount = parseFloat(document.getElementById('investAmount').value) || 0;
            if (amount <= 0) return;
            
            const roiResult = calculateDetailedROI(
                amount,
                selectedPlan.interest_rate,
                selectedPlan.duration_days,
                selectedPlan.compounding_interval
            );
            
            // Create ROI breakdown modal
            const modalHTML = `
                <div class="fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4">
                    <div class="bg-gray-800 rounded-xl max-w-2xl w-full max-h-[90vh] overflow-y-auto">
                        <div class="p-6 border-b border-gray-700">
                            <div class="flex justify-between items-center">
                                <h3 class="text-xl font-bold">ROI Breakdown</h3>
                                <button onclick="closeROIModal()" class="text-gray-400 hover:text-white">
                                    <i class="fas fa-times text-xl"></i>
                                </button>
                            </div>
                        </div>
                        
                        <div class="p-6">
                            <div class="mb-6">
                                <h4 class="text-lg font-bold mb-2">Investment Details</h4>
                                <div class="grid grid-cols-2 gap-4">
                                    <div>
                                        <div class="text-sm text-gray-400">Plan</div>
                                        <div class="font-medium">${selectedPlan.name}</div>
                                    </div>
                                    <div>
                                        <div class="text-sm text-gray-400">Amount</div>
                                        <div class="font-medium">$${amount.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})}</div>
                                    </div>
                                    <div>
                                        <div class="text-sm text-gray-400">Interest Rate</div>
                                        <div class="font-medium">${selectedPlan.interest_rate}% Total Return</div>
                                    </div>
                                    <div>
                                        <div class="text-sm text-gray-400">Duration</div>
                                        <div class="font-medium">${selectedPlan.duration_days} days</div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="mb-6">
                                <h4 class="text-lg font-bold mb-2">Return Calculation</h4>
                                <div class="bg-gray-900/50 rounded-lg p-4">
                                    <div class="space-y-3">
                                        <div class="flex justify-between">
                                            <span class="text-gray-400">Principal:</span>
                                            <span class="font-medium">$${amount.toFixed(2)}</span>
                                        </div>
                                        <div class="flex justify-between">
                                            <span class="text-gray-400">Total Return Rate:</span>
                                            <span class="font-medium">${selectedPlan.interest_rate}%</span>
                                        </div>
                                        <div class="flex justify-between">
                                            <span class="text-gray-400">Total Profit:</span>
                                            <span class="font-medium text-green-400">$${roiResult.profit.toFixed(2)}</span>
                                        </div>
                                        <div class="flex justify-between border-t border-gray-700 pt-3">
                                            <span class="text-lg font-bold text-gray-300">Total Return:</span>
                                            <span class="text-2xl font-bold text-green-400">$${roiResult.expectedReturn.toFixed(2)}</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="mb-6">
                                <h4 class="text-lg font-bold mb-2">Performance Metrics</h4>
                                <div class="grid grid-cols-2 md:grid-cols-4 gap-3">
                                    <div class="bg-gray-900/50 p-3 rounded-lg">
                                        <div class="text-xs text-gray-400">Total ROI</div>
                                        <div class="text-lg font-bold text-green-400">${roiResult.roiPercentage.toFixed(2)}%</div>
                                    </div>
                                    <div class="bg-gray-900/50 p-3 rounded-lg">
                                        <div class="text-xs text-gray-400">Daily ROI</div>
                                        <div class="text-lg font-bold text-green-400">${roiResult.dailyROI.toFixed(4)}%</div>
                                    </div>
                                    <div class="bg-gray-900/50 p-3 rounded-lg">
                                        <div class="text-xs text-gray-400">Daily Profit</div>
                                        <div class="text-lg font-bold text-green-400">$${roiResult.dailyProfit.toFixed(4)}</div>
                                    </div>
                                    <div class="bg-gray-900/50 p-3 rounded-lg">
                                        <div class="text-xs text-gray-400">Daily Rate</div>
                                        <div class="text-lg font-bold text-green-400">${roiResult.dailyRate.toFixed(4)}%</div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="text-xs text-gray-400">
                                <i class="fas fa-exclamation-triangle mr-1 text-yellow-400"></i>
                                Returns are projections based on the stated interest rate. Actual returns may vary.
                            </div>
                        </div>
                        
                        <div class="p-6 border-t border-gray-700 flex justify-end">
                            <button onclick="closeROIModal()" class="btn-secondary px-6">
                                Close
                            </button>
                        </div>
                    </div>
                </div>
            `;
            
            // Create and append modal
            const modalDiv = document.createElement('div');
            modalDiv.id = 'roi-breakdown-modal';
            modalDiv.innerHTML = modalHTML;
            document.body.appendChild(modalDiv);
            
            // Prevent body scrolling
            document.body.style.overflow = 'hidden';
        }
        
        function closeROIModal() {
            const modal = document.getElementById('roi-breakdown-modal');
            if (modal) {
                modal.remove();
                document.body.style.overflow = '';
            }
        }
        
        // Add ROI breakdown button to expected return section
        document.addEventListener('DOMContentLoaded', function() {
            // This will be called after updateExpectedReturn to add the button
            const observer = new MutationObserver(function(mutations) {
                mutations.forEach(function(mutation) {
                    if (mutation.target.id === 'expectedReturn' && mutation.addedNodes.length > 0) {
                        const roiSection = document.getElementById('expectedReturn');
                        if (roiSection && !roiSection.querySelector('.view-breakdown-btn')) {
                            const breakdownBtn = document.createElement('button');
                            breakdownBtn.className = 'view-breakdown-btn mt-4 text-blue-400 hover:text-blue-300 text-sm flex items-center gap-1';
                            breakdownBtn.innerHTML = '<i class="fas fa-chart-line"></i> View Detailed ROI Breakdown';
                            breakdownBtn.onclick = showROIBreakdown;
                            roiSection.querySelector('.roi-details').appendChild(breakdownBtn);
                        }
                    }
                });
            });
            
            observer.observe(document.getElementById('expectedReturn'), { childList: true, subtree: true });
        });
        
        function closeInvestmentForm() {
            document.getElementById('investmentForm').classList.add('hidden');
            document.querySelectorAll('.plan-card').forEach(card => {
                card.classList.remove('selected');
            });
            selectedPlan = null;
        }
        
        // Form validation
        document.getElementById('investForm').addEventListener('submit', function(e) {
            if (!selectedPlan) {
                e.preventDefault();
                showNotification('Please select an investment plan', 'error');
                return;
            }
            
            const amount = parseFloat(document.getElementById('investAmount').value) || 0;
            const min = parseFloat(selectedPlan.min_amount);
            const max = parseFloat(selectedPlan.max_amount);
            const balance = userBalance;
            
            let hasError = false;
            
            // Validate amount
            if (amount < min) {
                showFieldError('investAmount', `Minimum investment is $${min.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})}`);
                hasError = true;
            } else if (amount > max) {
                showFieldError('investAmount', `Maximum investment is $${max.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})}`);
                hasError = true;
            } else if (amount > balance) {
                showFieldError('investAmount', `Insufficient balance. Available: $${balance.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})}`);
                hasError = true;
            }
            
            if (hasError) {
                e.preventDefault();
                showNotification('Please fix the errors above', 'error');
            } else {
                // Calculate ROI for confirmation
                const roiResult = calculateDetailedROI(
                    amount,
                    selectedPlan.interest_rate,
                    selectedPlan.duration_days,
                    selectedPlan.compounding_interval
                );
                
                // Enhanced confirmation message
                const confirmationMessage = `Investment Confirmation\n\n` +
                    `Plan: ${selectedPlan.name}\n` +
                    `Amount: $${amount.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})}\n` +
                    `Duration: ${selectedPlan.duration_days} days\n` +
                    `Expected Return: $${roiResult.expectedReturn.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})}\n` +
                    `Expected Profit: $${roiResult.profit.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})}\n\n` +
                    `This will deduct $${amount.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})} from your account balance.\n\n` +
                    `Are you sure you want to proceed?`;
                
                if (!confirm(confirmationMessage)) {
                    e.preventDefault();
                }
            }
        });
        
        function showFieldError(fieldId, message) {
            const field = document.getElementById(fieldId);
            const errorDiv = document.createElement('div');
            errorDiv.className = 'error-message text-red-400 text-sm mt-1 flex items-center gap-1';
            errorDiv.innerHTML = `<i class="fas fa-exclamation-circle"></i> ${message}`;
            
            const existingError = field.parentNode.querySelector('.error-message');
            if (existingError) existingError.remove();
            
            field.parentNode.appendChild(errorDiv);
            field.classList.add('border-red-500');
            
            field.addEventListener('input', function() {
                errorDiv.remove();
                this.classList.remove('border-red-500');
            }, { once: true });
        }
        
        function showNotification(message, type = 'info') {
            const notification = document.createElement('div');
            notification.className = `fixed top-6 right-6 px-4 py-3 rounded-xl shadow-xl z-50 ${
                type === 'success' ? 'bg-green-600' : 
                type === 'error' ? 'bg-red-600' : 'bg-blue-600'
            } text-white`;
            notification.innerHTML = `
                <div class="flex items-center gap-3">
                    <i class="fas fa-${type === 'success' ? 'check-circle' : type === 'error' ? 'exclamation-circle' : 'info-circle'}"></i>
                    <span>${message}</span>
                </div>
            `;
            
            document.body.appendChild(notification);
            
            setTimeout(() => {
                notification.style.opacity = '0';
                notification.style.transform = 'translateX(100%)';
                setTimeout(() => notification.remove(), 300);
            }, 3000);
        }
        
        // Keyboard shortcuts for investment form
        document.addEventListener('keydown', function(e) {
            // Ctrl+Enter to submit investment form
            if (e.ctrlKey && e.key === 'Enter' && selectedPlan) {
                const investForm = document.getElementById('investForm');
                if (investForm) {
                    e.preventDefault();
                    investForm.dispatchEvent(new Event('submit'));
                }
            }
            
            // Escape to close investment form
            if (e.key === 'Escape' && document.getElementById('investmentForm').classList.contains('hidden') === false) {
                closeInvestmentForm();
            }
        });
        
    </script>
    
    
   <!-- Simple Real-time Profit Updater -->
<script>
// Simple version - updates every 10 seconds for testing
(function() {
    console.log('Investment updater initializing...');
    
    const userId = <?php echo json_encode($user_id); ?>;
    const hasActiveInvestments = <?php echo !empty($active_investments) ? 'true' : 'false'; ?>;
    
    if (!hasActiveInvestments) {
        console.log('No active investments, updater not needed');
        return;
    }
    
    console.log('Active investments found, starting updater');
    
    // Function to update profits
    function updateProfits() {
        console.log('Updating profits...', new Date().toLocaleTimeString());
        
        // Show loading indicator
        const balanceElement = document.querySelector('[data-account-balance]');
        if (balanceElement) {
            balanceElement.style.opacity = '0.5';
        }
        
        // Make AJAX request
        fetch('process_investment_ajax.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: 'action=process_profits'
        })
        .then(response => response.json())
        .then(data => {
            console.log('Profit update response:', data);
            
            if (data.success && data.total_profit > 0) {
                // Show notification
                showNotification(`+$${data.total_profit.toFixed(2)} profit added!`, 'success');
                
                // Refresh balance display
                refreshBalance();
            }
        })
        .catch(error => {
            console.error('Error updating profits:', error);
        })
        .finally(() => {
            if (balanceElement) {
                balanceElement.style.opacity = '1';
            }
        });
    }
    
    // Function to refresh balance display
    function refreshBalance() {
        fetch('process_investment_ajax.php?action=get_updates')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // Update balance displays
                document.querySelectorAll('[data-account-balance]').forEach(el => {
                    el.textContent = '$' + data.account_balance.toFixed(2);
                });
                
                document.querySelectorAll('[data-total-earnings]').forEach(el => {
                    el.textContent = '$' + data.total_earnings.toFixed(2);
                });
                
                // Update investment cards
                if (data.investments) {
                    data.investments.forEach(inv => {
                        const card = document.querySelector(`[data-investment-id="${inv.id}"]`);
                        if (card) {
                            const earnedEl = card.querySelector('[data-earned-amount]');
                            if (earnedEl) {
                                earnedEl.textContent = '$' + inv.actual_return.toFixed(2);
                            }
                            
                            // Update progress bar
                            const progressBar = card.querySelector('.progress-fill');
                            if (progressBar && inv.expected_return) {
                                const progress = (inv.actual_return / (inv.expected_return - inv.amount)) * 100;
                                progressBar.style.width = Math.min(progress, 100) + '%';
                            }
                        }
                    });
                }
                
                // Update last update time
                const timeEl = document.getElementById('last-update-time');
                if (timeEl) {
                    timeEl.textContent = new Date().toLocaleTimeString();
                }
            }
        })
        .catch(error => {
            console.error('Error refreshing balance:', error);
        });
    }
    
    // Notification function
    function showNotification(message, type = 'info') {
        const notification = document.createElement('div');
        notification.className = `fixed bottom-4 right-4 px-4 py-3 rounded-lg shadow-lg z-50 ${
            type === 'success' ? 'bg-green-600' : 'bg-blue-600'
        } text-white animate-fade-in-up`;
        notification.innerHTML = `
            <div class="flex items-center gap-3">
                <i class="fas fa-${type === 'success' ? 'check-circle' : 'info-circle'}"></i>
                <span>${message}</span>
            </div>
        `;
        
        document.body.appendChild(notification);
        
        setTimeout(() => {
            notification.style.opacity = '0';
            notification.style.transform = 'translateY(20px)';
            setTimeout(() => notification.remove(), 500);
        }, 3000);
    }
    
    // Run immediately
    setTimeout(() => {
        updateProfits();
        refreshBalance();
    }, 1000);
    
    // Then run every 10 seconds for testing (change to 60000 for production)
    setInterval(updateProfits, 10000);
    setInterval(refreshBalance, 5000); // Refresh display more often
    
    // Add data attributes to balance elements
    document.addEventListener('DOMContentLoaded', function() {
        // Find balance elements and add data attributes
        document.querySelectorAll('.glass-card.p-6 .text-2xl.font-bold').forEach(el => {
            const parentText = el.closest('.glass-card')?.querySelector('p')?.textContent || '';
            if (parentText.includes('Available Balance')) {
                el.setAttribute('data-account-balance', '');
            } else if (parentText.includes('Total Earnings')) {
                el.setAttribute('data-total-earnings', '');
            }
        });
        
        // Add last update time display
        const topBar = document.querySelector('.border-b.border-gray-800\\/50.p-6');
        if (topBar && !document.getElementById('last-update-time')) {
            const timeDiv = document.createElement('div');
            timeDiv.className = 'text-xs text-gray-500 mt-2';
            timeDiv.innerHTML = `
                <span>Last update: <span id="last-update-time">just now</span></span>
                <span class="mx-2">•</span>
                <span>Updates every 10 seconds (test mode)</span>
            `;
            topBar.appendChild(timeDiv);
        }
    });
})();
</script>

<!-- Add CSS animations -->
<style>
@keyframes fadeInUp {
    from {
        opacity: 0;
        transform: translateY(20px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.animate-fade-in-up {
    animation: fadeInUp 0.3s ease-out;
}
</style>
<!-- Add data attributes to balance elements -->
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Add data attributes to balance elements for easy updating
    document.querySelectorAll('.glass-card.p-6 .text-2xl.font-bold').forEach(el => {
        const parentText = el.closest('.glass-card').querySelector('p')?.textContent || '';
        if (parentText.includes('Available Balance')) {
            el.setAttribute('data-account-balance', '');
        } else if (parentText.includes('Total Earnings')) {
            el.setAttribute('data-total-earnings', '');
        }
    });
    
    // Add total profit today display
    const statsContainer = document.querySelector('.grid.grid-cols-1.md\\:grid-cols-2.lg\\:grid-cols-4');
    if (statsContainer && !document.getElementById('total-profit-today')) {
        const profitCard = document.createElement('div');
        profitCard.className = 'glass-card p-6 animate-fade-in';
        profitCard.innerHTML = `
            <div class="flex items-center justify-between mb-4">
                <div>
                    <p class="text-gray-400 text-sm">Today's Profit</p>
                    <h3 class="text-2xl font-bold mt-1" id="total-profit-today">$0.00</h3>
                </div>
                <div class="w-12 h-12 bg-gradient-to-br from-yellow-500/20 to-orange-500/20 rounded-xl flex items-center justify-center">
                    <i class="fas fa-clock text-xl text-yellow-400"></i>
                </div>
            </div>
            <div class="text-sm text-gray-400">Live updates every minute</div>
        `;
        statsContainer.appendChild(profitCard);
    }
});
</script>
</body>
</html>