<?php
session_start();
require_once 'php/adminconfig.php';
// Enhanced login and role check
if (!isset($_SESSION['admin_id']) || $_SESSION['user_role'] !== 'admin') {
    header('Location: signin-admin.php');
    exit();
}
// Simple logout
if (isset($_GET['action']) && $_GET['action'] === 'logout') {
    session_destroy();
    header('Location: signin-admin.php');
    exit();
}

// Fetch all investments with trading plan details
$query = "SELECT i.*, tp.package_title, u.username 
          FROM investments i
          JOIN trading_plan tp ON i.plan_id = tp.id
          JOIN users u ON i.user_id = u.id
          ORDER BY i.created_at DESC";
$stmt = $conn->prepare($query);
$stmt->execute();
$investments = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Fetch trading plans for dropdown in forms
$plans_query = "SELECT * FROM trading_plan ORDER BY id";
$plans_stmt = $conn->prepare($plans_query);
$plans_stmt->execute();
$trading_plans = $plans_stmt->fetchAll(PDO::FETCH_ASSOC);

// Fetch users for dropdown in forms
$users_query = "SELECT id, username FROM users ORDER BY username";
$users_stmt = $conn->prepare($users_query);
$users_stmt->execute();
$users = $users_stmt->fetchAll(PDO::FETCH_ASSOC);

// Handle investment deletion
if (isset($_POST['delete_investment']) && isset($_POST['investment_id'])) {
    $investment_id = intval($_POST['investment_id']);
    
    try {
        $delete_query = "DELETE FROM investments WHERE id = :investment_id";
        $delete_stmt = $conn->prepare($delete_query);
        $delete_stmt->bindParam(':investment_id', $investment_id, PDO::PARAM_INT);
        $delete_stmt->execute();
        
        // Set success message
        $_SESSION['success_message'] = "Investment deleted successfully";
        header('Location: ' . $_SERVER['PHP_SELF']);
        exit();
    } catch (PDOException $e) {
        $_SESSION['error_message'] = "Error deleting investment: " . $e->getMessage();
    }
}

// Handle investment update
if (isset($_POST['update_investment']) && isset($_POST['investment_id'])) {
    $investment_id = intval($_POST['investment_id']);
    $user_id = intval($_POST['user_id']);
    $plan_id = intval($_POST['plan_id']);
    $amount = floatval($_POST['amount']);
    $purchase_date = $_POST['purchase_date'];
    $end_date = $_POST['end_date'];
    
    try {
        $update_query = "UPDATE investments 
                        SET user_id = :user_id, 
                            plan_id = :plan_id, 
                            amount = :amount, 
                            purchase_date = :purchase_date, 
                            end_date = :end_date 
                        WHERE id = :investment_id";
        $update_stmt = $conn->prepare($update_query);
        $update_stmt->bindParam(':investment_id', $investment_id, PDO::PARAM_INT);
        $update_stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT);
        $update_stmt->bindParam(':plan_id', $plan_id, PDO::PARAM_INT);
        $update_stmt->bindParam(':amount', $amount);
        $update_stmt->bindParam(':purchase_date', $purchase_date);
        $update_stmt->bindParam(':end_date', $end_date);
        $update_stmt->execute();
        
        // Set success message
        $_SESSION['success_message'] = "Investment updated successfully";
        header('Location: ' . $_SERVER['PHP_SELF']);
        exit();
    } catch (PDOException $e) {
        $_SESSION['error_message'] = "Error updating investment: " . $e->getMessage();
    }
}

// Handle new investment creation
if (isset($_POST['create_investment'])) {
    // Required fields validation
    if (empty($_POST['user_id']) || empty($_POST['plan_id']) || empty($_POST['amount']) || 
        empty($_POST['purchase_date']) || empty($_POST['end_date'])) {
        $_SESSION['error_message'] = "All fields are required.";
    } else {
        $user_id = intval($_POST['user_id']);
        $plan_id = intval($_POST['plan_id']);
        $amount = floatval($_POST['amount']);
        $purchase_date = $_POST['purchase_date'];
        $end_date = $_POST['end_date'];
        
        try {
            $insert_query = "INSERT INTO investments (user_id, plan_id, amount, purchase_date, end_date) 
                            VALUES (:user_id, :plan_id, :amount, :purchase_date, :end_date)";
            $insert_stmt = $conn->prepare($insert_query);
            $insert_stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT);
            $insert_stmt->bindParam(':plan_id', $plan_id, PDO::PARAM_INT);
            $insert_stmt->bindParam(':amount', $amount);
            $insert_stmt->bindParam(':purchase_date', $purchase_date);
            $insert_stmt->bindParam(':end_date', $end_date);
            $insert_stmt->execute();
            
            $_SESSION['success_message'] = "New investment created successfully";
            header('Location: ' . $_SERVER['PHP_SELF']);
            exit();
        } catch (PDOException $e) {
            $_SESSION['error_message'] = "Error creating investment: " . $e->getMessage();
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9, user-scalable=no" />
    <title>Investment Management - TradeWave plc</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --primary-color: rgba(123, 31, 162);
            --primary-light: #e8e4ff;
            --secondary-color: #00cec9;
            --accent-color: #ff7675;
            --success-color: #00b894;
            --warning-color: #fdcb6e;
            --danger-color: #d63031;
            --dark-color: #2d3436;
            --light-color: #f7f7f7;
            --border-radius: 8px;
            --box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            --transition: all 0.3s ease;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        body {
            color: var(--dark-color);
             background-image: radial-gradient(circle at 10px 10px, #999 1px, transparent 0);
            background-size: 20px 20px;
            line-height: 1.5rem;
            background-color: #f9f9f9;
            min-height: 100vh;
            overflow-x: hidden;
            zoom: 0.9;
        }

        .containeer {
            max-width: 1400px;
            margin: 0 auto;
            padding: 15px;
            background-color: ;
            border-radius: var(--border-radius);
        }

        .page-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 25px;
            padding-bottom: 15px;
            border-bottom: 1px solid #eee;
        }

        .page-title {
            font-size: 24px;
            color: var(--primary-color);
            font-weight: 600;
        }

        .btn {
            display: inline-block;
            padding: 8px 16px;
            border-radius: var(--border-radius);
            cursor: pointer;
            border: none;
            font-size: 14px;
            font-weight: 500;
            transition: var(--transition);
        }

        .btn-primary {
            background-color: var(--primary-color);
            color: white;
        }

        .btn-primary:hover {
            background-color: #5649c0;
        }

        .btn-success {
            background-color: var(--success-color);
            color: white;
        }

        .btn-success:hover {
            background-color: #00a382;
        }

        .btn-danger {
            background-color: var(--danger-color);
            color: white;
        }

        .btn-danger:hover {
            background-color: #b52b2c;
        }

        .alert {
            padding: 12px 20px;
            margin-bottom: 20px;
            border-radius: var(--border-radius);
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .alert-success {
            background-color: rgba(0, 184, 148, 0.2);
            color: var(--success-color);
            border-left: 4px solid var(--success-color);
        }

        .alert-danger {
            background-color: rgba(214, 48, 49, 0.2);
            color: var(--danger-color);
            border-left: 4px solid var(--danger-color);
        }

        .close-alert {
            cursor: pointer;
            font-size: 18px;
            font-weight: bold;
        }

        .investment-table-wrapper {
            overflow-x: auto;
            margin-bottom: 30px;
        }

        .investment-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
            white-space: nowrap;
        }

        .investment-table th,
        .investment-table td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #eee;
        }

        .investment-table th {
            background-color: var(--primary-light);
            color: var(--primary-color);
            font-weight: 600;
            position: sticky;
            top: 0;
        }

        .investment-table tbody tr {
            transition: var(--transition);
        }

        .investment-table tbody tr:hover {
            background-color: rgba(108, 92, 231, 0.05);
        }

        .action-buttons {
            display: flex;
            gap: 8px;
        }

        .edit-btn,
        .delete-btn {
            background: none;
            border: none;
            cursor: pointer;
            font-size: 16px;
            transition: var(--transition);
        }

        .edit-btn {
            color: var(--primary-color);
        }

        .edit-btn:hover {
            color: #5649c0;
        }

        .delete-btn {
            color: var(--danger-color);
        }

        .delete-btn:hover {
            color: #b52b2c;
        }

        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            align-items: center;
            justify-content: center;
        }

        .modal-content {
            background-color: white;
            width: 90%;
            max-width: 500px;
            padding: 25px;
            border-radius: var(--border-radius);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
            position: relative;
        }

        .warning-icon {
            display: flex;
            justify-content: center;
            margin-bottom: 15px;
            font-size: 48px;
            color: var(--warning-color);
        }

        .modal-title {
            text-align: center;
            margin-bottom: 15px;
            color: var(--dark-color);
        }

        .modal-text {
            text-align: center;
            margin-bottom: 20px;
        }

        .modal-actions {
            display: flex;
            justify-content: space-between;
            gap: 12px;
        }

        .form-group {
            margin-bottom: 16px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: 500;
            color: var(--dark-color);
        }

        .form-control {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: var(--border-radius);
            transition: var(--transition);
        }

        .form-control:focus {
            border-color: var(--primary-color);
            outline: none;
            box-shadow: 0 0 0 3px rgba(108, 92, 231, 0.2);
        }

        .badge {
            display: inline-block;
            padding: 3px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 600;
        }

        .badge-success {
            background-color: rgba(0, 184, 148, 0.2);
            color: var(--success-color);
        }

        .badge-warning {
            background-color: rgba(253, 203, 110, 0.2);
            color: #f39c12;
        }

        .badge-danger {
            background-color: rgba(214, 48, 49, 0.2);
            color: var(--danger-color);
        }

        .submit-row {
            display: flex;
            justify-content: flex-end;
            gap: 12px;
        }

        .amount-cell {
            font-weight: 600;
        }

        .search-filter {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
        }

        .search-box {
            flex: 1;
            position: relative;
        }

        .search-box input {
            width: 100%;
            padding: 10px 12px 10px 36px;
            border: 1px solid #ddd;
            border-radius: var(--border-radius);
        }

        .search-box i {
            position: absolute;
            left: 12px;
            top: 50%;
            transform: translateY(-50%);
            color: #aaa;
        }

        .filter-select {
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: var(--border-radius);
            min-width: 150px;
        }

        .table-stats {
            display: flex;
            gap: 20px;
            margin-bottom: 20px;
        }

        .stat-card {
            display: flex;
            flex-direction: column;
            border-radius: var(--border-radius);
            background-color: white;
            padding: 15px;
            flex: 1;
            box-shadow: var(--box-shadow);
        }

        .stat-title {
            font-size: 14px;
            color: #718096;
            margin-bottom: 5px;
        }

        .stat-value {
            font-size: 24px;
            font-weight: 600;
            color: var(--primary-color);
        }

        .trend {
            display: flex;
            align-items: center;
            gap: 5px;
            font-size: 12px;
        }

        .trend-up {
            color: var(--success-color);
        }

        .trend-down {
            color: var(--danger-color);
        }

        .modal-close {
            position: absolute;
            top: 15px;
            right: 15px;
            font-size: 20px;
            color: #aaa;
            cursor: pointer;
            transition: var(--transition);
        }

        .modal-close:hover {
            color: var(--danger-color);
        }

        /* Responsive styles */
        @media (max-width: 768px) {
            .table-stats {
                flex-direction: column;
                gap: 10px;
            }
            
            .page-header {
                flex-direction: column;
                align-items: flex-start;
                gap: 15px;
            }
            
            .modal-content {
                width: 95%;
                padding: 20px;
            }
            
            .modal-actions {
                flex-direction: column;
            }
            
            .form-group {
                margin-bottom: 12px;
            }
        }

        /* Status indicator based on dates */
        .status-indicator {
            width: 12px;
            height: 12px;
            border-radius: 50%;
            display: inline-block;
            margin-right: 5px;
        }

        .status-active {
            background-color: var(--success-color);
        }

        .status-completed {
            background-color: var(--dark-color);
        }

        .status-upcoming {
            background-color: var(--warning-color);
        }
    </style>
</head>
<body>

    <?php include "required/admin-nav.php" ?>

    <div class="pc">
    <div class="containeer">
        <div class="page-header">
            <h2 class="page-title">Investment Management</h2>
            <button class="btn btn-success" id="addInvestmentBtn">
                <i class="fas fa-plus"></i> Add New Investment
            </button>
        </div>
        
        <?php if (isset($_SESSION['success_message'])): ?>
            <div class="alert alert-success">
                <span><?php echo $_SESSION['success_message']; unset($_SESSION['success_message']); ?></span>
                <span class="close-alert">&times;</span>
            </div>
        <?php endif; ?>
        
        <?php if (isset($_SESSION['error_message'])): ?>
            <div class="alert alert-danger">
                <span><?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?></span>
                <span class="close-alert">&times;</span>
            </div>
        <?php endif; ?>
        
        <!-- Investment Stats -->
        <div class="table-stats">
            <div class="stat-card">
                <div class="stat-title">TOTAL INVESTMENTS</div>
                <div class="stat-value"><?php echo count($investments); ?></div>
                <div class="trend trend-up">
                    <i class="fas fa-arrow-up"></i> 12.5% from last month
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-title">TOTAL INVESTMENT AMOUNT</div>
                <div class="stat-value">$<?php 
                    $total = 0;
                    foreach($investments as $inv) {
                        $total += $inv['amount'];
                    }
                    echo number_format($total, 2);
                ?></div>
                <div class="trend trend-up">
                    <i class="fas fa-arrow-up"></i> 8.3% from last month
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-title">ACTIVE INVESTMENTS</div>
                <div class="stat-value"><?php 
                    $active = 0;
                    $now = new DateTime();
                    foreach($investments as $inv) {
                        $end_date = new DateTime($inv['end_date']);
                        if($end_date > $now) {
                            $active++;
                        }
                    }
                    echo $active;
                ?></div>
                <div class="trend trend-up">
                    <i class="fas fa-arrow-up"></i> 5.2% from last week
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-title">AVERAGE INVESTMENT</div>
                <div class="stat-value">$<?php 
                    echo count($investments) > 0 ? number_format($total / count($investments), 2) : '0.00';
                ?></div>
                <div class="trend trend-down">
                    <i class="fas fa-arrow-down"></i> 2.1% from last month
                </div>
            </div>
        </div>
        
        <!-- Search and filter -->
        <div class="search-filter">
            <div class="search-box">
                <i class="fas fa-search"></i>
                <input type="text" id="searchInput" placeholder="Search investments...">
            </div>
            <select class="filter-select" id="planFilter">
                <option value="">All Plans</option>
                <?php foreach ($trading_plans as $plan): ?>
                    <option value="<?php echo htmlspecialchars($plan['package_title']); ?>">
                        <?php echo htmlspecialchars($plan['package_title']); ?>
                    </option>
                <?php endforeach; ?>
            </select>
            <select class="filter-select" id="statusFilter">
                <option value="">All Status</option>
                <option value="active">Active</option>
                <option value="completed">Completed</option>
                <option value="upcoming">Upcoming</option>
            </select>
        </div>
        
        <!-- Investment Table -->
        <div class="investment-table-wrapper">
            <table class="investment-table" id="investmentTable">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>User</th>
                        <th>Plan</th>
                        <th>Amount</th>
                        <th>Purchase Date</th>
                        <th>End Date</th>
                        <th>Status</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    $now = new DateTime();
                    foreach ($investments as $investment): 
                        $purchase_date = new DateTime($investment['purchase_date']);
                        $end_date = new DateTime($investment['end_date']);
                        
                        // Determine status
                        $status = '';
                        $status_class = '';
                        
                        if ($purchase_date > $now) {
                            $status = 'Upcoming';
                            $status_class = 'status-upcoming';
                        } elseif ($end_date < $now) {
                            $status = 'Completed';
                            $status_class = 'status-completed';
                        } else {
                            $status = 'Active';
                            $status_class = 'status-active';
                        }
                    ?>
                    <tr data-id="<?php echo $investment['id']; ?>" data-plan="<?php echo htmlspecialchars($investment['package_title']); ?>" data-status="<?php echo strtolower($status); ?>">
                        <td>#<?php echo $investment['id']; ?></td>
                        <td><?php echo htmlspecialchars($investment['username']); ?></td>
                        <td><?php echo htmlspecialchars($investment['package_title']); ?></td>
                        <td class="amount-cell">$<?php echo number_format($investment['amount'], 2); ?></td>
                        <td><?php echo date('M d, Y', strtotime($investment['purchase_date'])); ?></td>
                        <td><?php echo date('M d, Y', strtotime($investment['end_date'])); ?></td>
                        <td>
                            <span class="status-indicator <?php echo $status_class; ?>"></span>
                            <?php echo $status; ?>
                        </td>
                        <td class="action-buttons">
                            <button class="edit-btn" data-id="<?php echo $investment['id']; ?>">
                                <i class="fas fa-edit"></i>
                            </button>
                            <button class="delete-btn" data-id="<?php echo $investment['id']; ?>">
                                <i class="fas fa-trash"></i>
                            </button>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        
        <!-- Delete Confirmation Modal -->
        <div class="modal" id="deleteModal">
            <div class="modal-content">
                <span class="modal-close" id="closeDeleteModal">&times;</span>
                <div class="warning-icon">
                    <i class="fas fa-exclamation-triangle"></i>
                </div>
                <h3 class="modal-title">Delete Investment</h3>
                <p class="modal-text">Are you sure you want to delete this investment? This action cannot be undone.</p>
                <div class="modal-actions">
                    <form id="deleteForm" action="" method="POST">
                        <input type="hidden" name="investment_id" id="deleteInvestmentId">
                        <button type="submit" name="delete_investment" class="btn btn-danger">Yes, Delete</button>
                    </form>
                    <button class="btn btn-primary" id="cancelDelete">Cancel</button>
                </div>
            </div>
        </div>
        
        <!-- Edit Investment Modal -->
        <div class="modal" id="editModal">
            <div class="modal-content">
                <span class="modal-close" id="closeEditModal">&times;</span>
                <h3 class="modal-title">Edit Investment</h3>
                <form id="editForm" action="" method="POST" class="edit-form">
                    <input type="hidden" name="investment_id" id="editInvestmentId">
                    
                    <div class="form-group">
                        <label for="edit-user">User</label>
                        <select name="user_id" id="edit-user" class="form-control" required>
                            <?php foreach ($users as $user): ?>
                                <option value="<?php echo $user['id']; ?>">
                                    <?php echo htmlspecialchars($user['username']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="edit-plan">Trading Plan</label>
                        <select name="plan_id" id="edit-plan" class="form-control" required>
                            <?php foreach ($trading_plans as $plan): ?>
                                <option value="<?php echo $plan['id']; ?>">
                                    <?php echo htmlspecialchars($plan['package_title']); ?> 
                                    ($<?php echo number_format($plan['minimum_price'], 2); ?> 
                                    <?php if (!$plan['is_unlimited']): ?>
                                        - $<?php echo number_format($plan['maximum_price'], 2); ?>
                                    <?php endif; ?>)
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="edit-amount">Amount</label>
                        <input type="number" step="0.01" name="amount" id="edit-amount" class="form-control" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="edit-purchase-date">Purchase Date</label>
                        <input type="datetime-local" name="purchase_date" id="edit-purchase-date" class="form-control" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="edit-end-date">End Date</label>
                        <input type="datetime-local" name="end_date" id="edit-end-date" class="form-control" required>
                    </div>
                    
                    <div class="form-group submit-row">
                        <button type="button" class="btn btn-danger" id="cancelEdit">Cancel</button>
                        <button type="submit" name="update_investment" class="btn btn-primary">Update Investment</button>
                    </div>
                </form>
            </div>
        </div>
        
        <!-- New Investment Modal -->
        <div class="modal" id="newInvestmentModal">
            <div class="modal-content">
                <span class="modal-close" id="closeNewModal">&times;</span>
                <h3 class="modal-title">Add New Investment</h3>
                <form action="" method="POST" class="edit-form">
                    <div class="form-group">
                        <label for="new-user">User</label>
                        <select name="user_id" id="new-user" class="form-control" required>
                            <option value="">Select User</option>
                            <?php foreach ($users as $user): ?>
                                <option value="<?php echo $user['id']; ?>">
                                    <?php echo htmlspecialchars($user['username']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="new-plan">Trading Plan</label>
                        <select name="plan_id" id="new-plan" class="form-control" required>
                            <option value="">Select Plan</option>
                            <?php foreach ($trading_plans as $plan): ?>
                                <option value="<?php echo $plan['id']; ?>">
                                    <?php echo htmlspecialchars($plan['package_title']); ?> 
                                    ($<?php echo number_format($plan['minimum_price'], 2); ?> 
                                    <?php if (!$plan['is_unlimited']): ?>
                                        - $<?php echo number_format($plan['maximum_price'], 2); ?>
                                    <?php endif; ?>)
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="new-amount">Amount</label>
                        <input type="number" step="0.01" name="amount" id="new-amount" class="form-control" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="new-purchase-date">Purchase Date</label>
                        <input type="datetime-local" name="purchase_date" id="new-purchase-date" class="form-control" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="new-end-date">End Date</label>
                        <!-- Completing the new-end-date input field -->
                        <input type="datetime-local" name="end_date" id="new-end-date" class="form-control" required>
                    </div>
                    
                    <div class="form-group submit-row">
                        <button type="button" class="btn btn-danger" id="cancelNewInvestment">Cancel</button>
                        <button type="submit" name="create_investment" class="btn btn-primary">Create Investment</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

    <!-- JavaScript for dynamic functionality -->
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Modal elements
            const deleteModal = document.getElementById('deleteModal');
            const editModal = document.getElementById('editModal');
            const newInvestmentModal = document.getElementById('newInvestmentModal');
            
            // Buttons and controls
            const addInvestmentBtn = document.getElementById('addInvestmentBtn');
            const searchInput = document.getElementById('searchInput');
            const planFilter = document.getElementById('planFilter');
            const statusFilter = document.getElementById('statusFilter');
            
            // Close alert messages
            document.querySelectorAll('.close-alert').forEach(function(closeBtn) {
                closeBtn.addEventListener('click', function() {
                    this.parentElement.style.display = 'none';
                });
            });
            
            // Search functionality
            searchInput.addEventListener('keyup', filterTable);
            planFilter.addEventListener('change', filterTable);
            statusFilter.addEventListener('change', filterTable);
            
            function filterTable() {
                const searchValue = searchInput.value.toLowerCase();
                const planValue = planFilter.value.toLowerCase();
                const statusValue = statusFilter.value.toLowerCase();
                
                const rows = document.querySelectorAll('#investmentTable tbody tr');
                
                rows.forEach(function(row) {
                    const rowData = row.textContent.toLowerCase();
                    const planData = row.getAttribute('data-plan').toLowerCase();
                    const statusData = row.getAttribute('data-status').toLowerCase();
                    
                    const matchesSearch = searchValue === '' || rowData.includes(searchValue);
                    const matchesPlan = planValue === '' || planData === planValue;
                    const matchesStatus = statusValue === '' || statusData === statusValue;
                    
                    if (matchesSearch && matchesPlan && matchesStatus) {
                        row.style.display = '';
                    } else {
                        row.style.display = 'none';
                    }
                });
            }
            
            // Delete Investment functionality
            document.querySelectorAll('.delete-btn').forEach(function(btn) {
                btn.addEventListener('click', function() {
                    const investmentId = this.getAttribute('data-id');
                    document.getElementById('deleteInvestmentId').value = investmentId;
                    deleteModal.style.display = 'flex';
                });
            });
            
            document.getElementById('closeDeleteModal').addEventListener('click', function() {
                deleteModal.style.display = 'none';
            });
            
            document.getElementById('cancelDelete').addEventListener('click', function() {
                deleteModal.style.display = 'none';
            });
            
            // Edit Investment functionality
            document.querySelectorAll('.edit-btn').forEach(function(btn) {
                btn.addEventListener('click', function() {
                    const investmentId = this.getAttribute('data-id');
                    const row = document.querySelector(`tr[data-id="${investmentId}"]`);
                    
                    if (row) {
                        // Get data from the row
                        const columns = row.querySelectorAll('td');
                        const userId = row.querySelector('td:nth-child(2)').textContent;
                        const planTitle = row.querySelector('td:nth-child(3)').textContent;
                        const amount = row.querySelector('td:nth-child(4)').textContent.replace('$', '').replace(',', '');
                        const purchaseDate = new Date(row.querySelector('td:nth-child(5)').textContent);
                        const endDate = new Date(row.querySelector('td:nth-child(6)').textContent);
                        
                        // Set form values
                        document.getElementById('editInvestmentId').value = investmentId;
                        
                        // Find user by username
                        const userSelect = document.getElementById('edit-user');
                        for (let i = 0; i < userSelect.options.length; i++) {
                            if (userSelect.options[i].text === userId) {
                                userSelect.selectedIndex = i;
                                break;
                            }
                        }
                        
                        // Find plan by title
                        const planSelect = document.getElementById('edit-plan');
                        for (let i = 0; i < planSelect.options.length; i++) {
                            if (planSelect.options[i].text.includes(planTitle)) {
                                planSelect.selectedIndex = i;
                                break;
                            }
                        }
                        
                        // Set other form values
                        document.getElementById('edit-amount').value = parseFloat(amount).toFixed(2);
                        
                        // Format dates for datetime-local input
                        const formatDateForInput = (date) => {
                            return date.getFullYear() + '-' + 
                                   String(date.getMonth() + 1).padStart(2, '0') + '-' + 
                                   String(date.getDate()).padStart(2, '0') + 'T' + 
                                   String(date.getHours()).padStart(2, '0') + ':' + 
                                   String(date.getMinutes()).padStart(2, '0');
                        };
                        
                        document.getElementById('edit-purchase-date').value = formatDateForInput(purchaseDate);
                        document.getElementById('edit-end-date').value = formatDateForInput(endDate);
                        
                        // Show modal
                        editModal.style.display = 'flex';
                    }
                });
            });
            
            document.getElementById('closeEditModal').addEventListener('click', function() {
                editModal.style.display = 'none';
            });
            
            document.getElementById('cancelEdit').addEventListener('click', function() {
                editModal.style.display = 'none';
            });
            
            // New Investment functionality
            addInvestmentBtn.addEventListener('click', function() {
                // Set default dates
                const now = new Date();
                const end = new Date();
                end.setMonth(end.getMonth() + 3); // Default to 3 months investment
                
                const formatDateForInput = (date) => {
                    return date.getFullYear() + '-' + 
                           String(date.getMonth() + 1).padStart(2, '0') + '-' + 
                           String(date.getDate()).padStart(2, '0') + 'T' + 
                           String(date.getHours()).padStart(2, '0') + ':' + 
                           String(date.getMinutes()).padStart(2, '0');
                };
                
                document.getElementById('new-purchase-date').value = formatDateForInput(now);
                document.getElementById('new-end-date').value = formatDateForInput(end);
                
                newInvestmentModal.style.display = 'flex';
            });
            
            document.getElementById('closeNewModal').addEventListener('click', function() {
                newInvestmentModal.style.display = 'none';
            });
            
            document.getElementById('cancelNewInvestment').addEventListener('click', function() {
                newInvestmentModal.style.display = 'none';
            });
            
            // Close modals when clicking outside of them
            window.addEventListener('click', function(event) {
                if (event.target === deleteModal) {
                    deleteModal.style.display = 'none';
                }
                if (event.target === editModal) {
                    editModal.style.display = 'none';
                }
                if (event.target === newInvestmentModal) {
                    newInvestmentModal.style.display = 'none';
                }
            });
            
            // Plan price validation
            document.getElementById('new-plan').addEventListener('change', validateAmount);
            document.getElementById('new-amount').addEventListener('input', validateAmount);
            
            function validateAmount() {
                const planSelect = document.getElementById('new-plan');
                const amountInput = document.getElementById('new-amount');
                
                if (planSelect.value && amountInput.value) {
                    const planOption = planSelect.options[planSelect.selectedIndex];
                    const planText = planOption.text;
                    
                    // Extract minimum and maximum price from plan text
                    const priceRegex = /\$([0-9,.]+)(?:\s*-\s*\$([0-9,.]+))?/;
                    const match = priceRegex.exec(planText);
                    
                    if (match) {
                        const minPrice = parseFloat(match[1].replace(',', ''));
                        const maxPrice = match[2] ? parseFloat(match[2].replace(',', '')) : Infinity;
                        const amount = parseFloat(amountInput.value);
                        
                        if (amount < minPrice) {
                            amountInput.setCustomValidity(`Minimum investment for this plan is $${minPrice.toFixed(2)}`);
                        } else if (amount > maxPrice && maxPrice !== Infinity) {
                            amountInput.setCustomValidity(`Maximum investment for this plan is $${maxPrice.toFixed(2)}`);
                        } else {
                            amountInput.setCustomValidity('');
                        }
                    }
                }
            }
            
            // Also apply validation to edit form
            document.getElementById('edit-plan').addEventListener('change', validateEditAmount);
            document.getElementById('edit-amount').addEventListener('input', validateEditAmount);
            
            function validateEditAmount() {
                const planSelect = document.getElementById('edit-plan');
                const amountInput = document.getElementById('edit-amount');
                
                if (planSelect.value && amountInput.value) {
                    const planOption = planSelect.options[planSelect.selectedIndex];
                    const planText = planOption.text;
                    
                    // Extract minimum and maximum price from plan text
                    const priceRegex = /\$([0-9,.]+)(?:\s*-\s*\$([0-9,.]+))?/;
                    const match = priceRegex.exec(planText);
                    
                    if (match) {
                        const minPrice = parseFloat(match[1].replace(',', ''));
                        const maxPrice = match[2] ? parseFloat(match[2].replace(',', '')) : Infinity;
                        const amount = parseFloat(amountInput.value);
                        
                        if (amount < minPrice) {
                            amountInput.setCustomValidity(`Minimum investment for this plan is $${minPrice.toFixed(2)}`);
                        } else if (amount > maxPrice && maxPrice !== Infinity) {
                            amountInput.setCustomValidity(`Maximum investment for this plan is $${maxPrice.toFixed(2)}`);
                        } else {
                            amountInput.setCustomValidity('');
                        }
                    }
                }
            }
        });
    </script>
</body>
</html>