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

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

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

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

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

// Check if investments tables exist
$checkPlansTable = "SHOW TABLES LIKE 'investment_plans'";
$checkUserInvestmentsTable = "SHOW TABLES LIKE 'user_investments'";

$plansTableExists = $conn->query($checkPlansTable)->num_rows > 0;
$userInvestmentsTableExists = $conn->query($checkUserInvestmentsTable)->num_rows > 0;

// Create tables if they don't exist
if (!$plansTableExists) {
    $createPlansTable = "
    CREATE TABLE investment_plans (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(100) NOT NULL,
        description TEXT,
        min_amount DECIMAL(15,2) NOT NULL DEFAULT 0.00,
        max_amount DECIMAL(15,2) DEFAULT NULL,
        interest_rate DECIMAL(5,2) NOT NULL,
        duration_days INT NOT NULL,
        compounding_interval ENUM('daily', 'weekly', 'monthly', 'quarterly', 'annually') DEFAULT 'monthly',
        status ENUM('active', 'inactive') DEFAULT 'active',
        features TEXT DEFAULT NULL,
        created_by INT DEFAULT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX idx_status (status),
        INDEX idx_created_at (created_at)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
    ";
    $conn->query($createPlansTable);
}

if (!$userInvestmentsTableExists) {
    $createUserInvestmentsTable = "
    CREATE TABLE user_investments (
        id INT AUTO_INCREMENT PRIMARY KEY,
        user_id INT NOT NULL,
        plan_id INT NOT NULL,
        amount DECIMAL(15,2) NOT NULL,
        expected_return DECIMAL(15,2) DEFAULT 0.00,
        actual_return DECIMAL(15,2) DEFAULT 0.00,
        status ENUM('pending', 'active', 'completed', 'cancelled', 'failed') DEFAULT 'pending',
        start_date DATE,
        end_date DATE,
        next_payout_date DATE,
        transaction_id VARCHAR(100),
        payment_method VARCHAR(50),
        payment_proof VARCHAR(255),
        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)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
    ";
    $conn->query($createUserInvestmentsTable);
}

// Handle form submissions
$success_message = '';
$error_message = '';

// Add/Edit Investment Plan
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['save_plan'])) {
        $plan_id = $_POST['plan_id'] ?? 0;
        $name = trim($_POST['name']);
        $description = trim($_POST['description']);
        $min_amount = floatval($_POST['min_amount']);
        $max_amount = !empty($_POST['max_amount']) ? floatval($_POST['max_amount']) : NULL;
        $interest_rate = floatval($_POST['interest_rate']);
        $duration_days = intval($_POST['duration_days']);
        $compounding_interval = $_POST['compounding_interval'];
        $status = $_POST['status'];
        $features = isset($_POST['features']) ? implode('|', $_POST['features']) : '';
        
        // Validation
        if ($min_amount < 0 || $interest_rate <= 0 || $duration_days <= 0) {
            $error_message = "Invalid input values!";
        } else {
            if ($plan_id > 0) {
                // Update existing plan
                $query = "UPDATE investment_plans SET 
                          name = ?, description = ?, min_amount = ?, max_amount = ?, 
                          interest_rate = ?, duration_days = ?, compounding_interval = ?,
                          status = ?, features = ?, updated_at = CURRENT_TIMESTAMP 
                          WHERE id = ?";
                $stmt = $conn->prepare($query);
                $stmt->bind_param("ssdddisssi", $name, $description, $min_amount, $max_amount,
                                 $interest_rate, $duration_days, $compounding_interval,
                                 $status, $features, $plan_id);
            } else {
                // Insert new plan
                $query = "INSERT INTO investment_plans (name, description, min_amount, max_amount, 
                          interest_rate, duration_days, compounding_interval, status, features, created_by) 
                          VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                $stmt = $conn->prepare($query);
                $stmt->bind_param("ssdddisssi", $name, $description, $min_amount, $max_amount,
                                 $interest_rate, $duration_days, $compounding_interval,
                                 $status, $features, $admin_id);
            }
            
            if ($stmt->execute()) {
                $success_message = "Investment plan " . ($plan_id > 0 ? "updated" : "added") . " successfully!";
            } else {
                $error_message = "Error saving plan: " . $conn->error;
            }
            $stmt->close();
        }
    }
    
    // Delete plan
    if (isset($_POST['delete_plan'])) {
        $plan_id = intval($_POST['plan_id']);
        
        // Check if plan has active investments
        $checkQuery = "SELECT COUNT(*) as investment_count FROM user_investments WHERE plan_id = ? AND status IN ('active', 'pending')";
        $checkStmt = $conn->prepare($checkQuery);
        $checkStmt->bind_param("i", $plan_id);
        $checkStmt->execute();
        $checkResult = $checkStmt->get_result();
        $checkData = $checkResult->fetch_assoc();
        $checkStmt->close();
        
        if ($checkData['investment_count'] > 0) {
            $error_message = "Cannot delete plan with active or pending investments!";
        } else {
            $query = "DELETE FROM investment_plans WHERE id = ?";
            $stmt = $conn->prepare($query);
            $stmt->bind_param("i", $plan_id);
            
            if ($stmt->execute()) {
                $success_message = "Investment plan deleted successfully!";
            } else {
                $error_message = "Error deleting plan: " . $conn->error;
            }
            $stmt->close();
        }
    }
    
    // Update user investment status
    if (isset($_POST['update_investment_status'])) {
        $investment_id = intval($_POST['investment_id']);
        $new_status = $_POST['status'];
        $admin_notes = trim($_POST['admin_notes'] ?? '');
        
        $query = "UPDATE user_investments SET status = ?, admin_notes = ? WHERE id = ?";
        $stmt = $conn->prepare($query);
        $stmt->bind_param("ssi", $new_status, $admin_notes, $investment_id);
        
        if ($stmt->execute()) {
            $success_message = "Investment status updated successfully!";
        } else {
            $error_message = "Error updating investment status: " . $conn->error;
        }
        $stmt->close();
    }
    
    // Add manual user investment
    if (isset($_POST['add_user_investment'])) {
        $user_id = intval($_POST['user_id']);
        $plan_id = intval($_POST['plan_id']);
        $amount = floatval($_POST['amount']);
        $status = $_POST['status'];
        
        // Get plan details
        $planQuery = "SELECT * FROM investment_plans WHERE id = ?";
        $planStmt = $conn->prepare($planQuery);
        $planStmt->bind_param("i", $plan_id);
        $planStmt->execute();
        $planResult = $planStmt->get_result();
        
        if ($planResult->num_rows > 0) {
            $plan = $planResult->fetch_assoc();
            
            // Validate amount
            if ($amount < $plan['min_amount'] || ($plan['max_amount'] && $amount > $plan['max_amount'])) {
                $error_message = "Amount must be between $" . $plan['min_amount'] . " and $" . ($plan['max_amount'] ?? 'unlimited');
            } else {
                // Calculate expected return
                $expected_return = $amount * (1 + ($plan['interest_rate'] / 100 * $plan['duration_days'] / 365));
                
                // Generate transaction ID
                $transaction_id = 'INV-' . time() . '-' . $user_id;
                
                $query = "INSERT INTO user_investments (user_id, plan_id, amount, expected_return, 
                          status, start_date, end_date, transaction_id, created_at) 
                          VALUES (?, ?, ?, ?, ?, CURDATE(), 
                          DATE_ADD(CURDATE(), INTERVAL ? DAY), ?, CURRENT_TIMESTAMP)";
                $stmt = $conn->prepare($query);
                $stmt->bind_param("iiddsis", $user_id, $plan_id, $amount, $expected_return,
                                 $status, $plan['duration_days'], $transaction_id);
                
                if ($stmt->execute()) {
                    $success_message = "Manual investment added successfully!";
                } else {
                    $error_message = "Error adding investment: " . $conn->error;
                }
                $stmt->close();
            }
        }
        $planStmt->close();
    }
    
    // Update user investment
    if (isset($_POST['update_user_investment'])) {
        $investment_id = intval($_POST['investment_id']);
        $amount = floatval($_POST['amount']);
        $status = $_POST['status'];
        $admin_notes = trim($_POST['admin_notes'] ?? '');
        
        // Get current investment details
        $query = "SELECT * FROM user_investments WHERE id = ?";
        $stmt = $conn->prepare($query);
        $stmt->bind_param("i", $investment_id);
        $stmt->execute();
        $result = $stmt->get_result();
        $investment = $result->fetch_assoc();
        $stmt->close();
        
        if ($investment) {
            // Get plan details for recalculation
            $planQuery = "SELECT * FROM investment_plans WHERE id = ?";
            $planStmt = $conn->prepare($planQuery);
            $planStmt->bind_param("i", $investment['plan_id']);
            $planStmt->execute();
            $planResult = $planStmt->get_result();
            $plan = $planResult->fetch_assoc();
            $planStmt->close();
            
            // Calculate expected return
            $expected_return = $amount * (1 + ($plan['interest_rate'] / 100 * $plan['duration_days'] / 365));
            
            $query = "UPDATE user_investments SET 
                      amount = ?, expected_return = ?, status = ?, admin_notes = ?,
                      updated_at = CURRENT_TIMESTAMP WHERE id = ?";
            $stmt = $conn->prepare($query);
            $stmt->bind_param("ddssi", $amount, $expected_return, $status, $admin_notes, $investment_id);
            
            if ($stmt->execute()) {
                $success_message = "Investment updated successfully!";
            } else {
                $error_message = "Error updating investment: " . $conn->error;
            }
            $stmt->close();
        }
    }
    
    // Delete user investment
    if (isset($_POST['delete_user_investment'])) {
        $investment_id = intval($_POST['investment_id']);
        
        $query = "DELETE FROM user_investments WHERE id = ?";
        $stmt = $conn->prepare($query);
        $stmt->bind_param("i", $investment_id);
        
        if ($stmt->execute()) {
            $success_message = "Investment deleted successfully!";
        } else {
            $error_message = "Error deleting investment: " . $conn->error;
        }
        $stmt->close();
    }
}

// Get action parameters
$action = $_GET['action'] ?? '';
$plan_id = $_GET['plan_id'] ?? 0;
$investment_id = $_GET['investment_id'] ?? 0;

// Fetch all investment plans
$plansQuery = "SELECT ip.*, a.email as created_by_email 
               FROM investment_plans ip 
               LEFT JOIN admin_table a ON ip.created_by = a.id 
               ORDER BY ip.created_at DESC";
$plansResult = $conn->query($plansQuery);
$plans = [];
if ($plansResult) {
    while ($row = $plansResult->fetch_assoc()) {
        $plans[] = $row;
    }
}

// Fetch plan for editing
$editPlan = null;
if ($plan_id > 0 && $action == 'edit') {
    $query = "SELECT * FROM investment_plans WHERE id = ?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("i", $plan_id);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result) {
        $editPlan = $result->fetch_assoc();
    }
    $stmt->close();
}

// Fetch all user investments with details
$userInvestmentsQuery = "
    SELECT ui.*, u.username, u.email, u.full_name, u.phone, u.country,
           ip.name as plan_name, ip.interest_rate, ip.duration_days, 
           ip.compounding_interval, ip.description as plan_description
    FROM user_investments ui
    JOIN users u ON ui.user_id = u.id
    JOIN investment_plans ip ON ui.plan_id = ip.id
    ORDER BY ui.created_at DESC
";
$userInvestmentsResult = $conn->query($userInvestmentsQuery);
$userInvestments = [];
if ($userInvestmentsResult) {
    while ($row = $userInvestmentsResult->fetch_assoc()) {
        $userInvestments[] = $row;
    }
}

// Fetch users for manual investment
$usersQuery = "SELECT id, username, email, full_name, account_status FROM users WHERE account_status = 'active' ORDER BY username";
$usersResult = $conn->query($usersQuery);
$users = [];
if ($usersResult) {
    while ($row = $usersResult->fetch_assoc()) {
        $users[] = $row;
    }
}

// Fetch investment details for viewing/editing
$viewInvestment = null;
$editInvestment = null;
if ($investment_id > 0) {
    $query = "
        SELECT ui.*, u.username, u.email, u.full_name, u.phone, u.country, u.account_status,
               ip.name as plan_name, ip.interest_rate, ip.duration_days, 
               ip.compounding_interval, ip.description as plan_description,
               ip.min_amount, ip.max_amount
        FROM user_investments ui
        JOIN users u ON ui.user_id = u.id
        JOIN investment_plans ip ON ui.plan_id = ip.id
        WHERE ui.id = ?
    ";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("i", $investment_id);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows > 0) {
        $investmentData = $result->fetch_assoc();
        if ($action == 'view') {
            $viewInvestment = $investmentData;
        } elseif ($action == 'edit-investment') {
            $editInvestment = $investmentData;
        }
    }
    $stmt->close();
}

// Calculate statistics
$stats = [
    'total_plans' => count($plans),
    'active_plans' => 0,
    'total_investments' => count($userInvestments),
    'active_investments' => 0,
    'pending_investments' => 0,
    'total_invested' => 0,
    'total_returns' => 0
];

foreach ($plans as $plan) {
    if ($plan['status'] == 'active') {
        $stats['active_plans']++;
    }
}

foreach ($userInvestments as $investment) {
    if ($investment['status'] == 'active') {
        $stats['active_investments']++;
        $stats['total_invested'] += $investment['amount'];
    }
    if ($investment['status'] == 'pending') {
        $stats['pending_investments']++;
    }
    if ($investment['status'] == 'completed') {
        $stats['total_returns'] += $investment['actual_return'];
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Investment Management - Unify Grant</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: {
                            50: '#eff6ff',
                            100: '#dbeafe',
                            200: '#bfdbfe',
                            300: '#93c5fd',
                            400: '#60a5fa',
                            500: '#3b82f6',
                            600: '#2563eb',
                            700: '#1d4ed8',
                            800: '#1e40af',
                            900: '#1e3a8a',
                        }
                    },
                    fontFamily: {
                        'inter': ['Inter', 'system-ui', 'sans-serif'],
                    }
                }
            }
        }
    </script>
    <style>
        body {
            font-family: 'Inter', sans-serif;
        }
        
        .investment-card {
            transition: all 0.3s ease;
        }
        
        .investment-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
        }
        
        .status-active { background-color: #d1fae5; color: #065f46; }
        .status-completed { background-color: #dbeafe; color: #1e40af; }
        .status-pending { background-color: #fef3c7; color: #92400e; }
        .status-cancelled { background-color: #fee2e2; color: #991b1b; }
        
        .tab-active {
            background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
            color: white;
        }
        
        .modal-overlay {
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 9999;
        }
    </style>
</head>
<body class="bg-gray-50 font-inter">

<?php include("nav.php"); ?>

    <!-- Main Content -->
    <div class="main-content ml-64">
        <!-- Header -->
        <header class="bg-white shadow-sm border-b border-gray-200 px-8 py-4">
            <div class="flex items-center justify-between">
                <div>
                    <h2 class="text-2xl font-bold text-gray-800">Investment Management</h2>
                    <p class="text-gray-600">Manage investment plans and user investments</p>
                </div>
                <div class="flex items-center space-x-4">
                    <button onclick="showTab('plans')" id="tab-plans-btn" class="px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition tab-active">
                        <i class="fas fa-chart-line mr-2"></i>
                        Investment Plans
                    </button>
                    <button onclick="showTab('investments')" id="tab-investments-btn" class="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition">
                        <i class="fas fa-users mr-2"></i>
                        User Investments
                    </button>
                    <button onclick="showTab('add-investment')" id="tab-add-investment-btn" class="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition">
                        <i class="fas fa-plus-circle mr-2"></i>
                        Add Manual Investment
                    </button>
                </div>
            </div>
        </header>

        <!-- Main Content -->
        <main class="p-8">
            <!-- Success/Error Messages -->
            <?php if ($success_message): ?>
            <div class="mb-6 p-4 bg-green-50 border border-green-200 rounded-lg flex items-center">
                <i class="fas fa-check-circle text-green-600 text-lg mr-3"></i>
                <span class="text-green-800"><?php echo htmlspecialchars($success_message); ?></span>
            </div>
            <?php endif; ?>
            
            <?php if ($error_message): ?>
            <div class="mb-6 p-4 bg-red-50 border border-red-200 rounded-lg flex items-center">
                <i class="fas fa-exclamation-circle text-red-600 text-lg mr-3"></i>
                <span class="text-red-800"><?php echo htmlspecialchars($error_message); ?></span>
            </div>
            <?php endif; ?>

            <!-- Statistics -->
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
                <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 investment-card">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm font-medium text-gray-600">Total Plans</p>
                            <p class="text-3xl font-bold text-gray-800 mt-2"><?php echo $stats['total_plans']; ?></p>
                        </div>
                        <div class="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
                            <i class="fas fa-chart-line text-blue-600 text-xl"></i>
                        </div>
                    </div>
                    <div class="mt-4">
                        <p class="text-sm text-gray-600">
                            <?php echo $stats['active_plans']; ?> active
                        </p>
                    </div>
                </div>

                <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 investment-card">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm font-medium text-gray-600">Total Investments</p>
                            <p class="text-3xl font-bold text-gray-800 mt-2"><?php echo $stats['total_investments']; ?></p>
                        </div>
                        <div class="w-12 h-12 bg-green-100 rounded-lg flex items-center justify-center">
                            <i class="fas fa-users text-green-600 text-xl"></i>
                        </div>
                    </div>
                    <div class="mt-4">
                        <p class="text-sm text-gray-600">
                            <?php echo $stats['active_investments']; ?> active
                        </p>
                    </div>
                </div>

                <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 investment-card">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm font-medium text-gray-600">Total Invested</p>
                            <p class="text-3xl font-bold text-gray-800 mt-2">$<?php echo number_format($stats['total_invested'], 2); ?></p>
                        </div>
                        <div class="w-12 h-12 bg-purple-100 rounded-lg flex items-center justify-center">
                            <i class="fas fa-money-bill-wave text-purple-600 text-xl"></i>
                        </div>
                    </div>
                    <div class="mt-4">
                        <p class="text-sm text-gray-600">
                            Active investments only
                        </p>
                    </div>
                </div>

                <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 investment-card">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm font-medium text-gray-600">Pending Review</p>
                            <p class="text-3xl font-bold text-gray-800 mt-2"><?php echo $stats['pending_investments']; ?></p>
                        </div>
                        <div class="w-12 h-12 bg-yellow-100 rounded-lg flex items-center justify-center">
                            <i class="fas fa-clock text-yellow-600 text-xl"></i>
                        </div>
                    </div>
                    <div class="mt-4">
                        <a href="#investments-tab" onclick="showTab('investments'); filterInvestments('pending')" 
                           class="text-primary-600 hover:text-primary-800 text-sm font-medium">
                            Review →
                        </a>
                    </div>
                </div>
            </div>

            <!-- Investment Plans Tab -->
            <div id="plans-tab" class="tab-content">
                <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
                    <div class="p-6 border-b border-gray-200">
                        <div class="flex items-center justify-between">
                            <h3 class="text-lg font-semibold text-gray-800">Investment Plans</h3>
                            <button onclick="showPlanForm()" class="px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition">
                                <i class="fas fa-plus mr-2"></i>
                                Add New Plan
                            </button>
                        </div>
                    </div>
                    
                    <div class="overflow-x-auto">
                        <table class="w-full">
                            <thead>
                                <tr class="bg-gray-50 text-left text-sm text-gray-500">
                                    <th class="py-3 px-6 font-medium">Plan Name</th>
                                    <th class="py-3 px-6 font-medium">Interest Rate</th>
                                    <th class="py-3 px-6 font-medium">Min Amount</th>
                                    <th class="py-3 px-6 font-medium">Duration</th>
                                    <th class="py-3 px-6 font-medium">Compounding</th>
                                    <th class="py-3 px-6 font-medium">Status</th>
                                    <th class="py-3 px-6 font-medium">Created By</th>
                                    <th class="py-3 px-6 font-medium">Actions</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-gray-200">
                                <?php if (empty($plans)): ?>
                                <tr>
                                    <td colspan="8" class="py-8 text-center text-gray-500">
                                        <i class="fas fa-chart-line text-3xl mb-2 block"></i>
                                        No investment plans found
                                    </td>
                                </tr>
                                <?php else: ?>
                                <?php foreach ($plans as $plan): ?>
                                <tr class="hover:bg-gray-50 transition">
                                    <td class="py-4 px-6">
                                        <div>
                                            <p class="font-medium text-gray-800"><?php echo htmlspecialchars($plan['name']); ?></p>
                                            <p class="text-sm text-gray-500"><?php echo htmlspecialchars(substr($plan['description'], 0, 50)) . '...'; ?></p>
                                        </div>
                                    </td>
                                    <td class="py-4 px-6">
                                        <span class="px-2 py-1 bg-green-100 text-green-800 text-sm font-medium rounded-full">
                                            <?php echo $plan['interest_rate']; ?>%
                                        </span>
                                    </td>
                                    <td class="py-4 px-6">
                                        <p class="text-gray-800">$<?php echo number_format($plan['min_amount'], 2); ?></p>
                                        <?php if ($plan['max_amount']): ?>
                                        <p class="text-sm text-gray-500">Max: $<?php echo number_format($plan['max_amount'], 2); ?></p>
                                        <?php endif; ?>
                                    </td>
                                    <td class="py-4 px-6">
                                        <p class="text-gray-800"><?php echo $plan['duration_days']; ?> days</p>
                                    </td>
                                    <td class="py-4 px-6">
                                        <span class="text-sm text-gray-600"><?php echo ucfirst($plan['compounding_interval']); ?></span>
                                    </td>
                                    <td class="py-4 px-6">
                                        <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium <?php echo $plan['status'] == 'active' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'; ?>">
                                            <?php echo ucfirst($plan['status']); ?>
                                        </span>
                                    </td>
                                    <td class="py-4 px-6">
                                        <p class="text-sm text-gray-600"><?php echo htmlspecialchars($plan['created_by_email'] ?? 'System'); ?></p>
                                        <p class="text-xs text-gray-500"><?php echo date('M d, Y', strtotime($plan['created_at'])); ?></p>
                                    </td>
                                    <td class="py-4 px-6">
                                        <div class="flex space-x-2">
                                            <a href="?action=edit&plan_id=<?php echo $plan['id']; ?>" class="text-blue-600 hover:text-blue-800" title="Edit">
                                                <i class="fas fa-edit"></i>
                                            </a>
                                            <form method="POST" class="inline" onsubmit="return confirm('Are you sure you want to delete this plan?')">
                                                <input type="hidden" name="plan_id" value="<?php echo $plan['id']; ?>">
                                                <button type="submit" name="delete_plan" class="text-red-600 hover:text-red-800" title="Delete">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </form>
                                            <a href="#investments-tab" onclick="showTab('investments'); filterByPlan(<?php echo $plan['id']; ?>)" 
                                               class="text-purple-600 hover:text-purple-800" title="View Investments">
                                                <i class="fas fa-eye"></i>
                                            </a>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- User Investments Tab -->
            <div id="investments-tab" class="tab-content hidden">
                <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
                    <div class="p-6 border-b border-gray-200">
                        <div class="flex items-center justify-between">
                            <h3 class="text-lg font-semibold text-gray-800">User Investments</h3>
                            <div class="flex items-center space-x-4">
                                <select id="statusFilter" onchange="filterInvestments(this.value)" class="px-3 py-2 border border-gray-300 rounded-lg">
                                    <option value="">All Status</option>
                                    <option value="active">Active</option>
                                    <option value="pending">Pending</option>
                                    <option value="completed">Completed</option>
                                    <option value="cancelled">Cancelled</option>
                                </select>
                                <select id="planFilter" onchange="filterByPlan(this.value)" class="px-3 py-2 border border-gray-300 rounded-lg">
                                    <option value="">All Plans</option>
                                    <?php foreach ($plans as $plan): ?>
                                    <option value="<?php echo $plan['id']; ?>"><?php echo htmlspecialchars($plan['name']); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                    </div>
                    
                    <div class="overflow-x-auto">
                        <table class="w-full">
                            <thead>
                                <tr class="bg-gray-50 text-left text-sm text-gray-500">
                                    <th class="py-3 px-6 font-medium">User</th>
                                    <th class="py-3 px-6 font-medium">Plan</th>
                                    <th class="py-3 px-6 font-medium">Amount</th>
                                    <th class="py-3 px-6 font-medium">Expected Return</th>
                                    <th class="py-3 px-6 font-medium">Start Date</th>
                                    <th class="py-3 px-6 font-medium">End Date</th>
                                    <th class="py-3 px-6 font-medium">Status</th>
                                    <th class="py-3 px-6 font-medium">Actions</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-gray-200">
                                <?php if (empty($userInvestments)): ?>
                                <tr>
                                    <td colspan="8" class="py-8 text-center text-gray-500">
                                        <i class="fas fa-users text-3xl mb-2 block"></i>
                                        No user investments found
                                    </td>
                                </tr>
                                <?php else: ?>
                                <?php foreach ($userInvestments as $investment): ?>
                                <tr class="hover:bg-gray-50 transition investment-row" 
                                    data-status="<?php echo $investment['status']; ?>"
                                    data-plan="<?php echo $investment['plan_id']; ?>">
                                    <td class="py-4 px-6">
                                        <div class="flex items-center">
                                            <div class="w-8 h-8 bg-primary-100 rounded-full flex items-center justify-center mr-3">
                                                <span class="text-primary-800 font-medium text-sm">
                                                    <?php echo isset($investment['full_name']) && !empty($investment['full_name']) ? strtoupper(substr($investment['full_name'], 0, 1)) : 'U'; ?>
                                                </span>
                                            </div>
                                            <div>
                                                <p class="font-medium text-gray-800">
                                                    <?php 
                                                    $name = !empty($investment['full_name']) ? htmlspecialchars($investment['full_name']) : htmlspecialchars($investment['username']);
                                                    echo $name;
                                                    ?>
                                                </p>
                                                <p class="text-sm text-gray-500"><?php echo htmlspecialchars($investment['email']); ?></p>
                                            </div>
                                        </div>
                                    </td>
                                    <td class="py-4 px-6">
                                        <p class="font-medium text-gray-800"><?php echo htmlspecialchars($investment['plan_name']); ?></p>
                                        <p class="text-sm text-gray-500"><?php echo $investment['interest_rate']; ?>% for <?php echo $investment['duration_days']; ?> days</p>
                                    </td>
                                    <td class="py-4 px-6">
                                        <p class="font-medium text-gray-800">$<?php echo number_format($investment['amount'], 2); ?></p>
                                    </td>
                                    <td class="py-4 px-6">
                                        <p class="font-medium text-gray-800">$<?php echo number_format($investment['expected_return'], 2); ?></p>
                                        <?php if ($investment['actual_return'] > 0): ?>
                                        <p class="text-sm text-green-600">Actual: $<?php echo number_format($investment['actual_return'], 2); ?></p>
                                        <?php endif; ?>
                                    </td>
                                    <td class="py-4 px-6">
                                        <p class="text-gray-600"><?php echo date('M d, Y', strtotime($investment['start_date'])); ?></p>
                                    </td>
                                    <td class="py-4 px-6">
                                        <p class="text-gray-600"><?php echo date('M d, Y', strtotime($investment['end_date'])); ?></p>
                                    </td>
                                    <td class="py-4 px-6">
                                        <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium status-<?php echo $investment['status']; ?>">
                                            <?php echo ucfirst($investment['status']); ?>
                                        </span>
                                    </td>
                                    <td class="py-4 px-6">
                                        <div class="flex space-x-2">
                                            <button onclick="showInvestmentDetails(<?php echo $investment['id']; ?>)" 
                                                    class="text-blue-600 hover:text-blue-800" title="View Details">
                                                <i class="fas fa-eye"></i>
                                            </button>
                                            <button onclick="showEditInvestment(<?php echo $investment['id']; ?>)" 
                                                    class="text-green-600 hover:text-green-800" title="Edit">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                            <button onclick="confirmDeleteInvestment(<?php echo $investment['id']; ?>)" 
                                                    class="text-red-600 hover:text-red-800" title="Delete">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- Add/Edit Plan Form Modal -->
            <div id="plan-form-modal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50 <?php echo ($plan_id > 0 && $action == 'edit') ? '' : 'hidden'; ?>">
                <div class="relative top-20 mx-auto p-5 border w-full max-w-2xl shadow-lg rounded-lg bg-white">
                    <div class="flex justify-between items-center pb-3">
                        <h3 class="text-xl font-semibold text-gray-800">
                            <?php echo $editPlan ? 'Edit Investment Plan' : 'Add New Investment Plan'; ?>
                        </h3>
                        <button onclick="closePlanForm()" class="text-gray-400 hover:text-gray-600">
                            <i class="fas fa-times text-xl"></i>
                        </button>
                    </div>
                    
                    <form method="POST">
                        <input type="hidden" name="plan_id" value="<?php echo $editPlan['id'] ?? 0; ?>">
                        
                        <div class="space-y-4">
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">
                                        Plan Name *
                                    </label>
                                    <input type="text" name="name" value="<?php echo htmlspecialchars($editPlan['name'] ?? ''); ?>" 
                                           class="w-full px-3 py-2 border border-gray-300 rounded-lg" required>
                                </div>
                                
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">
                                        Interest Rate (%) *
                                    </label>
                                    <input type="number" name="interest_rate" step="0.01" min="0" 
                                           value="<?php echo $editPlan['interest_rate'] ?? ''; ?>" 
                                           class="w-full px-3 py-2 border border-gray-300 rounded-lg" required>
                                </div>
                                
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">
                                        Minimum Amount ($) *
                                    </label>
                                    <input type="number" name="min_amount" step="0.01" min="0" 
                                           value="<?php echo $editPlan['min_amount'] ?? ''; ?>" 
                                           class="w-full px-3 py-2 border border-gray-300 rounded-lg" required>
                                </div>
                                
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">
                                        Maximum Amount ($)
                                    </label>
                                    <input type="number" name="max_amount" step="0.01" min="0" 
                                           value="<?php echo $editPlan['max_amount'] ?? ''; ?>" 
                                           class="w-full px-3 py-2 border border-gray-300 rounded-lg">
                                </div>
                                
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">
                                        Duration (Days) *
                                    </label>
                                    <input type="number" name="duration_days" min="1" 
                                           value="<?php echo $editPlan['duration_days'] ?? '30'; ?>" 
                                           class="w-full px-3 py-2 border border-gray-300 rounded-lg" required>
                                </div>
                                
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">
                                        Compounding Interval
                                    </label>
                                    <select name="compounding_interval" class="w-full px-3 py-2 border border-gray-300 rounded-lg">
                                        <option value="daily" <?php echo ($editPlan['compounding_interval'] ?? 'monthly') == 'daily' ? 'selected' : ''; ?>>Daily</option>
                                        <option value="weekly" <?php echo ($editPlan['compounding_interval'] ?? 'monthly') == 'weekly' ? 'selected' : ''; ?>>Weekly</option>
                                        <option value="monthly" <?php echo ($editPlan['compounding_interval'] ?? 'monthly') == 'monthly' ? 'selected' : ''; ?>>Monthly</option>
                                        <option value="quarterly" <?php echo ($editPlan['compounding_interval'] ?? 'monthly') == 'quarterly' ? 'selected' : ''; ?>>Quarterly</option>
                                        <option value="annually" <?php echo ($editPlan['compounding_interval'] ?? 'monthly') == 'annually' ? 'selected' : ''; ?>>Annually</option>
                                    </select>
                                </div>
                                
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">
                                        Status
                                    </label>
                                    <select name="status" class="w-full px-3 py-2 border border-gray-300 rounded-lg">
                                        <option value="active" <?php echo ($editPlan['status'] ?? 'active') == 'active' ? 'selected' : ''; ?>>Active</option>
                                        <option value="inactive" <?php echo ($editPlan['status'] ?? 'active') == 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                                    </select>
                                </div>
                            </div>
                            
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">
                                    Description *
                                </label>
                                <textarea name="description" rows="3" 
                                          class="w-full px-3 py-2 border border-gray-300 rounded-lg" required><?php echo htmlspecialchars($editPlan['description'] ?? ''); ?></textarea>
                            </div>
                            
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">
                                    Features (Select all that apply)
                                </label>
                                <div class="grid grid-cols-2 md:grid-cols-3 gap-2">
                                    <?php 
                                    $selectedFeatures = isset($editPlan['features']) ? explode('|', $editPlan['features']) : [];
                                    $allFeatures = [
                                        'Daily Payouts',
                                        'Compounding Interest',
                                        'Principal Protection',
                                        'Early Withdrawal',
                                        'Reinvestment Option',
                                        'Referral Bonus',
                                        '24/7 Support',
                                        'Insurance Coverage',
                                        'Flexible Terms'
                                    ];
                                    foreach ($allFeatures as $feature): 
                                    ?>
                                    <label class="flex items-center">
                                        <input type="checkbox" name="features[]" value="<?php echo $feature; ?>" 
                                               class="h-4 w-4 text-primary-600 rounded border-gray-300"
                                               <?php echo in_array($feature, $selectedFeatures) ? 'checked' : ''; ?>>
                                        <span class="ml-2 text-sm text-gray-700"><?php echo $feature; ?></span>
                                    </label>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        </div>
                        
                        <div class="flex justify-end space-x-3 mt-6">
                            <button type="button" onclick="closePlanForm()" 
                                    class="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition">
                                Cancel
                            </button>
                            <button type="submit" name="save_plan" 
                                    class="px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition">
                                Save Plan
                            </button>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Investment Details Modal -->
            <div id="investment-details-modal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50 hidden">
                <div class="relative top-10 mx-auto p-5 border w-full max-w-4xl shadow-lg rounded-lg bg-white">
                    <div class="flex justify-between items-center pb-3 border-b">
                        <h3 class="text-xl font-semibold text-gray-800">Investment Details</h3>
                        <button onclick="closeInvestmentDetails()" class="text-gray-400 hover:text-gray-600">
                            <i class="fas fa-times text-xl"></i>
                        </button>
                    </div>
                    
                    <div id="investment-details-content" class="py-4">
                        <!-- Content will be loaded via JavaScript -->
                    </div>
                    
                    <div class="flex justify-end space-x-3 pt-4 border-t">
                        <button onclick="closeInvestmentDetails()" 
                                class="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition">
                            Close
                        </button>
                        <button id="edit-investment-btn" onclick="editCurrentInvestment()" 
                                class="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition">
                            <i class="fas fa-edit mr-2"></i>
                            Edit Investment
                        </button>
                    </div>
                </div>
            </div>

            <!-- Edit Investment Modal -->
            <div id="edit-investment-modal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50 <?php echo ($investment_id > 0 && $action == 'edit-investment') ? '' : 'hidden'; ?>">
                <div class="relative top-10 mx-auto p-5 border w-full max-w-2xl shadow-lg rounded-lg bg-white">
                    <div class="flex justify-between items-center pb-3">
                        <h3 class="text-xl font-semibold text-gray-800">Edit Investment</h3>
                        <button onclick="closeEditInvestment()" class="text-gray-400 hover:text-gray-600">
                            <i class="fas fa-times text-xl"></i>
                        </button>
                    </div>
                    
                    <form method="POST" id="edit-investment-form">
                        <input type="hidden" name="investment_id" id="edit-investment-id" value="<?php echo $editInvestment['id'] ?? 0; ?>">
                        
                        <div class="space-y-4">
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">
                                        User
                                    </label>
                                    <div class="p-2 bg-gray-50 rounded border">
                                        <p id="edit-user-name" class="font-medium text-gray-800"></p>
                                        <p id="edit-user-email" class="text-sm text-gray-500"></p>
                                    </div>
                                </div>
                                
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">
                                        Investment Plan
                                    </label>
                                    <div class="p-2 bg-gray-50 rounded border">
                                        <p id="edit-plan-name" class="font-medium text-gray-800"></p>
                                        <p id="edit-plan-details" class="text-sm text-gray-500"></p>
                                    </div>
                                </div>
                                
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">
                                        Investment Amount ($) *
                                    </label>
                                    <input type="number" name="amount" id="edit-amount" step="0.01" min="0" 
                                           class="w-full px-3 py-2 border border-gray-300 rounded-lg" required>
                                    <p class="text-xs text-gray-500 mt-1" id="edit-amount-hint"></p>
                                </div>
                                
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">
                                        Status *
                                    </label>
                                    <select name="status" id="edit-status" class="w-full px-3 py-2 border border-gray-300 rounded-lg" required>
                                        <option value="pending">Pending</option>
                                        <option value="active">Active</option>
                                        <option value="completed">Completed</option>
                                        <option value="cancelled">Cancelled</option>
                                        <option value="failed">Failed</option>
                                    </select>
                                </div>
                            </div>
                            
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">
                                    Expected Return
                                </label>
                                <div class="p-2 bg-gray-50 rounded border">
                                    <p id="edit-expected-return" class="font-medium text-gray-800"></p>
                                </div>
                            </div>
                            
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">
                                    Admin Notes
                                </label>
                                <textarea name="admin_notes" id="edit-admin-notes" rows="3" 
                                          class="w-full px-3 py-2 border border-gray-300 rounded-lg" 
                                          placeholder="Add any notes about this investment..."></textarea>
                            </div>
                            
                            <div class="p-4 bg-yellow-50 border border-yellow-200 rounded-lg">
                                <div class="flex">
                                    <i class="fas fa-exclamation-triangle text-yellow-500 mt-1 mr-3"></i>
                                    <div>
                                        <h4 class="text-sm font-medium text-yellow-800">Important Note</h4>
                                        <p class="text-sm text-yellow-700 mt-1">
                                            Changing the investment amount will recalculate the expected return based on the plan's interest rate and duration.
                                        </p>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="flex justify-between mt-6">
                            <div>
                                <button type="button" onclick="deleteCurrentInvestment()" 
                                        class="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition">
                                    <i class="fas fa-trash mr-2"></i>
                                    Delete Investment
                                </button>
                            </div>
                            <div class="flex space-x-3">
                                <button type="button" onclick="closeEditInvestment()" 
                                        class="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition">
                                    Cancel
                                </button>
                                <button type="submit" name="update_user_investment" 
                                        class="px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition">
                                    <i class="fas fa-save mr-2"></i>
                                    Update Investment
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Add Manual Investment Form -->
            <div id="add-investment-tab" class="tab-content hidden">
                <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
                    <h3 class="text-lg font-semibold text-gray-800 mb-6">Add Manual Investment</h3>
                    
                    <form method="POST">
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">
                                    Select User *
                                </label>
                                <select name="user_id" class="w-full px-4 py-2 border border-gray-300 rounded-lg" required>
                                    <option value="">Choose a user...</option>
                                    <?php foreach ($users as $user): ?>
                                    <option value="<?php echo $user['id']; ?>">
                                        <?php echo htmlspecialchars($user['username'] . ' - ' . $user['email']); ?>
                                        <?php if (!empty($user['full_name'])): ?>
                                        (<?php echo htmlspecialchars($user['full_name']); ?>)
                                        <?php endif; ?>
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">
                                    Investment Plan *
                                </label>
                                <select name="plan_id" class="w-full px-4 py-2 border border-gray-300 rounded-lg" required 
                                        onchange="updatePlanDetails(this.value)">
                                    <option value="">Choose a plan...</option>
                                    <?php foreach ($plans as $plan): ?>
                                    <?php if ($plan['status'] == 'active'): ?>
                                    <option value="<?php echo $plan['id']; ?>" 
                                            data-interest="<?php echo $plan['interest_rate']; ?>"
                                            data-min="<?php echo $plan['min_amount']; ?>"
                                            data-max="<?php echo $plan['max_amount']; ?>"
                                            data-duration="<?php echo $plan['duration_days']; ?>">
                                        <?php echo htmlspecialchars($plan['name'] . ' (' . $plan['interest_rate'] . '% for ' . $plan['duration_days'] . ' days)'); ?>
                                    </option>
                                    <?php endif; ?>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">
                                    Investment Amount ($) *
                                </label>
                                <input type="number" name="amount" step="0.01" min="0" 
                                       class="w-full px-4 py-2 border border-gray-300 rounded-lg" required>
                                <p class="text-xs text-gray-500 mt-1" id="amount-hint"></p>
                            </div>
                            
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">
                                    Status *
                                </label>
                                <select name="status" class="w-full px-4 py-2 border border-gray-300 rounded-lg" required>
                                    <option value="pending">Pending</option>
                                    <option value="active">Active</option>
                                    <option value="completed">Completed</option>
                                </select>
                            </div>
                        </div>
                        
                        <div class="mt-6 p-4 bg-gray-50 rounded-lg">
                            <h4 class="text-sm font-medium text-gray-700 mb-2">Plan Details</h4>
                            <div id="plan-details" class="text-sm text-gray-600">
                                Select a plan to see details
                            </div>
                        </div>
                        
                        <div class="mt-8 flex justify-end">
                            <button type="submit" name="add_user_investment" 
                                    class="px-6 py-2 bg-green-600 text-white font-medium rounded-lg hover:bg-green-700 transition">
                                <i class="fas fa-plus-circle mr-2"></i>
                                Add Investment
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </main>
    </div>

    <!-- JavaScript -->
    <script>
        // Tab switching
        function showTab(tabName) {
            // Hide all tabs
            document.querySelectorAll('.tab-content').forEach(tab => {
                tab.classList.add('hidden');
            });
            
            // Update tab buttons
            document.querySelectorAll('#tab-plans-btn, #tab-investments-btn, #tab-add-investment-btn').forEach(btn => {
                btn.classList.remove('tab-active', 'bg-primary-600', 'bg-gray-200', 'bg-green-600');
                btn.classList.add('bg-gray-200', 'text-gray-700');
            });
            
            // Show selected tab
            document.getElementById(tabName + '-tab').classList.remove('hidden');
            
            // Update active tab button
            const activeBtn = document.getElementById('tab-' + tabName.replace('-tab', '') + '-btn');
            if (tabName === 'plans') {
                activeBtn.classList.remove('bg-gray-200', 'text-gray-700');
                activeBtn.classList.add('bg-primary-600', 'text-white', 'tab-active');
            } else if (tabName === 'investments') {
                activeBtn.classList.remove('bg-gray-200', 'text-gray-700');
                activeBtn.classList.add('bg-primary-600', 'text-white', 'tab-active');
            } else if (tabName === 'add-investment') {
                activeBtn.classList.remove('bg-gray-200', 'text-gray-700');
                activeBtn.classList.add('bg-green-600', 'text-white', 'tab-active');
            }
            
            // Close modals if open
            closePlanForm();
            closeInvestmentDetails();
            closeEditInvestment();
        }
        
        // Plan form modal functions
        function showPlanForm() {
            document.getElementById('plan-form-modal').classList.remove('hidden');
        }
        
        function closePlanForm() {
            document.getElementById('plan-form-modal').classList.add('hidden');
        }
        
        // Investment Details Modal
        function showInvestmentDetails(investmentId) {
            // Fetch investment details via AJAX
            fetch(`get_investment_details.php?id=${investmentId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const investment = data.data;
                        const content = document.getElementById('investment-details-content');
                        
                        // Format dates
                        const startDate = new Date(investment.start_date).toLocaleDateString('en-US', {
                            year: 'numeric',
                            month: 'long',
                            day: 'numeric'
                        });
                        const endDate = new Date(investment.end_date).toLocaleDateString('en-US', {
                            year: 'numeric',
                            month: 'long',
                            day: 'numeric'
                        });
                        const createdAt = new Date(investment.created_at).toLocaleDateString('en-US', {
                            year: 'numeric',
                            month: 'long',
                            day: 'numeric',
                            hour: '2-digit',
                            minute: '2-digit'
                        });
                        
                        // Calculate days remaining
                        const today = new Date();
                        const end = new Date(investment.end_date);
                        const daysRemaining = Math.ceil((end - today) / (1000 * 60 * 60 * 24));
                        
                        content.innerHTML = `
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                                <div>
                                    <h4 class="text-sm font-medium text-gray-500 mb-2">User Information</h4>
                                    <div class="bg-gray-50 p-4 rounded-lg">
                                        <p class="font-medium text-gray-800">${investment.full_name || investment.username}</p>
                                        <p class="text-sm text-gray-600">${investment.email}</p>
                                        ${investment.phone ? `<p class="text-sm text-gray-600">Phone: ${investment.phone}</p>` : ''}
                                        ${investment.country ? `<p class="text-sm text-gray-600">Country: ${investment.country}</p>` : ''}
                                        <p class="text-sm text-gray-600 mt-2">Account Status: 
                                            <span class="font-medium ${investment.account_status === 'active' ? 'text-green-600' : 'text-red-600'}">
                                                ${investment.account_status}
                                            </span>
                                        </p>
                                    </div>
                                </div>
                                
                                <div>
                                    <h4 class="text-sm font-medium text-gray-500 mb-2">Investment Plan</h4>
                                    <div class="bg-gray-50 p-4 rounded-lg">
                                        <p class="font-medium text-gray-800">${investment.plan_name}</p>
                                        <p class="text-sm text-gray-600">${investment.plan_description || 'No description available'}</p>
                                        <div class="mt-2 grid grid-cols-2 gap-2">
                                            <span class="text-sm bg-blue-100 text-blue-800 px-2 py-1 rounded">${investment.interest_rate}% Interest</span>
                                            <span class="text-sm bg-green-100 text-green-800 px-2 py-1 rounded">${investment.duration_days} Days</span>
                                            <span class="text-sm bg-purple-100 text-purple-800 px-2 py-1 rounded">${investment.compounding_interval} Compounding</span>
                                        </div>
                                    </div>
                                </div>
                                
                                <div>
                                    <h4 class="text-sm font-medium text-gray-500 mb-2">Investment Details</h4>
                                    <div class="bg-gray-50 p-4 rounded-lg">
                                        <div class="grid grid-cols-2 gap-4">
                                            <div>
                                                <p class="text-sm text-gray-500">Amount Invested</p>
                                                <p class="text-lg font-bold text-gray-800">$${parseFloat(investment.amount).toFixed(2)}</p>
                                            </div>
                                            <div>
                                                <p class="text-sm text-gray-500">Expected Return</p>
                                                <p class="text-lg font-bold text-green-600">$${parseFloat(investment.expected_return).toFixed(2)}</p>
                                            </div>
                                            <div>
                                                <p class="text-sm text-gray-500">Actual Return</p>
                                                <p class="text-lg font-bold ${investment.actual_return > 0 ? 'text-green-600' : 'text-gray-600'}">
                                                    $${parseFloat(investment.actual_return || 0).toFixed(2)}
                                                </p>
                                            </div>
                                            <div>
                                                <p class="text-sm text-gray-500">Profit</p>
                                                <p class="text-lg font-bold text-green-600">
                                                    $${(parseFloat(investment.expected_return) - parseFloat(investment.amount)).toFixed(2)}
                                                </p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                
                                <div>
                                    <h4 class="text-sm font-medium text-gray-500 mb-2">Status & Timeline</h4>
                                    <div class="bg-gray-50 p-4 rounded-lg">
                                        <div class="mb-4">
                                            <p class="text-sm text-gray-500">Status</p>
                                            <span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium status-${investment.status}">
                                                ${investment.status.charAt(0).toUpperCase() + investment.status.slice(1)}
                                            </span>
                                        </div>
                                        <div class="space-y-2">
                                            <p class="text-sm text-gray-600">
                                                <span class="font-medium">Start Date:</span> ${startDate}
                                            </p>
                                            <p class="text-sm text-gray-600">
                                                <span class="font-medium">End Date:</span> ${endDate}
                                            </p>
                                            <p class="text-sm ${daysRemaining > 0 ? 'text-green-600' : 'text-red-600'}">
                                                <span class="font-medium">Days Remaining:</span> ${daysRemaining > 0 ? daysRemaining : 'Completed'}
                                            </p>
                                            <p class="text-sm text-gray-600">
                                                <span class="font-medium">Created:</span> ${createdAt}
                                            </p>
                                        </div>
                                    </div>
                                </div>
                                
                                ${investment.transaction_id ? `
                                <div>
                                    <h4 class="text-sm font-medium text-gray-500 mb-2">Transaction Details</h4>
                                    <div class="bg-gray-50 p-4 rounded-lg">
                                        <p class="text-sm text-gray-600">
                                            <span class="font-medium">Transaction ID:</span> ${investment.transaction_id}
                                        </p>
                                        ${investment.payment_method ? `
                                        <p class="text-sm text-gray-600">
                                            <span class="font-medium">Payment Method:</span> ${investment.payment_method}
                                        </p>
                                        ` : ''}
                                    </div>
                                </div>
                                ` : ''}
                                
                                ${investment.admin_notes ? `
                                <div>
                                    <h4 class="text-sm font-medium text-gray-500 mb-2">Admin Notes</h4>
                                    <div class="bg-gray-50 p-4 rounded-lg">
                                        <p class="text-sm text-gray-600">${investment.admin_notes}</p>
                                    </div>
                                </div>
                                ` : ''}
                            </div>
                        `;
                        
                        // Store the investment ID for the edit button
                        document.getElementById('edit-investment-btn').dataset.investmentId = investmentId;
                        
                        // Show the modal
                        document.getElementById('investment-details-modal').classList.remove('hidden');
                    } else {
                        alert('Error loading investment details: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('Error loading investment details');
                });
        }
        
        function closeInvestmentDetails() {
            document.getElementById('investment-details-modal').classList.add('hidden');
        }
        
        function editCurrentInvestment() {
            const investmentId = document.getElementById('edit-investment-btn').dataset.investmentId;
            if (investmentId) {
                showEditInvestment(investmentId);
                closeInvestmentDetails();
            }
        }
        
        // Edit Investment Modal
        function showEditInvestment(investmentId) {
            // Fetch investment data via AJAX
            fetch(`get_investment_details.php?id=${investmentId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const investment = data.data;
                        
                        // Populate the form
                        document.getElementById('edit-investment-id').value = investment.id;
                        document.getElementById('edit-user-name').textContent = investment.full_name || investment.username;
                        document.getElementById('edit-user-email').textContent = investment.email;
                        document.getElementById('edit-plan-name').textContent = investment.plan_name;
                        document.getElementById('edit-plan-details').textContent = 
                            `${investment.interest_rate}% for ${investment.duration_days} days`;
                        document.getElementById('edit-amount').value = investment.amount;
                        document.getElementById('edit-status').value = investment.status;
                        document.getElementById('edit-expected-return').textContent = 
                            `$${parseFloat(investment.expected_return).toFixed(2)}`;
                        document.getElementById('edit-admin-notes').value = investment.admin_notes || '';
                        
                        // Update amount hint
                        const amountHint = document.getElementById('edit-amount-hint');
                        amountHint.textContent = `Plan allows: $${investment.min_amount} - $${investment.max_amount || 'Unlimited'}`;
                        
                        // Show the modal
                        document.getElementById('edit-investment-modal').classList.remove('hidden');
                    } else {
                        alert('Error loading investment data: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('Error loading investment data');
                });
        }
        
        function closeEditInvestment() {
            document.getElementById('edit-investment-modal').classList.add('hidden');
        }
        
        // Delete Investment Confirmation
        function confirmDeleteInvestment(investmentId) {
            if (confirm('Are you sure you want to delete this investment record? This action cannot be undone.')) {
                const form = document.createElement('form');
                form.method = 'POST';
                form.action = '';
                
                const input1 = document.createElement('input');
                input1.type = 'hidden';
                input1.name = 'investment_id';
                input1.value = investmentId;
                form.appendChild(input1);
                
                const input2 = document.createElement('input');
                input2.type = 'hidden';
                input2.name = 'delete_user_investment';
                input2.value = '1';
                form.appendChild(input2);
                
                document.body.appendChild(form);
                form.submit();
            }
        }
        
        function deleteCurrentInvestment() {
            const investmentId = document.getElementById('edit-investment-id').value;
            if (confirm('Are you sure you want to delete this investment record? This action cannot be undone.')) {
                const form = document.createElement('form');
                form.method = 'POST';
                form.action = '';
                
                const input1 = document.createElement('input');
                input1.type = 'hidden';
                input1.name = 'investment_id';
                input1.value = investmentId;
                form.appendChild(input1);
                
                const input2 = document.createElement('input');
                input2.type = 'hidden';
                input2.name = 'delete_user_investment';
                input2.value = '1';
                form.appendChild(input2);
                
                document.body.appendChild(form);
                form.submit();
            }
        }
        
        // Filter investments by status
        function filterInvestments(status) {
            const rows = document.querySelectorAll('.investment-row');
            rows.forEach(row => {
                if (!status || row.getAttribute('data-status') === status) {
                    row.style.display = '';
                } else {
                    row.style.display = 'none';
                }
            });
        }
        
        // Filter investments by plan
        function filterByPlan(planId) {
            const rows = document.querySelectorAll('.investment-row');
            rows.forEach(row => {
                if (!planId || row.getAttribute('data-plan') == planId) {
                    row.style.display = '';
                } else {
                    row.style.display = 'none';
                }
            });
        }
        
        // Update plan details in manual investment form
        function updatePlanDetails(planId) {
            const select = document.querySelector('select[name="plan_id"]');
            const selectedOption = select.options[select.selectedIndex];
            const detailsDiv = document.getElementById('plan-details');
            const amountInput = document.querySelector('input[name="amount"]');
            const amountHint = document.getElementById('amount-hint');
            
            if (selectedOption && selectedOption.value) {
                const interestRate = selectedOption.getAttribute('data-interest');
                const minAmount = selectedOption.getAttribute('data-min');
                const maxAmount = selectedOption.getAttribute('data-max');
                const duration = selectedOption.getAttribute('data-duration');
                
                detailsDiv.innerHTML = `
                    <p><strong>Interest Rate:</strong> ${interestRate}% per annum</p>
                    <p><strong>Duration:</strong> ${duration} days</p>
                    <p><strong>Minimum Investment:</strong> $${minAmount}</p>
                    <p><strong>Maximum Investment:</strong> $${maxAmount || 'No limit'}</p>
                `;
                
                amountHint.textContent = `Enter amount between $${minAmount} and $${maxAmount || 'any amount'}`;
                amountInput.min = minAmount;
                if (maxAmount) {
                    amountInput.max = maxAmount;
                }
            } else {
                detailsDiv.innerHTML = 'Select a plan to see details';
                amountHint.textContent = '';
            }
        }
        
        // Auto-open modals based on URL parameters
        <?php if ($plan_id > 0 && $action == 'edit'): ?>
        document.addEventListener('DOMContentLoaded', function() {
            showPlanForm();
            showTab('plans');
        });
        <?php endif; ?>
        
        <?php if ($investment_id > 0 && $action == 'view'): ?>
        document.addEventListener('DOMContentLoaded', function() {
            showInvestmentDetails(<?php echo $investment_id; ?>);
            showTab('investments');
        });
        <?php endif; ?>
        
        <?php if ($investment_id > 0 && $action == 'edit-investment'): ?>
        document.addEventListener('DOMContentLoaded', function() {
            showEditInvestment(<?php echo $investment_id; ?>);
            showTab('investments');
        });
        <?php endif; ?>
    </script>
</body>
</html>