<?php
$page_title = "Investment Details";
require_once '../config/config.php';

require_once '../includes/user_auth.php';
require_once '../includes/functions.php';


$db = Database::getInstance()->connect();
$user_id = $_SESSION['user_id'];

// Check if viewing specific investment or creating new
if (isset($_GET['id'])) {
    // View existing investment
    $investment_id = intval($_GET['id']);
    
    $sql = "
        SELECT 
            i.*, 
            p.name as plan_name,
            p.description as plan_description,
            p.daily_return,
            p.duration_days,
            p.min_amount,
            p.max_amount,
            p.total_return,
            p.principal_return,
            p.features,
            p.status as plan_status
        FROM investments i
        JOIN investment_plans p ON i.plan_id = p.id
        WHERE i.id = ? AND i.user_id = ?
    ";
    
    $stmt = $db->prepare($sql);
    $stmt->execute([$investment_id, $user_id]);
    $investment = $stmt->fetch();
    
    if (!$investment) {
        $_SESSION['error'] = "Investment not found";
        header('Location: investments.php');
        exit();
    }
    
    $mode = 'view';
    
} else {
    // Create new investment
    $mode = 'create';
    
    // Get available plans
    $plans_sql = "SELECT * FROM investment_plans WHERE status = 'active' ORDER BY min_amount";
    $plans_stmt = $db->query($plans_sql);
    $plans = $plans_stmt->fetchAll();
    
    // Get user balance
    $user_stmt = $db->prepare("SELECT balance FROM users WHERE id = ?");
    $user_stmt->execute([$user_id]);
    $user = $user_stmt->fetch();

    // Handle Reinvest Action
    $preselect_plan = 0;
    $preselect_amount = 0;
    if (isset($_GET['reinvest'])) {
        $old_inv_id = intval($_GET['reinvest']);
        $old_inv_stmt = $db->prepare("SELECT plan_id, amount FROM investments WHERE id = ? AND user_id = ?");
        $old_inv_stmt->execute([$old_inv_id, $user_id]);
        $old_inv = $old_inv_stmt->fetch();
        if ($old_inv) {
            $preselect_plan = $old_inv['plan_id'];
            $preselect_amount = $old_inv['amount'];
        }
    } elseif (isset($_GET['plan_id'])) {
        $preselect_plan = intval($_GET['plan_id']);
    }
}

// Handle new investment creation
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $mode == 'create' && isset($_POST['create_investment'])) {
    $plan_id = intval($_POST['plan_id']);
    $amount = floatval($_POST['amount']);
    
    // Get plan details
    $plan_stmt = $db->prepare("SELECT * FROM investment_plans WHERE id = ? AND status = 'active'");
    $plan_stmt->execute([$plan_id]);
    $plan = $plan_stmt->fetch();
    
    // Get user balance
    $balance_stmt = $db->prepare("SELECT balance FROM users WHERE id = ?");
    $balance_stmt->execute([$user_id]);
    $user_balance = $balance_stmt->fetch()['balance'];
    
    $errors = [];
    
    // Validation
    if (!$plan) {
        $errors[] = "Invalid investment plan";
    }
    
    if ($amount < $plan['min_amount']) {
        $errors[] = "Minimum investment for this plan is $" . number_format($plan['min_amount'], 2);
    }
    
    if ($amount > $plan['max_amount']) {
        $errors[] = "Maximum investment for this plan is $" . number_format($plan['max_amount'], 2);
    }
    
    if ($amount > $user_balance) {
        $errors[] = "Insufficient balance. Available: $" . number_format($user_balance, 2);
    }
    
    if (empty($errors)) {
        try {
            $db->beginTransaction();
            
            // Calculate daily profit
            $daily_profit = $amount * ($plan['daily_return'] / 100);
            
            // Calculate end date
            $end_date = date('Y-m-d H:i:s', strtotime("+" . $plan['duration_days'] . " days"));
            
            // Create investment
            $insert_stmt = $db->prepare("
                INSERT INTO investments (
                    user_id, plan_id, amount, daily_profit, 
                    total_profit, start_date, end_date, status
                ) VALUES (?, ?, ?, ?, 0, NOW(), ?, 'running')
            ");
            
            $insert_stmt->execute([
                $user_id, $plan_id, $amount, $daily_profit, $end_date
            ]);
            
            $investment_id = $db->lastInsertId();
            
            // Deduct amount from user balance
            $update_stmt = $db->prepare("UPDATE users SET balance = balance - ? WHERE id = ?");
            $update_stmt->execute([$amount, $user_id]);
            
            // Record transaction
            $reference = 'INV' . time() . rand(1000, 9999);
            $description = 'Investment in ' . $plan['name'];
            $tx_stmt = $db->prepare("
                INSERT INTO transactions (
                    user_id, type, amount, method, description, reference, status
                ) VALUES (?, 'investment', ?, 'balance', ?, ?, 'completed')
            ");
            
            $tx_stmt->execute([
                $user_id, $amount, $description, $reference
            ]);
            
            // Log activity
            $log_stmt = $db->prepare("
                INSERT INTO activity_logs (user_id, action, description, ip_address, user_agent, details, created_at)
                VALUES (?, 'investment_create', 'New investment created', ?, ?, ?, NOW())
            ");

            $log_stmt->execute([
                $user_id,
                $_SERVER['REMOTE_ADDR'] ?? '',
                $_SERVER['HTTP_USER_AGENT'] ?? '',
                json_encode([
                    'investment_id' => $investment_id,
                    'plan_id' => $plan_id,
                    'amount' => $amount,
                    'daily_return' => $plan['daily_return'],
                    'duration' => $plan['duration_days']
                ])
            ]);
            
            $db->commit();
            
            $_SESSION['success'] = "Investment created successfully!";
            header('Location: investment.php?id=' . $investment_id);
            exit();
            
        } catch (Exception $e) {
            $db->rollBack();
            $errors[] = "Failed to create investment: " . $e->getMessage();
        }
    }
}
?>
<?php require_once '../includes/header_user.php'; ?>

<div class="container-fluid">
    <!-- Page Header -->
    <div class="mb-6">
        <div class="flex justify-between items-center">
            <div>
                <h1 class="text-2xl font-bold">
                    <?php echo $mode == 'view' ? 'Investment Details' : 'New Investment'; ?>
                </h1>
                <p class="text-gray-600">
                    <?php echo $mode == 'view' ? 'Track your investment progress' : 'Start growing your wealth'; ?>
                </p>
            </div>
            <div>
                <a href="investments.php" class="bg-gray-200 text-gray-800 px-4 py-2 rounded-lg hover:bg-gray-300">
                    <i class="fas fa-arrow-left mr-2"></i>Back to Investments
                </a>
            </div>
        </div>
    </div>

    <!-- Messages -->
    <?php if (isset($_SESSION['success'])): ?>
    <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded mb-4">
        <?php echo $_SESSION['success']; unset($_SESSION['success']); ?>
    </div>
    <?php endif; ?>
    
    <?php if (isset($_SESSION['error'])): ?>
    <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
        <?php echo $_SESSION['error']; unset($_SESSION['error']); ?>
    </div>
    <?php endif; ?>
    
    <?php if (!empty($errors)): ?>
    <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
        <ul class="list-disc list-inside">
            <?php foreach ($errors as $error): ?>
            <li><?php echo $error; ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
    <?php endif; ?>

    <?php if ($mode == 'view'): ?>
    <!-- View Investment Details -->
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <!-- Left Column: Investment Details -->
        <div class="lg:col-span-2 space-y-6">
            <!-- Investment Card -->
            <div class="bg-white rounded-xl shadow">
                <div class="p-6 border-b">
                    <div class="flex justify-between items-center">
                        <div>
                            <h2 class="text-xl font-bold"><?php echo htmlspecialchars($investment['plan_name']); ?></h2>
                            <p class="text-gray-600">Investment ID: <?php echo $investment['id']; ?></p>
                        </div>
                        <span class="px-4 py-2 rounded-full text-sm font-semibold <?php
                            echo $investment['status'] == 'running' ? 'bg-green-100 text-green-800' :
                                ($investment['status'] == 'completed' ? 'bg-blue-100 text-blue-800' :
                                'bg-red-100 text-red-800');
                        ?>">
                            <?php echo ucfirst($investment['status']); ?>
                        </span>
                    </div>
                </div>
                
                <div class="p-6">
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <!-- Amount & Profit -->
                        <div class="space-y-4">
                            <div>
                                <p class="text-sm text-gray-600">Investment Amount</p>
                                <p class="text-3xl font-bold text-green-600">$<?php echo number_format($investment['amount'], 2); ?></p>
                            </div>
                            
                            <div>
                                <p class="text-sm text-gray-600">Daily Profit</p>
                                <p class="text-2xl font-bold">$<?php echo number_format($investment['daily_profit'], 2); ?></p>
                                <p class="text-sm text-gray-500"><?php echo $investment['daily_return']; ?>% daily</p>
                            </div>
                            
                            <div>
                                <p class="text-sm text-gray-600">Total Profit Earned</p>
                                <p class="text-2xl font-bold text-green-600">$<?php echo number_format($investment['total_profit'], 2); ?></p>
                            </div>
                        </div>
                        
                        <!-- Timeline -->
                        <div class="space-y-4">
                            <?php
                            $start_date = new DateTime($investment['start_date']);
                            $end_date = new DateTime($investment['end_date']);
                            $current_date = new DateTime();
                            
                            $total_days = $investment['duration_days'];
                            
                            if ($current_date > $end_date) {
                                $days_elapsed = $total_days;
                            } else {
                                $days_elapsed = $current_date->diff($start_date)->days;
                            }
                            
                            $days_left = max(0, $total_days - $days_elapsed);
                            $progress = min(100, ($days_elapsed / $total_days) * 100);
                            
                            $expected_total = $investment['daily_profit'] * $total_days;
                            ?>
                            
                            <div>
                                <p class="text-sm text-gray-600 mb-2">Investment Period</p>
                                <div class="space-y-2">
                                    <div class="flex justify-between">
                                        <span class="text-sm">Start Date:</span>
                                        <span class="font-medium"><?php echo date('M d, Y', strtotime($investment['start_date'])); ?></span>
                                    </div>
                                    <div class="flex justify-between">
                                        <span class="text-sm">End Date:</span>
                                        <span class="font-medium"><?php echo date('M d, Y', strtotime($investment['end_date'])); ?></span>
                                    </div>
                                    <div class="flex justify-between">
                                        <span class="text-sm">Days Elapsed:</span>
                                        <span class="font-medium"><?php echo $days_elapsed; ?> / <?php echo $total_days; ?></span>
                                    </div>
                                    <div class="flex justify-between">
                                        <span class="text-sm">Days Remaining:</span>
                                        <span class="font-medium <?php echo $days_left > 0 ? 'text-green-600' : 'text-red-600'; ?>">
                                            <?php echo $days_left; ?>
                                        </span>
                                    </div>
                                </div>
                            </div>
                            
                            <div>
                                <div class="flex justify-between text-sm mb-1">
                                    <span>Progress</span>
                                    <span><?php echo number_format($progress, 1); ?>%</span>
                                </div>
                                <div class="w-full bg-gray-200 rounded-full h-2">
                                    <div class="bg-green-600 h-2 rounded-full" style="width: <?php echo $progress; ?>%"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <?php if ($investment['plan_description']): ?>
                    <div class="mt-6 border-t pt-6">
                        <p class="text-sm text-gray-600 mb-2">Plan Description</p>
                        <p class="text-gray-700"><?php echo htmlspecialchars($investment['plan_description']); ?></p>
                    </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Profit History -->
            <div class="bg-white rounded-xl shadow">
                <div class="p-6 border-b">
                    <h3 class="text-lg font-bold">Recent Profit History</h3>
                </div>
                <div class="p-6">
                    <?php
                    // Get profit history for this investment
                    $profit_sql = "
                        SELECT * FROM transactions 
                        WHERE user_id = ? AND type = 'profit' 
                        AND description LIKE ?
                        ORDER BY created_at DESC 
                        LIMIT 10
                    ";
                    
                    $profit_stmt = $db->prepare($profit_sql);
                    $profit_stmt->execute([$user_id, "%investment #" . $investment['id'] . "%"]);
                    $profit_history = $profit_stmt->fetchAll();
                    ?>
                    
                    <?php if (!empty($profit_history)): ?>
                    <div class="overflow-x-auto">
                        <table class="w-full">
                            <thead class="bg-gray-50">
                                <tr>
                                    <th class="p-3 text-left text-sm">Date</th>
                                    <th class="p-3 text-left text-sm">Amount</th>
                                    <th class="p-3 text-left text-sm">Description</th>
                                    <th class="p-3 text-left text-sm">Status</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-gray-100">
                                <?php foreach ($profit_history as $profit): ?>
                                <tr>
                                    <td class="p-3"><?php echo date('M d, Y', strtotime($profit['created_at'])); ?></td>
                                    <td class="p-3 font-medium text-green-600">$<?php echo number_format($profit['amount'], 2); ?></td>
                                    <td class="p-3 text-sm text-gray-600"><?php echo htmlspecialchars($profit['description']); ?></td>
                                    <td class="p-3">
                                        <span class="px-2 py-1 rounded-full text-xs <?php echo $profit['status'] == 'completed' ? 'bg-green-100 text-green-800' : 'bg-yellow-100 text-yellow-800'; ?>">
                                            <?php echo ucfirst($profit['status']); ?>
                                        </span>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <?php else: ?>
                    <p class="text-gray-500 text-center py-4">No profit history yet</p>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        
        <!-- Right Column: Actions & Info -->
        <div class="space-y-6">
            <!-- Expected Returns -->
            <div class="bg-white rounded-xl shadow p-6">
                <h3 class="text-lg font-bold mb-4">Expected Returns</h3>
                <div class="space-y-3">
                    <?php
                    $daily_return = $investment['daily_profit'];
                    $weekly_return = $daily_return * 7;
                    $monthly_return = $daily_return * 30;
                    $total_return = $daily_return * $total_days;
                    ?>
                    
                    <div class="flex justify-between">
                        <span class="text-gray-600">Daily:</span>
                        <span class="font-bold text-green-600">$<?php echo number_format($daily_return, 2); ?></span>
                    </div>
                    <div class="flex justify-between">
                        <span class="text-gray-600">Weekly:</span>
                        <span class="font-bold text-green-600">$<?php echo number_format($weekly_return, 2); ?></span>
                    </div>
                    <div class="flex justify-between">
                        <span class="text-gray-600">Monthly:</span>
                        <span class="font-bold text-green-600">$<?php echo number_format($monthly_return, 2); ?></span>
                    </div>
                    <div class="flex justify-between border-t pt-3">
                        <span class="text-gray-600 font-semibold">Total Expected:</span>
                        <span class="font-bold text-green-600 text-xl">$<?php echo number_format($total_return, 2); ?></span>
                    </div>
                </div>
            </div>
            
            <!-- Quick Actions -->
            <div class="bg-white rounded-xl shadow p-6">
                <h3 class="text-lg font-bold mb-4">Quick Actions</h3>
                <div class="space-y-3">
                    <?php if ($investment['status'] == 'running'): ?>
                    <button onclick="addFunds(<?php echo $investment['id']; ?>)" 
                            class="w-full bg-green-600 text-white py-2 rounded-lg hover:bg-green-700">
                        <i class="fas fa-plus-circle mr-2"></i>Add Funds
                    </button>
                    
                    <button onclick="reinvestProfits(<?php echo $investment['id']; ?>)" 
                            class="w-full bg-blue-600 text-white py-2 rounded-lg hover:bg-blue-700">
                        <i class="fas fa-redo mr-2"></i>Reinvest Profits
                    </button>
                    
                    <button onclick="withdrawProfits(<?php echo $investment['id']; ?>)" 
                            class="w-full bg-purple-600 text-white py-2 rounded-lg hover:bg-purple-700">
                        <i class="fas fa-hand-holding-usd mr-2"></i>Withdraw Profits
                    </button>
                    
                    <button onclick="cancelInvestment(<?php echo $investment['id']; ?>)" 
                            class="w-full bg-red-600 text-white py-2 rounded-lg hover:bg-red-700">
                        <i class="fas fa-times-circle mr-2"></i>Cancel Investment
                    </button>
                    <?php elseif ($investment['status'] == 'completed'): ?>
                    <button onclick="reinvestCompleted(<?php echo $investment['id']; ?>)" 
                            class="w-full bg-green-600 text-white py-2 rounded-lg hover:bg-green-700">
                        <i class="fas fa-redo mr-2"></i>Reinvest
                    </button>
                    <?php endif; ?>
                    
                    <button onclick="exportStatement(<?php echo $investment['id']; ?>)" 
                            class="w-full bg-gray-600 text-white py-2 rounded-lg hover:bg-gray-700">
                        <i class="fas fa-download mr-2"></i>Export Statement
                    </button>
                </div>
            </div>
            
            <!-- Plan Features -->
            <?php if (!empty($investment['features'])): 
                $features = json_decode($investment['features'], true);
            ?>
            <div class="bg-white rounded-xl shadow p-6">
                <h3 class="text-lg font-bold mb-4">Plan Features</h3>
                <ul class="space-y-2">
                    <?php foreach ($features as $feature): ?>
                    <li class="flex items-center">
                        <i class="fas fa-check text-green-500 mr-2"></i>
                        <span class="text-sm"><?php echo htmlspecialchars($feature); ?></span>
                    </li>
                    <?php endforeach; ?>
                </ul>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <?php elseif ($mode == 'create'): ?>
    <!-- Create New Investment -->
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <!-- Investment Plans -->
        <div class="lg:col-span-2">
            <div class="bg-white rounded-xl shadow p-6">
                <h3 class="text-lg font-bold mb-4">Select Investment Plan</h3>
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <?php foreach ($plans as $plan): 
                        $features = json_decode($plan['features'] ?? '[]', true);
                        $total_return = $plan['daily_return'] * $plan['duration_days'];
                    ?>
                    <div class="border rounded-lg p-6 hover:border-purple-500 hover:shadow-md transition-all">
                        <div class="flex justify-between items-start mb-4">
                            <div>
                                <h4 class="text-xl font-bold"><?php echo htmlspecialchars($plan['name']); ?></h4>
                                <p class="text-sm text-gray-600"><?php echo $plan['duration_days']; ?> days</p>
                            </div>
                            <div class="text-right">
                                <p class="text-2xl font-bold text-green-600"><?php echo $plan['daily_return']; ?>%</p>
                                <p class="text-sm text-gray-600">daily</p>
                            </div>
                        </div>
                        
                        <div class="mb-4">
                            <p class="text-sm text-gray-600 mb-2">Investment Range</p>
                            <p class="font-bold">$<?php echo number_format($plan['min_amount'], 0); ?> - $<?php echo number_format($plan['max_amount'], 0); ?></p>
                        </div>
                        
                        <?php if (!empty($features)): ?>
                        <div class="mb-4">
                            <p class="text-sm text-gray-600 mb-2">Features</p>
                            <ul class="space-y-1">
                                <?php foreach (array_slice($features, 0, 3) as $feature): ?>
                                <li class="flex items-center text-sm">
                                    <i class="fas fa-check text-green-500 mr-2 text-xs"></i>
                                    <?php echo htmlspecialchars($feature); ?>
                                </li>
                                <?php endforeach; ?>
                            </ul>
                        </div>
                        <?php endif; ?>
                        
                        <div class="mb-4">
                            <p class="text-sm text-gray-600 mb-2">Total Return</p>
                            <p class="text-lg font-bold text-purple-600"><?php echo $total_return; ?>%</p>
                        </div>
                        
                        <button type="button" 
                                onclick="selectPlan(<?php echo $plan['id']; ?>, '<?php echo addslashes($plan['name']); ?>', <?php echo $plan['min_amount']; ?>, <?php echo $plan['max_amount']; ?>, <?php echo $plan['daily_return']; ?>)"
                                class="w-full bg-purple-600 text-white py-2 rounded-lg hover:bg-purple-700">
                            Select Plan
                        </button>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
            
            <!-- Investment Form -->
            <div class="mt-6 bg-white rounded-xl shadow p-6">
                <h3 class="text-lg font-bold mb-4">Create Investment</h3>
                
                <form method="POST" action="" class="space-y-6">
                    <input type="hidden" id="selected_plan_id" name="plan_id" required>
                    
                    <!-- Selected Plan Info -->
                    <div id="selectedPlanInfo" class="hidden bg-blue-50 border border-blue-200 rounded-lg p-4">
                        <div class="flex justify-between items-center">
                            <div>
                                <h4 id="selectedPlanName" class="font-bold text-blue-800"></h4>
                                <p id="selectedPlanDetails" class="text-sm text-blue-700"></p>
                            </div>
                            <button type="button" onclick="clearSelection()" class="text-blue-600 hover:text-blue-800">
                                <i class="fas fa-times"></i>
                            </button>
                        </div>
                    </div>
                    
                    <!-- Amount -->
                    <div>
                        <label class="block text-gray-700 font-medium mb-2">Investment Amount ($)</label>
                        <input type="number" id="amount" name="amount" step="0.01" min="0"
                               class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 text-lg font-bold"
                               placeholder="0.00"
                               oninput="validateAndCalculateReturns()"
                               required>
                        <div id="amountValidation" class="text-sm mt-2"></div>
                        <div class="flex justify-between text-sm text-gray-600 mt-2">
                            <span id="amountRange">Select a plan first</span>
                            <span>Available: $<?php echo number_format($user['balance'], 2); ?></span>
                        </div>
                    </div>
                    
                    <!-- Returns Calculator -->
                    <div class="bg-gray-50 border border-gray-200 rounded-lg p-6">
                        <h4 class="font-bold mb-4">Expected Returns</h4>
                        <div class="space-y-3">
                            <div class="flex justify-between">
                                <span class="text-gray-600">Daily Return:</span>
                                <span id="dailyReturn" class="font-bold">$0.00</span>
                            </div>
                            <div class="flex justify-between">
                                <span class="text-gray-600">Weekly Return:</span>
                                <span id="weeklyReturn" class="font-bold">$0.00</span>
                            </div>
                            <div class="flex justify-between">
                                <span class="text-gray-600">Monthly Return:</span>
                                <span id="monthlyReturn" class="font-bold">$0.00</span>
                            </div>
                            <div class="flex justify-between border-t pt-3">
                                <span class="text-gray-600 font-semibold">Total Return:</span>
                                <span id="totalReturn" class="font-bold text-green-600 text-xl">$0.00</span>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Terms Agreement -->
                    <div class="border-t pt-6">
                        <label class="flex items-start">
                            <input type="checkbox" name="agree_terms" required class="mt-1 mr-3">
                            <span class="text-gray-700 text-sm">
                                I agree to the <a href="../terms.php" class="text-blue-600 hover:text-blue-800">Terms and Conditions</a> 
                                and understand that investments carry risks. I have read and understood the investment plan details.
                            </span>
                        </label>
                    </div>
                    
                    <!-- Submit -->
                    <div class="border-t pt-6">
                        <button type="submit" name="create_investment" 
                                class="w-full bg-gradient-to-r from-green-600 to-blue-600 text-white font-bold py-3 px-4 rounded-lg hover:opacity-90 disabled:opacity-50 disabled:cursor-not-allowed"
                                id="submitButton" disabled>
                            <i class="fas fa-chart-line mr-2"></i>Create Investment
                        </button>
                    </div>
                </form>
            </div>
        </div>
        
        <!-- Sidebar -->
        <div class="space-y-6">
            <!-- Balance Info -->
            <div class="bg-gradient-to-r from-blue-500 to-purple-600 text-white rounded-xl p-6">
                <div class="flex justify-between items-center">
                    <div>
                        <p class="text-sm">Available Balance</p>
                        <h2 class="text-3xl font-bold">$<?php echo number_format($user['balance'], 2); ?></h2>
                    </div>
                    <i class="fas fa-wallet text-4xl opacity-80"></i>
                </div>
                <div class="mt-4">
                    <a href="deposit.php" class="block bg-white text-blue-600 font-bold py-2 rounded-lg text-center hover:bg-gray-100">
                        <i class="fas fa-plus-circle mr-2"></i>Add Funds
                    </a>
                </div>
            </div>
            
            <!-- Investment Tips -->
            <div class="bg-white rounded-xl shadow p-6">
                <h4 class="font-bold mb-3">Investment Tips</h4>
                <ul class="space-y-3 text-sm">
                    <li class="flex items-start">
                        <i class="fas fa-check-circle text-green-500 mt-1 mr-2"></i>
                        <span>Start with amounts you can afford</span>
                    </li>
                    <li class="flex items-start">
                        <i class="fas fa-check-circle text-green-500 mt-1 mr-2"></i>
                        <span>Diversify across different plans</span>
                    </li>
                    <li class="flex items-start">
                        <i class="fas fa-check-circle text-green-500 mt-1 mr-2"></i>
                        <span>Reinvest profits for compound growth</span>
                    </li>
                    <li class="flex items-start">
                        <i class="fas fa-check-circle text-green-500 mt-1 mr-2"></i>
                        <span>Monitor your investments regularly</span>
                    </li>
                </ul>
            </div>
            
            <!-- Quick Stats -->
            <div class="bg-white rounded-xl shadow p-6">
                <h4 class="font-bold mb-3">Investment Statistics</h4>
                <div class="space-y-3">
                    <?php
                    $stats_sql = "
                        SELECT 
                            COUNT(*) as total_investments,
                            SUM(amount) as total_invested,
                            SUM(total_profit) as total_profits
                        FROM investments 
                        WHERE user_id = ?
                    ";
                    
                    $stats_stmt = $db->prepare($stats_sql);
                    $stats_stmt->execute([$user_id]);
                    $user_stats = $stats_stmt->fetch();
                    ?>
                    
                    <div class="flex justify-between">
                        <span class="text-gray-600">Total Investments:</span>
                        <span class="font-bold"><?php echo number_format($user_stats['total_investments']); ?></span>
                    </div>
                    <div class="flex justify-between">
                        <span class="text-gray-600">Total Invested:</span>
                        <span class="font-bold">$<?php echo number_format($user_stats['total_invested'] ?? 0, 2); ?></span>
                    </div>
                    <div class="flex justify-between">
                        <span class="text-gray-600">Total Profits:</span>
                        <span class="font-bold text-green-600">$<?php echo number_format($user_stats['total_profits'] ?? 0, 2); ?></span>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>
</div>

<?php require_once '../includes/footer.php'; ?>

<script>
// Notification function (Tailwind style)
function showNotification(message, type = 'info') {
    const container = document.getElementById('notification-container');
    const notification = document.createElement('div');
    
    // Tailwind classes for styling
    const baseClasses = 'transform transition-all duration-300 ease-in-out translate-x-full bg-white rounded-lg shadow-lg p-4 flex items-center space-x-3 min-w-[300px] border-l-4';
    const typeClasses = type === 'success' ? 'border-green-500' : (type === 'error' ? 'border-red-500' : 'border-blue-500');
    const iconClass = type === 'success' ? 'fa-check-circle text-green-500' : (type === 'error' ? 'fa-exclamation-circle text-red-500' : 'fa-info-circle text-blue-500');
    
    notification.className = `${baseClasses} ${typeClasses}`;
    notification.innerHTML = `
        <i class="fas ${iconClass} text-xl"></i>
        <div class="flex-1">
            <p class="text-sm font-medium text-gray-900">${message}</p>
        </div>
        <button onclick="this.parentElement.remove()" class="text-gray-400 hover:text-gray-500">
            <i class="fas fa-times"></i>
        </button>
    `;

    container.appendChild(notification);

    // Animate in
    requestAnimationFrame(() => {
        notification.classList.remove('translate-x-full');
    });

    // Auto dismiss
    setTimeout(() => {
        notification.classList.add('translate-x-full');
        setTimeout(() => {
            notification.remove();
        }, 3000);
    }, 3000);
}

<?php if ($mode == 'view'): ?>
// Investment actions
function addFunds(investmentId) {
    const amount = prompt('Enter amount to add to investment:');
    if (amount && amount > 0) {
        $.ajax({
            url: '../api/add-investment-funds.php',
            method: 'POST',
            data: { investment_id: investmentId, amount: amount },
            success: function(response) {
                const result = typeof response === 'string' ? JSON.parse(response) : response;
                showNotification(result.message, result.success ? 'success' : 'error');
                if (result.success) {
                    location.reload();
                }
            }
        });
    }
}

function reinvestProfits(investmentId) {
    if (confirm('Reinvest all profits from this investment?')) {
        $.ajax({
            url: '../api/reinvest-profits.php',
            method: 'POST',
            data: { investment_id: investmentId },
            success: function(response) {
                const result = typeof response === 'string' ? JSON.parse(response) : response;
                showNotification(result.message, result.success ? 'success' : 'error');
                if (result.success) {
                    location.reload();
                }
            }
        });
    }
}

function withdrawProfits(investmentId) {
    if (confirm('Withdraw available profits to your balance?')) {
        $.ajax({
            url: '../api/withdraw-profits.php',
            method: 'POST',
            data: { investment_id: investmentId },
            success: function(response) {
                const result = typeof response === 'string' ? JSON.parse(response) : response;
                showNotification(result.message, result.success ? 'success' : 'error');
                if (result.success) {
                    location.reload();
                }
            }
        });
    }
}

function cancelInvestment(investmentId) {
    if (confirm('Cancel this investment? Principal may be returned based on plan rules.')) {
        $.ajax({
            url: '../api/cancel-investment.php',
            method: 'POST',
            data: { investment_id: investmentId },
            success: function(response) {
                const result = typeof response === 'string' ? JSON.parse(response) : response;
                showNotification(result.message, result.success ? 'success' : 'error');
                if (result.success) {
                    location.reload();
                }
            }
        });
    }
}

function reinvestCompleted(investmentId) {
    if (confirm('Reinvest this completed investment?')) {
        window.location.href = 'investment.php?reinvest=' + investmentId;
    }
}

function exportStatement(investmentId) {
    window.open(`../api/export-investment-statement.php?id=${investmentId}`, '_blank');
}

<?php elseif ($mode == 'create'): ?>
// Investment creation
let selectedPlan = null;
const availableBalance = <?php echo floatval($user['balance']); ?>;

function selectPlan(planId, planName, minAmount, maxAmount, dailyReturn) {
    selectedPlan = {
        id: planId,
        name: planName,
        minAmount: minAmount,
        maxAmount: maxAmount,
        dailyReturn: dailyReturn
    };
    
    document.getElementById('selected_plan_id').value = planId;
    document.getElementById('selectedPlanInfo').classList.remove('hidden');
    
    // Update plan info display
    document.getElementById('selectedPlanName').textContent = planName;
    document.getElementById('selectedPlanDetails').textContent =
        `Min: $${minAmount.toFixed(2)} | Max: $${maxAmount.toFixed(2)} | ${dailyReturn}% daily`;
    
    // Update amount range
    document.getElementById('amountRange').textContent =
        `Range: $${minAmount.toFixed(2)} - $${maxAmount.toFixed(2)}`;
    
    // Set default amount to minimum
    document.getElementById('amount').value = minAmount;
    document.getElementById('amount').min = minAmount;
    document.getElementById('amount').max = maxAmount;
    
    // Enable submit button
    document.getElementById('submitButton').disabled = false;
    
    // Calculate returns
    validateAndCalculateReturns();

    // Show notification
    showNotification(`Selected plan: ${planName}`, 'success');
}

// Auto-select plan if reinvesting
<?php if (isset($preselect_plan) && $preselect_plan > 0): ?>
document.addEventListener('DOMContentLoaded', function() {
    // Find the button for this plan and click it
    const planBtn = document.querySelector(`button[onclick*="selectPlan(<?php echo $preselect_plan; ?>,"]`);
    if (planBtn) {
        planBtn.click();
        document.getElementById('amount').value = "<?php echo $preselect_amount; ?>";
        validateAndCalculateReturns();
    }
});
<?php endif; ?>

function clearSelection() {
    selectedPlan = null;
    document.getElementById('selected_plan_id').value = '';
    document.getElementById('selectedPlanInfo').classList.add('hidden');
    document.getElementById('amount').value = '';
    document.getElementById('amountRange').textContent = 'Select a plan first';
    document.getElementById('submitButton').disabled = true;
    resetReturns();
}

function validateAndCalculateReturns() {
    if (!selectedPlan) {
        document.getElementById('amountValidation').innerHTML = '<span class="text-red-600">Please select a plan first</span>';
        return;
    }
    
    const amount = parseFloat(document.getElementById('amount').value) || 0;
    const validationDiv = document.getElementById('amountValidation');
    
    // Allow empty input
    if (amount === 0 || document.getElementById('amount').value === '') {
        validationDiv.innerHTML = '';
        resetReturns();
        return;
    }
    
    // Check minimum
    if (amount < selectedPlan.minAmount) {
        validationDiv.innerHTML = `<span class="text-orange-600">Minimum: $${selectedPlan.minAmount.toFixed(2)}</span>`;
        resetReturns();
        return;
    }
    
    // Check maximum
    if (amount > selectedPlan.maxAmount) {
        validationDiv.innerHTML = `<span class="text-orange-600">Maximum: $${selectedPlan.maxAmount.toFixed(2)}</span>`;
        resetReturns();
        return;
    }
    
    // Check balance
    if (amount > availableBalance) {
        validationDiv.innerHTML = `<span class="text-red-600">Exceeds available balance: $${availableBalance.toFixed(2)}</span>`;
        resetReturns();
        return;
    }
    
    // Valid amount - show success and calculate
    validationDiv.innerHTML = '<span class="text-green-600">✓ Valid amount</span>';
    
    // Calculate returns
    const dailyReturn = amount * (selectedPlan.dailyReturn / 100);
    const weeklyReturn = dailyReturn * 7;
    const monthlyReturn = dailyReturn * 30;
    const totalReturn = dailyReturn * 90; // Assuming 90 days for display
    
    // Update display
    document.getElementById('dailyReturn').textContent = '$' + dailyReturn.toFixed(2);
    document.getElementById('weeklyReturn').textContent = '$' + weeklyReturn.toFixed(2);
    document.getElementById('monthlyReturn').textContent = '$' + monthlyReturn.toFixed(2);
    document.getElementById('totalReturn').textContent = '$' + totalReturn.toFixed(2);
}

function resetReturns() {
    document.getElementById('dailyReturn').textContent = '$0.00';
    document.getElementById('weeklyReturn').textContent = '$0.00';
    document.getElementById('monthlyReturn').textContent = '$0.00';
    document.getElementById('totalReturn').textContent = '$0.00';
}

// Form validation
document.querySelector('form').addEventListener('submit', function(e) {
    if (!selectedPlan) {
        e.preventDefault();
        showNotification('Please select an investment plan', 'error');
        return false;
    }
    
    const amount = parseFloat(document.getElementById('amount').value) || 0;
    
    if (amount < selectedPlan.minAmount) {
        e.preventDefault();
        showNotification(`Minimum investment for this plan is $${selectedPlan.minAmount.toFixed(2)}`, 'error');
        return false;
    } 
    
    if (amount > selectedPlan.maxAmount) {
        e.preventDefault();
        showNotification(`Maximum investment for this plan is $${selectedPlan.maxAmount.toFixed(2)}`, 'error');
        return false;
    }
    
    if (amount > availableBalance) {
        e.preventDefault();
        showNotification(`Insufficient balance. Available: $${availableBalance.toFixed(2)}`, 'error');
        return false;
    }
    
    return true;
});
<?php endif; ?>
</script>