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

// Handle investment status update
$message = '';
$message_type = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $investment_id = intval($_POST['investment_id']);
    $status = mysqli_real_escape_string($conn, $_POST['status']);
    
    // Get investment details with user and plan information
    $investment_query = "
        SELECT 
            ci.*, 
            cp.plan_name, 
            cp.profit_percentage, 
            cp.duration_days,
            u.id as user_id,
            u.account_balance,
            u.email,
            u.full_name,
            u.username
        FROM copy_trade_investments ci
        JOIN copy_trade_plans cp ON ci.plan_id = cp.id
        JOIN users u ON ci.user_id = u.id
        WHERE ci.id = ?
    ";
    
    $investment_stmt = $conn->prepare($investment_query);
    $investment_stmt->bind_param("i", $investment_id);
    $investment_stmt->execute();
    $investment_result = $investment_stmt->get_result();
    
    if ($investment_result->num_rows === 0) {
        $message = "Investment not found";
        $message_type = "error";
    } else {
        $investment = $investment_result->fetch_assoc();
        $investment_stmt->close();
        
        // Check if status is actually changing
        if ($investment['status'] === $status) {
            $message = "Investment is already " . $status;
            $message_type = "error";
        } else {
            // Begin transaction
            $conn->begin_transaction();
            
            try {
                // Calculate amounts
                $profit_amount = 0;
                $total_return = 0;
                
                if ($status === 'completed') {
                    $profit_amount = ($investment['amount'] * $investment['profit_percentage']) / 100;
                    $total_return = $investment['amount'] + $profit_amount;
                } elseif ($status === 'rejected') {
                    $total_return = $investment['amount']; // Return only the invested amount
                }
                
                // Update investment status
                $update_stmt = $conn->prepare("UPDATE copy_trade_investments SET status = ? WHERE id = ?");
                $update_stmt->bind_param("si", $status, $investment_id);
                
                if (!$update_stmt->execute()) {
                    throw new Exception("Failed to update investment status");
                }
                
                // Handle balance updates for completed or rejected investments
                if (in_array($status, ['completed', 'rejected'])) {
                    // Calculate new balance
                    $new_balance = $investment['account_balance'] + $total_return;
                    
                    // Update user balance
                    $balance_stmt = $conn->prepare("UPDATE users SET account_balance = ? WHERE id = ?");
                    $balance_stmt->bind_param("di", $new_balance, $investment['user_id']);
                    
                    if (!$balance_stmt->execute()) {
                        throw new Exception("Failed to update user balance");
                    }
                    
                    // Update total invested for completed investments
                    if ($status === 'completed') {
                        $total_invested_stmt = $conn->prepare("UPDATE users SET total_invested = total_invested + ? WHERE id = ?");
                        $total_invested_stmt->bind_param("di", $investment['amount'], $investment['user_id']);
                        
                        if (!$total_invested_stmt->execute()) {
                            throw new Exception("Failed to update total invested");
                        }
                        $total_invested_stmt->close();
                    }
                    
                    $balance_stmt->close();
                }
                
                // Create notification for user
                $notif_title = "Investment " . ucfirst($status);
                
                if ($status === 'completed') {
                    $notification_message = "Your investment of $" . number_format($investment['amount'], 2) . 
                        " in {$investment['plan_name']} has been completed. You received $" . 
                        number_format($total_return, 2) . " (Initial: $" . number_format($investment['amount'], 2) . 
                        " + Profit: $" . number_format($profit_amount, 2) . ")";
                } elseif ($status === 'rejected') {
                    $notification_message = "Your investment of $" . number_format($investment['amount'], 2) . 
                        " in {$investment['plan_name']} has been rejected. The amount has been returned to your balance.";
                } elseif ($status === 'approved' || $status === 'active') {
                    $notification_message = "Your investment of $" . number_format($investment['amount'], 2) . 
                        " in {$investment['plan_name']} has been approved and is now active.";
                } else {
                    $notification_message = "Your investment status has been updated to: " . $status;
                }
                
                // Check if notifications table exists
                $check_table = $conn->query("SHOW TABLES LIKE 'notifications'");
                if ($check_table->num_rows > 0) {
                    $notif_stmt = $conn->prepare("
                        INSERT INTO notifications (user_id, title, message, notification_type) 
                        VALUES (?, ?, ?, 'investment')
                    ");
                    $notif_stmt->bind_param("iss", $investment['user_id'], $notif_title, $notification_message);
                    
                    if (!$notif_stmt->execute()) {
                        // Log error but don't rollback transaction for notification failure
                        error_log("Failed to create notification: " . $conn->error);
                    }
                    $notif_stmt->close();
                }
                
                // Commit transaction
                $conn->commit();
                
                // Prepare success message
                if ($status === 'completed') {
                    $message = "Investment #{$investment_id} marked as completed. User received $" . number_format($total_return, 2) . 
                        " (Initial: $" . number_format($investment['amount'], 2) . " + Profit: $" . number_format($profit_amount, 2) . ")";
                } elseif ($status === 'rejected') {
                    $message = "Investment #{$investment_id} rejected. $" . number_format($investment['amount'], 2) . " returned to user.";
                } elseif ($status === 'approved' || $status === 'active') {
                    $message = "Investment #{$investment_id} approved successfully.";
                } else {
                    $message = "Investment #{$investment_id} status updated to {$status}";
                }
                
                $message_type = "success";
                
            } catch (Exception $e) {
                // Rollback transaction on error
                $conn->rollback();
                $message = "Error processing investment: " . $e->getMessage();
                $message_type = "error";
            }
            
            $update_stmt->close();
        }
    }
}

// Get filter parameters
$status_filter = isset($_GET['status']) ? $_GET['status'] : 'all';
$plan_filter = isset($_GET['plan_id']) ? intval($_GET['plan_id']) : 0;

// Build query based on filters
$query = "
    SELECT 
        ci.*,
        u.username,
        u.full_name,
        u.email,
        u.account_balance as user_balance,
        cp.plan_name,
        cp.profit_percentage,
        cp.duration_days,
        cp.min_investment,
        cp.max_investment
    FROM copy_trade_investments ci
    JOIN users u ON ci.user_id = u.id
    JOIN copy_trade_plans cp ON ci.plan_id = cp.id
    WHERE 1=1
";

$params = [];
$types = "";

if ($status_filter !== 'all') {
    $query .= " AND ci.status = ?";
    $params[] = $status_filter;
    $types .= "s";
}

if ($plan_filter > 0) {
    $query .= " AND ci.plan_id = ?";
    $params[] = $plan_filter;
    $types .= "i";
}

$query .= " ORDER BY ci.created_at DESC";

$investments_stmt = $conn->prepare($query);
if (!empty($params)) {
    $investments_stmt->bind_param($types, ...$params);
}
$investments_stmt->execute();
$investments_result = $investments_stmt->get_result();
$investments_stmt->close();

// Fetch all plans for filter dropdown
$plans_query = "SELECT id, plan_name FROM copy_trade_plans ORDER BY plan_name";
$plans_result = $conn->query($plans_query);

// Get statistics
$stats = [];

// Total investments
$stats_query = "SELECT COUNT(*) as total FROM copy_trade_investments";
$stats_result = $conn->query($stats_query);
$stats['total'] = $stats_result->fetch_assoc()['total'];

// Pending investments
$stats_query = "SELECT COUNT(*) as pending FROM copy_trade_investments WHERE status = 'pending'";
$stats_result = $conn->query($stats_query);
$stats['pending'] = $stats_result->fetch_assoc()['pending'];

// Active investments
$stats_query = "SELECT COUNT(*) as active FROM copy_trade_investments WHERE status IN ('active', 'approved')";
$stats_result = $conn->query($stats_query);
$stats['active'] = $stats_result->fetch_assoc()['active'];

// Completed investments
$stats_query = "SELECT COUNT(*) as completed FROM copy_trade_investments WHERE status = 'completed'";
$stats_result = $conn->query($stats_query);
$stats['completed'] = $stats_result->fetch_assoc()['completed'];

// Rejected investments
$stats_query = "SELECT COUNT(*) as rejected FROM copy_trade_investments WHERE status = 'rejected'";
$stats_result = $conn->query($stats_query);
$stats['rejected'] = $stats_result->fetch_assoc()['rejected'];

// Total invested amount
$stats_query = "SELECT COALESCE(SUM(amount), 0) as total_amount FROM copy_trade_investments";
$stats_result = $conn->query($stats_query);
$stats['total_amount'] = $stats_result->fetch_assoc()['total_amount'];

// Pending amount
$stats_query = "SELECT COALESCE(SUM(amount), 0) as pending_amount FROM copy_trade_investments WHERE status = 'pending'";
$stats_result = $conn->query($stats_query);
$stats['pending_amount'] = $stats_result->fetch_assoc()['pending_amount'];
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Copy Trade Investments - Admin</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        body {
            font-family: 'Inter', sans-serif;
            background: #f3f4f6;
        }
        
        .stat-card {
            transition: all 0.3s ease;
        }
        
        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
        }
        
        .status-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 600;
            display: inline-flex;
            align-items: center;
            gap: 0.25rem;
        }
        
        .status-pending {
            background: #fef3c7;
            color: #92400e;
        }
        
        .status-active, .status-approved {
            background: #dbeafe;
            color: #1e40af;
        }
        
        .status-completed {
            background: #d1fae5;
            color: #065f46;
        }
        
        .status-rejected {
            background: #fee2e2;
            color: #991b1b;
        }
        
        .action-btn {
            transition: all 0.2s;
            display: inline-flex;
            align-items: center;
            gap: 0.25rem;
        }
        
        .action-btn:hover {
            transform: translateY(-2px);
        }
        
        /* Modal styles */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            align-items: center;
            justify-content: center;
        }
        
        .modal.active {
            display: flex;
        }
        
        .modal-content {
            background: white;
            border-radius: 1rem;
            max-width: 500px;
            width: 90%;
            max-height: 90vh;
            overflow-y: auto;
            animation: slideIn 0.3s ease-out;
        }
        
        @keyframes slideIn {
            from {
                transform: translateY(-50px);
                opacity: 0;
            }
            to {
                transform: translateY(0);
                opacity: 1;
            }
        }
        
        /* Mobile responsive */
        @media (max-width: 768px) {
            .table-container {
                overflow-x: auto;
            }
            
            .stats-grid {
                grid-template-columns: repeat(2, 1fr);
            }
        }
    </style>
</head>
<body class="bg-gray-50">

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

<div class="lg:ml-64 p-6">
    <!-- Header -->
    <div class="mb-8">
        <h1 class="text-3xl font-bold text-gray-800">Copy Trade Investments</h1>
        <p class="text-gray-600 mt-1">Manage and monitor all copy trade investments</p>
    </div>

    <!-- Alert Messages -->
    <?php if ($message): ?>
    <div class="mb-6 p-4 rounded-lg <?php echo $message_type === 'success' ? 'bg-green-100 text-green-700 border-green-400' : 'bg-red-100 text-red-700 border-red-400'; ?> border">
        <div class="flex items-center justify-between">
            <div class="flex items-center gap-3">
                <i class="fas fa-<?php echo $message_type === 'success' ? 'check-circle' : 'exclamation-circle'; ?>"></i>
                <span><?php echo htmlspecialchars($message); ?></span>
            </div>
            <button onclick="this.parentElement.parentElement.remove()" class="text-gray-500 hover:text-gray-700">
                <i class="fas fa-times"></i>
            </button>
        </div>
    </div>
    <?php endif; ?>

    <!-- Statistics Cards -->
    <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-7 gap-4 mb-8">
        <div class="stat-card bg-white rounded-xl shadow-sm border border-gray-200 p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-500">Total</p>
                    <p class="text-2xl font-bold text-gray-800"><?php echo $stats['total']; ?></p>
                </div>
                <div class="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center">
                    <i class="fas fa-chart-line text-blue-600"></i>
                </div>
            </div>
        </div>
        
        <div class="stat-card bg-white rounded-xl shadow-sm border border-gray-200 p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-500">Pending</p>
                    <p class="text-2xl font-bold text-yellow-600"><?php echo $stats['pending']; ?></p>
                </div>
                <div class="w-10 h-10 bg-yellow-100 rounded-lg flex items-center justify-center">
                    <i class="fas fa-clock text-yellow-600"></i>
                </div>
            </div>
        </div>
        
        <div class="stat-card bg-white rounded-xl shadow-sm border border-gray-200 p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-500">Active</p>
                    <p class="text-2xl font-bold text-blue-600"><?php echo $stats['active']; ?></p>
                </div>
                <div class="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center">
                    <i class="fas fa-play text-blue-600"></i>
                </div>
            </div>
        </div>
        
        <div class="stat-card bg-white rounded-xl shadow-sm border border-gray-200 p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-500">Completed</p>
                    <p class="text-2xl font-bold text-green-600"><?php echo $stats['completed']; ?></p>
                </div>
                <div class="w-10 h-10 bg-green-100 rounded-lg flex items-center justify-center">
                    <i class="fas fa-check-circle text-green-600"></i>
                </div>
            </div>
        </div>
        
        <div class="stat-card bg-white rounded-xl shadow-sm border border-gray-200 p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-500">Rejected</p>
                    <p class="text-2xl font-bold text-red-600"><?php echo $stats['rejected']; ?></p>
                </div>
                <div class="w-10 h-10 bg-red-100 rounded-lg flex items-center justify-center">
                    <i class="fas fa-times-circle text-red-600"></i>
                </div>
            </div>
        </div>
        
        <div class="stat-card bg-white rounded-xl shadow-sm border border-gray-200 p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-500">Total Amount</p>
                    <p class="text-lg font-bold text-gray-800">$<?php echo number_format($stats['total_amount'], 2); ?></p>
                </div>
                <div class="w-10 h-10 bg-purple-100 rounded-lg flex items-center justify-center">
                    <i class="fas fa-dollar-sign text-purple-600"></i>
                </div>
            </div>
        </div>
        
        <div class="stat-card bg-white rounded-xl shadow-sm border border-gray-200 p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-500">Pending Amount</p>
                    <p class="text-lg font-bold text-yellow-600">$<?php echo number_format($stats['pending_amount'], 2); ?></p>
                </div>
                <div class="w-10 h-10 bg-yellow-100 rounded-lg flex items-center justify-center">
                    <i class="fas fa-hourglass-half text-yellow-600"></i>
                </div>
            </div>
        </div>
    </div>

    <!-- Filters -->
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-4 mb-6">
        <form method="GET" action="" class="flex flex-wrap gap-4 items-end">
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Status Filter</label>
                <select name="status" class="border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary-500">
                    <option value="all" <?php echo $status_filter === 'all' ? 'selected' : ''; ?>>All Status</option>
                    <option value="pending" <?php echo $status_filter === 'pending' ? 'selected' : ''; ?>>Pending</option>
                    <option value="active" <?php echo $status_filter === 'active' ? 'selected' : ''; ?>>Active</option>
                    <option value="completed" <?php echo $status_filter === 'completed' ? 'selected' : ''; ?>>Completed</option>
                    <option value="rejected" <?php echo $status_filter === 'rejected' ? 'selected' : ''; ?>>Rejected</option>
                </select>
            </div>
            
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Plan Filter</label>
                <select name="plan_id" class="border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary-500">
                    <option value="0">All Plans</option>
                    <?php if ($plans_result): ?>
                        <?php $plans_result->data_seek(0); ?>
                        <?php while ($plan = $plans_result->fetch_assoc()): ?>
                        <option value="<?php echo $plan['id']; ?>" <?php echo $plan_filter == $plan['id'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($plan['plan_name']); ?>
                        </option>
                        <?php endwhile; ?>
                    <?php endif; ?>
                </select>
            </div>
            
            <div>
                <button type="submit" class="bg-primary-600 text-white px-4 py-2 rounded-lg hover:bg-primary-700 transition">
                    <i class="fas fa-filter mr-2"></i>
                    Apply Filters
                </button>
            </div>
            
            <div>
                <a href="copy-trades.php" class="bg-gray-500 text-white px-4 py-2 rounded-lg hover:bg-gray-600 transition">
                    <i class="fas fa-redo mr-2"></i>
                    Reset
                </a>
            </div>
        </form>
    </div>

    <!-- Investments Table -->
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
        <div class="overflow-x-auto">
            <table class="w-full">
                <thead class="bg-gray-50 border-b border-gray-200">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">User</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Plan</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Amount</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Profit %</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Expected Return</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Date</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-200">
                    <?php if ($investments_result && $investments_result->num_rows > 0): ?>
                        <?php while ($investment = $investments_result->fetch_assoc()): 
                            $status_class = '';
                            switch ($investment['status']) {
                                case 'pending':
                                    $status_class = 'status-pending';
                                    break;
                                case 'active':
                                case 'approved':
                                    $status_class = 'status-active';
                                    break;
                                case 'completed':
                                    $status_class = 'status-completed';
                                    break;
                                case 'rejected':
                                    $status_class = 'status-rejected';
                                    break;
                                default:
                                    $status_class = 'status-pending';
                            }
                            
                            $expected_profit = ($investment['amount'] * $investment['profit_percentage']) / 100;
                            $total_return = $investment['amount'] + $expected_profit;
                            
                            // Determine which action buttons to show based on status
                            $show_approve = false;
                            $show_reject = false;
                            $show_complete = false;
                            
                            if ($investment['status'] === 'pending') {
                                $show_approve = true;
                                $show_reject = true;
                            } elseif ($investment['status'] === 'active' || $investment['status'] === 'approved') {
                                $show_complete = true;
                            }
                        ?>
                        <tr class="hover:bg-gray-50 transition">
                            <td class="px-6 py-4 text-sm font-medium text-gray-900">#<?php echo $investment['id']; ?></td>
                            <td class="px-6 py-4">
                                <div class="text-sm font-medium text-gray-900"><?php echo htmlspecialchars($investment['full_name'] ?: $investment['username']); ?></div>
                                <div class="text-xs text-gray-500"><?php echo htmlspecialchars($investment['email']); ?></div>
                            </td>
                            <td class="px-6 py-4">
                                <div class="text-sm font-medium text-gray-900"><?php echo htmlspecialchars($investment['plan_name']); ?></div>
                                <div class="text-xs text-gray-500"><?php echo $investment['duration_days']; ?> days</div>
                            </td>
                            <td class="px-6 py-4 text-sm font-medium text-gray-900">$<?php echo number_format($investment['amount'], 2); ?></td>
                            <td class="px-6 py-4 text-sm text-green-600 font-medium">+<?php echo $investment['profit_percentage']; ?>%</td>
                            <td class="px-6 py-4">
                                <div class="text-sm font-medium text-green-600">$<?php echo number_format($expected_profit, 2); ?></div>
                                <div class="text-xs text-gray-500">Total: $<?php echo number_format($total_return, 2); ?></div>
                            </td>
                            <td class="px-6 py-4 text-sm text-gray-500"><?php echo date('M d, Y', strtotime($investment['created_at'])); ?></td>
                            <td class="px-6 py-4">
                                <span class="status-badge <?php echo $status_class; ?>">
                                    <i class="fas fa-<?php 
                                        echo $investment['status'] === 'pending' ? 'clock' : 
                                            ($investment['status'] === 'active' ? 'play' : 
                                            ($investment['status'] === 'approved' ? 'check' :
                                            ($investment['status'] === 'completed' ? 'check-circle' : 'times'))); 
                                    ?>"></i>
                                    <?php echo ucfirst($investment['status']); ?>
                                </span>
                            </td>
                            <td class="px-6 py-4">
                                <div class="flex space-x-2">
                                    <?php if ($show_approve): ?>
                                    <button onclick="showActionModal(<?php echo $investment['id']; ?>, '<?php echo htmlspecialchars($investment['plan_name']); ?>', '<?php echo htmlspecialchars($investment['full_name'] ?: $investment['username']); ?>', <?php echo $investment['amount']; ?>, <?php echo $investment['profit_percentage']; ?>, 'approved')" 
                                            class="action-btn text-green-600 hover:text-green-800 bg-green-100 px-3 py-1 rounded-lg text-sm font-medium">
                                        <i class="fas fa-check mr-1"></i> Approve
                                    </button>
                                    <?php endif; ?>
                                    
                                    <?php if ($show_reject): ?>
                                    <button onclick="showActionModal(<?php echo $investment['id']; ?>, '<?php echo htmlspecialchars($investment['plan_name']); ?>', '<?php echo htmlspecialchars($investment['full_name'] ?: $investment['username']); ?>', <?php echo $investment['amount']; ?>, <?php echo $investment['profit_percentage']; ?>, 'rejected')" 
                                            class="action-btn text-red-600 hover:text-red-800 bg-red-100 px-3 py-1 rounded-lg text-sm font-medium">
                                        <i class="fas fa-times mr-1"></i> Reject
                                    </button>
                                    <?php endif; ?>
                                    
                                    <?php if ($show_complete): ?>
                                    <button onclick="showActionModal(<?php echo $investment['id']; ?>, '<?php echo htmlspecialchars($investment['plan_name']); ?>', '<?php echo htmlspecialchars($investment['full_name'] ?: $investment['username']); ?>', <?php echo $investment['amount']; ?>, <?php echo $investment['profit_percentage']; ?>, 'completed')" 
                                            class="action-btn text-blue-600 hover:text-blue-800 bg-blue-100 px-3 py-1 rounded-lg text-sm font-medium">
                                        <i class="fas fa-check-circle mr-1"></i> Complete
                                    </button>
                                    <?php endif; ?>
                                    
                                    <?php if (!$show_approve && !$show_reject && !$show_complete): ?>
                                    <span class="text-gray-400 text-sm">No actions</span>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    <?php else: ?>
                    <tr>
                        <td colspan="9" class="px-6 py-12 text-center text-gray-500">
                            <i class="fas fa-inbox text-4xl mb-3 block text-gray-400"></i>
                            No investments found
                        </td>
                    </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Action Confirmation Modal -->
<div class="modal" id="actionModal">
    <div class="modal-content">
        <div class="p-6 border-b border-gray-200 flex items-center justify-between">
            <h3 class="text-xl font-bold text-gray-800" id="modalTitle">Confirm Action</h3>
            <button onclick="closeModal()" class="text-gray-400 hover:text-gray-600">
                <i class="fas fa-times text-xl"></i>
            </button>
        </div>
        
        <form method="POST" action="" class="p-6">
            <input type="hidden" name="investment_id" id="modalInvestmentId">
            <input type="hidden" name="status" id="modalStatus">
            
            <div id="modalContent" class="mb-6">
                <!-- Dynamic content will be inserted here -->
            </div>
            
            <div class="bg-gray-50 p-4 rounded-lg mb-6">
                <h4 class="font-medium text-gray-700 mb-2">Investment Summary</h4>
                <div class="space-y-2 text-sm">
                    <div class="flex justify-between">
                        <span class="text-gray-600">User:</span>
                        <span class="font-medium text-gray-800" id="modalUser"></span>
                    </div>
                    <div class="flex justify-between">
                        <span class="text-gray-600">Plan:</span>
                        <span class="font-medium text-gray-800" id="modalPlan"></span>
                    </div>
                    <div class="flex justify-between">
                        <span class="text-gray-600">Amount:</span>
                        <span class="font-medium text-gray-800" id="modalAmount"></span>
                    </div>
                    <div class="flex justify-between">
                        <span class="text-gray-600">Profit %:</span>
                        <span class="font-medium text-green-600" id="modalProfit"></span>
                    </div>
                    <div class="flex justify-between pt-2 border-t border-gray-200" id="modalReturnRow">
                        <span class="text-gray-600">Total Return:</span>
                        <span class="font-bold text-green-600" id="modalReturn"></span>
                    </div>
                </div>
            </div>
            
            <div class="flex gap-3">
                <button type="button" onclick="closeModal()" class="flex-1 bg-gray-100 text-gray-700 px-4 py-2 rounded-lg hover:bg-gray-200 transition">
                    Cancel
                </button>
                <button type="submit" name="action" class="flex-1 text-white px-4 py-2 rounded-lg transition" id="modalConfirmBtn">
                    Confirm
                </button>
            </div>
        </form>
    </div>
</div>

<script>
    // Modal functions
    function showActionModal(investmentId, planName, userName, amount, profitPercentage, action) {
        const modal = document.getElementById('actionModal');
        const modalTitle = document.getElementById('modalTitle');
        const modalContent = document.getElementById('modalContent');
        const modalInvestmentId = document.getElementById('modalInvestmentId');
        const modalStatus = document.getElementById('modalStatus');
        const modalUser = document.getElementById('modalUser');
        const modalPlan = document.getElementById('modalPlan');
        const modalAmount = document.getElementById('modalAmount');
        const modalProfit = document.getElementById('modalProfit');
        const modalReturn = document.getElementById('modalReturn');
        const modalReturnRow = document.getElementById('modalReturnRow');
        const modalConfirmBtn = document.getElementById('modalConfirmBtn');
        
        const expectedProfit = (amount * profitPercentage) / 100;
        const totalReturn = amount + expectedProfit;
        
        modalInvestmentId.value = investmentId;
        modalStatus.value = action;
        modalUser.textContent = userName;
        modalPlan.textContent = planName;
        modalAmount.textContent = '$' + amount.toFixed(2);
        modalProfit.textContent = '+' + profitPercentage + '% ($' + expectedProfit.toFixed(2) + ')';
        
        // Reset classes
        modalConfirmBtn.classList.remove('bg-green-600', 'hover:bg-green-700', 'bg-red-600', 'hover:bg-red-700', 'bg-blue-600', 'hover:bg-blue-700');
        
        if (action === 'completed') {
            modalTitle.textContent = 'Mark Investment as Completed';
            modalContent.innerHTML = '<p class="text-gray-600">Are you sure you want to mark this investment as completed? The user will receive:</p>';
            modalReturn.textContent = '$' + totalReturn.toFixed(2);
            modalReturnRow.style.display = 'flex';
            modalConfirmBtn.textContent = 'Complete Investment';
            modalConfirmBtn.classList.add('bg-green-600', 'hover:bg-green-700');
        } else if (action === 'rejected') {
            modalTitle.textContent = 'Reject Investment';
            modalContent.innerHTML = '<p class="text-gray-600">Are you sure you want to reject this investment? The invested amount will be returned to the user.</p>';
            modalReturn.textContent = '$' + amount.toFixed(2);
            modalReturnRow.style.display = 'flex';
            modalConfirmBtn.textContent = 'Reject Investment';
            modalConfirmBtn.classList.add('bg-red-600', 'hover:bg-red-700');
        } else if (action === 'approved') {
            modalTitle.textContent = 'Approve Investment';
            modalContent.innerHTML = '<p class="text-gray-600">Are you sure you want to approve this investment? The amount will be deducted from user\'s balance and investment will become active.</p>';
            modalReturnRow.style.display = 'none';
            modalConfirmBtn.textContent = 'Approve Investment';
            modalConfirmBtn.classList.add('bg-green-600', 'hover:bg-green-700');
        }
        
        modal.classList.add('active');
    }
    
    function closeModal() {
        document.getElementById('actionModal').classList.remove('active');
    }
    
    // Close modal when clicking outside
    window.addEventListener('click', function(e) {
        const modal = document.getElementById('actionModal');
        if (e.target === modal) {
            closeModal();
        }
    });
    
    // Escape key to close modal
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            closeModal();
        }
    });
    
    // Auto-hide alerts after 5 seconds
    setTimeout(function() {
        const alerts = document.querySelectorAll('.bg-green-100, .bg-red-100');
        alerts.forEach(alert => {
            alert.style.transition = 'opacity 0.5s';
            alert.style.opacity = '0';
            setTimeout(() => alert.remove(), 500);
        });
    }, 5000);
</script>

</body>
</html>