<?php
$page_title = "Investments Management";
require_once 'header.php';

$db = Database::getInstance()->connect();

// Handle actions
if (isset($_GET['action']) && isset($_GET['id'])) {
    $action = $_GET['action'];
    $investment_id = $_GET['id'];
    
    try {
        $db->beginTransaction();
        
        // Get investment details
        $stmt = $db->prepare("SELECT i.*, u.username, u.email FROM investments i 
                             JOIN users u ON i.user_id = u.id 
                             WHERE i.id = ?");
        $stmt->execute([$investment_id]);
        $investment = $stmt->fetch();
        
        if (!$investment) {
            throw new Exception("Investment not found");
        }
        
        $user_id = $investment['user_id'];
        $amount = $investment['amount'];
        
        if ($action == 'complete') {
            // Mark as completed
            $update_stmt = $db->prepare("UPDATE investments SET status = 'completed', end_date = NOW() WHERE id = ?");
            $update_stmt->execute([$investment_id]);
            
            // Return principal if applicable
            $plan_stmt = $db->prepare("SELECT principal_return FROM investment_plans WHERE id = ?");
            $plan_stmt->execute([$investment['plan_id']]);
            $plan = $plan_stmt->fetch();
            
            if ($plan['principal_return']) {
                $balance_stmt = $db->prepare("UPDATE users SET balance = balance + ? WHERE id = ?");
                $balance_stmt->execute([$amount, $user_id]);
                
                // Record transaction
                $reference = 'INV' . time() . rand(1000, 9999);
                $tx_stmt = $db->prepare("INSERT INTO transactions (user_id, type, amount, method, description, reference, status) 
                                        VALUES (?, 'investment_return', ?, 'system', 'Principal return from investment #$investment_id', ?, 'completed')");
                $tx_stmt->execute([$user_id, $amount, $reference]);
            }
            
            $message = "Investment marked as completed!";
            $success = true;
            
        } elseif ($action == 'cancel') {
            // Mark as cancelled
            $update_stmt = $db->prepare("UPDATE investments SET status = 'cancelled', end_date = NOW() WHERE id = ?");
            $update_stmt->execute([$investment_id]);
            
            // Return principal
            $balance_stmt = $db->prepare("UPDATE users SET balance = balance + ? WHERE id = ?");
            $balance_stmt->execute([$amount, $user_id]);
            
            $message = "Investment cancelled and principal returned!";
            $success = true;
            
        } elseif ($action == 'delete') {
            // Return principal first
            $balance_stmt = $db->prepare("UPDATE users SET balance = balance + ? WHERE id = ?");
            $balance_stmt->execute([$amount, $user_id]);
            
            // Delete investment
            $delete_stmt = $db->prepare("DELETE FROM investments WHERE id = ?");
            $delete_stmt->execute([$investment_id]);
            
            $message = "Investment deleted and principal returned!";
            $success = true;
        }
        
        // Log action
        if ($success) {
            $log_stmt = $db->prepare("INSERT INTO activity_logs (admin_id, user_id, action, details) VALUES (?, ?, 'investment_$action', ?)");
            $log_stmt->execute([
                $_SESSION['admin_id'],
                $user_id,
                json_encode([
                    'investment_id' => $investment_id,
                    'amount' => $amount,
                    'plan_id' => $investment['plan_id']
                ])
            ]);
        }
        
        $db->commit();
        
        if ($success) {
            $redirect = 'investments.php';
            if (isset($_GET['from']) && $_GET['from'] == 'view') {
                // If deleted, go to list, otherwise stay on view
                $redirect = ($action == 'delete') ? 'investments.php' : "investment-view.php?id=$investment_id";
            }
            echo "<script>alert('$message'); window.location.href='$redirect';</script>";
            exit();
        }
        
    } catch (Exception $e) {
        $db->rollBack();
        $error = "Action failed: " . $e->getMessage();
    }
}

// Get investments
$status = $_GET['status'] ?? 'running';
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$limit = 20;
$offset = ($page - 1) * $limit;

// Build query
$where = "WHERE 1=1";
$params = [];

if ($status != 'all') {
    $where .= " AND i.status = ?";
    $params[] = $status;
}

if (isset($_GET['user_id'])) {
    $where .= " AND i.user_id = ?";
    $params[] = $_GET['user_id'];
}

if (isset($_GET['plan_id'])) {
    $where .= " AND i.plan_id = ?";
    $params[] = $_GET['plan_id'];
}

// Get total count
$count_sql = "SELECT COUNT(*) as total FROM investments i $where";
$count_stmt = $db->prepare($count_sql);
$count_stmt->execute($params);
$total_investments = $count_stmt->fetch()['total'];
$total_pages = ceil($total_investments / $limit);

// Get investments with user and plan details
$sql = "SELECT i.*, u.username, u.email, p.name as plan_name, p.daily_return, p.duration_days 
        FROM investments i 
        JOIN users u ON i.user_id = u.id 
        JOIN investment_plans p ON i.plan_id = p.id 
        $where 
        ORDER BY i.created_at DESC 
        LIMIT $limit OFFSET $offset";

$stmt = $db->prepare($sql);
$stmt->execute($params);
$investments = $stmt->fetchAll();

// Get stats
$stats_sql = "SELECT 
    COUNT(*) as total,
    SUM(CASE WHEN status = 'running' THEN 1 ELSE 0 END) as running,
    SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed,
    SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) as cancelled,
    SUM(amount) as total_invested,
    SUM(total_profit) as total_profits
    FROM investments";

$stats_stmt = $db->query($stats_sql);
$stats = $stats_stmt->fetch();

// Get plans for filter
$plans_stmt = $db->query("SELECT id, name FROM investment_plans WHERE status = 'active'");
$plans = $plans_stmt->fetchAll();
?>

<div class="container-fluid">
    <!-- Stats Cards -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm">Total Investments</p>
                    <h3 class="text-2xl font-bold"><?php echo number_format((int)($stats['total'] ?? 0)); ?></h3>
                </div>
                <i class="fas fa-chart-pie text-purple-500 text-2xl"></i>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm">Running Investments</p>
                    <h3 class="text-2xl font-bold text-green-600"><?php echo number_format((int)($stats['running'] ?? 0)); ?></h3>
                </div>
                <i class="fas fa-running text-green-500 text-2xl"></i>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm">Total Invested</p>
                    <h3 class="text-2xl font-bold">$<?php echo number_format((float)($stats['total_invested'] ?? 0), 2); ?></h3>
                </div>
                <i class="fas fa-money-bill-wave text-blue-500 text-2xl"></i>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm">Total Profits</p>
                    <h3 class="text-2xl font-bold text-green-600">$<?php echo number_format((float)($stats['total_profits'] ?? 0), 2); ?></h3>
                </div>
                <i class="fas fa-coins text-yellow-500 text-2xl"></i>
            </div>
        </div>
    </div>

    <!-- Filters -->
    <div class="bg-white rounded-xl shadow p-6 mb-6">
        <div class="flex flex-wrap gap-4 items-center">
            <div class="flex space-x-2">
                <a href="?status=running" class="px-4 py-2 rounded-lg <?php echo $status == 'running' ? 'bg-green-100 text-green-800' : 'bg-gray-100'; ?>">
                    Running (<?php echo $stats['running']; ?>)
                </a>
                <a href="?status=completed" class="px-4 py-2 rounded-lg <?php echo $status == 'completed' ? 'bg-blue-100 text-blue-800' : 'bg-gray-100'; ?>">
                    Completed (<?php echo $stats['completed']; ?>)
                </a>
                <a href="?status=cancelled" class="px-4 py-2 rounded-lg <?php echo $status == 'cancelled' ? 'bg-red-100 text-red-800' : 'bg-gray-100'; ?>">
                    Cancelled (<?php echo $stats['cancelled']; ?>)
                </a>
                <a href="?status=all" class="px-4 py-2 rounded-lg <?php echo $status == 'all' ? 'bg-purple-100 text-purple-800' : 'bg-gray-100'; ?>">
                    All Investments
                </a>
            </div>
            
            <div class="flex-1">
                <form method="GET" class="flex gap-2">
                    <input type="text" name="user_id" value="<?php echo $_GET['user_id'] ?? ''; ?>"
                           class="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500"
                           placeholder="Filter by User ID">
                    <select name="plan_id" class="px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                        <option value="">All Plans</option>
                        <?php foreach ($plans as $plan): ?>
                        <option value="<?php echo $plan['id']; ?>" <?php echo ($_GET['plan_id'] ?? '') == $plan['id'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($plan['name']); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                    <button type="submit" class="bg-gray-800 text-white px-4 py-2 rounded-lg hover:bg-gray-900">
                        <i class="fas fa-search"></i>
                    </button>
                </form>
            </div>
            
            <div>
                <button onclick="exportInvestments()" class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700">
                    <i class="fas fa-download mr-2"></i>Export
                </button>
            </div>
        </div>
    </div>

    <!-- Investments Table -->
    <div class="bg-white rounded-xl shadow overflow-hidden">
        <div class="overflow-x-auto">
            <table class="w-full">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="p-4 text-left">Investment</th>
                        <th class="p-4 text-left">User</th>
                        <th class="p-4 text-left">Plan</th>
                        <th class="p-4 text-left">Amount</th>
                        <th class="p-4 text-left">Daily Profit</th>
                        <th class="p-4 text-left">Total Profit</th>
                        <th class="p-4 text-left">Period</th>
                        <th class="p-4 text-left">Status</th>
                        <th class="p-4 text-left">Actions</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-100">
                    <?php if (count($investments) > 0): ?>
                        <?php foreach ($investments as $investment): 
                            $days_elapsed = floor((time() - strtotime($investment['start_date'])) / 86400);
                            $total_days = $investment['duration_days'];
                            $days_left = max(0, $total_days - $days_elapsed);
                            $progress = min(100, ($days_elapsed / $total_days) * 100);
                        ?>
                        <tr class="hover:bg-gray-50">
                            <!-- Investment Info -->
                            <td class="p-4">
                                <p class="font-medium">ID: <?php echo $investment['id']; ?></p>
                                <p class="text-sm text-gray-500"><?php echo date('M d, Y', strtotime($investment['start_date'])); ?></p>
                            </td>
                            
                            <!-- User -->
                            <td class="p-4">
                                <p class="font-medium"><?php echo htmlspecialchars($investment['username']); ?></p>
                                <p class="text-sm text-gray-500"><?php echo htmlspecialchars($investment['email']); ?></p>
                                <p class="text-xs text-gray-500">ID: <?php echo $investment['user_id']; ?></p>
                            </td>
                            
                            <!-- Plan -->
                            <td class="p-4">
                                <p class="font-medium"><?php echo htmlspecialchars($investment['plan_name']); ?></p>
                                <p class="text-sm text-gray-500"><?php echo $investment['daily_return']; ?>% daily</p>
                                <p class="text-xs text-gray-500"><?php echo $total_days; ?> days</p>
                            </td>
                            
                            <!-- Amount -->
                            <td class="p-4">
                                <p class="font-bold">$<?php echo number_format($investment['amount'], 2); ?></p>
                            </td>
                            
                            <!-- Daily Profit -->
                            <td class="p-4">
                                <p class="font-bold text-green-600">$<?php echo number_format($investment['daily_profit'], 2); ?></p>
                                <p class="text-xs text-gray-500">Per day</p>
                            </td>
                            
                            <!-- Total Profit -->
                            <td class="p-4">
                                <p class="font-bold text-green-600">$<?php echo number_format($investment['total_profit'], 2); ?></p>
                                <p class="text-xs text-gray-500">Earned so far</p>
                            </td>
                            
                            <!-- Period -->
                            <td class="p-4">
                                <div class="space-y-2">
                                    <div class="flex justify-between text-sm">
                                        <span>Start:</span>
                                        <span><?php echo date('M d', strtotime($investment['start_date'])); ?></span>
                                    </div>
                                    <div class="flex justify-between text-sm">
                                        <span>End:</span>
                                        <span><?php echo date('M d, Y', strtotime($investment['end_date'])); ?></span>
                                    </div>
                                    <div class="flex justify-between text-sm">
                                        <span>Days left:</span>
                                        <span class="font-semibold <?php echo $days_left > 0 ? 'text-green-600' : 'text-red-600'; ?>">
                                            <?php echo $days_left; ?>
                                        </span>
                                    </div>
                                    <div class="w-full bg-gray-200 rounded-full h-2">
                                        <div class="bg-green-600 h-2 rounded-full" style="width: <?php echo $progress; ?>%"></div>
                                    </div>
                                </div>
                            </td>
                            
                            <!-- Status -->
                            <td class="p-4">
                                <span class="px-3 py-1 rounded-full text-xs font-semibold <?php
                                    echo $investment['status'] == 'running' ? 'bg-green-100 text-green-800' :
                                        ($investment['status'] == 'completed' ? 'bg-blue-100 text-blue-800' :
                                        'bg-red-100 text-red-800');
                                ?>">
                                    <?php echo ucfirst($investment['status']); ?>
                                </span>
                            </td>
                            
                            <!-- Actions -->
                            <td class="p-4">
                                <div class="flex flex-col space-y-2">
                                    <a href="investment-view.php?id=<?php echo $investment['id']; ?>" 
                                       class="text-blue-600 hover:text-blue-800 text-sm font-medium">
                                        <i class="fas fa-eye mr-1"></i> View
                                    </a>
                                    
                                    <?php if ($investment['status'] == 'running'): ?>
                                    <a href="?action=complete&id=<?php echo $investment['id']; ?>" 
                                       onclick="return confirm('Mark this investment as completed?')"
                                       class="text-green-600 hover:text-green-800 text-sm font-medium">
                                        <i class="fas fa-check mr-1"></i> Complete
                                    </a>
                                    <a href="?action=cancel&id=<?php echo $investment['id']; ?>" 
                                       onclick="return confirm('Cancel this investment? Principal will be returned to user.')"
                                       class="text-red-600 hover:text-red-800 text-sm font-medium">
                                        <i class="fas fa-times mr-1"></i> Cancel
                                    </a>
                                    <?php endif; ?>
                                    
                                    <a href="?action=delete&id=<?php echo $investment['id']; ?>" 
                                       onclick="return confirm('Delete this investment? Principal will be returned to user.')"
                                       class="text-red-600 hover:text-red-800 text-sm font-medium">
                                        <i class="fas fa-trash mr-1"></i> Delete
                                    </a>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="9" class="p-8 text-center text-gray-500">
                                <i class="fas fa-chart-pie text-4xl mb-4 text-gray-300"></i>
                                <p class="text-lg">No investments found</p>
                                <?php if ($status != 'all'): ?>
                                <p class="text-sm mt-2">Try viewing <a href="?status=all" class="text-purple-600">all investments</a></p>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        
        <!-- Pagination -->
        <?php if ($total_pages > 1): ?>
        <div class="border-t border-gray-100 p-4">
            <div class="flex items-center justify-between">
                <div class="text-sm text-gray-600">
                    Showing <?php echo ($offset + 1); ?> to <?php echo min($offset + $limit, $total_investments); ?> of <?php echo number_format($total_investments); ?> investments
                </div>
                <div class="flex space-x-2">
                    <?php if ($page > 1): ?>
                    <a href="?page=<?php echo $page - 1; ?>&status=<?php echo $status; ?><?php echo isset($_GET['user_id']) ? '&user_id=' . $_GET['user_id'] : ''; ?><?php echo isset($_GET['plan_id']) ? '&plan_id=' . $_GET['plan_id'] : ''; ?>"
                       class="px-3 py-2 bg-gray-100 rounded-lg hover:bg-gray-200">
                        <i class="fas fa-chevron-left"></i> Previous
                    </a>
                    <?php endif; ?>
                    
                    <?php
                    $start = max(1, $page - 2);
                    $end = min($total_pages, $start + 4);
                    
                    for ($i = $start; $i <= $end; $i++):
                    ?>
                    <a href="?page=<?php echo $i; ?>&status=<?php echo $status; ?><?php echo isset($_GET['user_id']) ? '&user_id=' . $_GET['user_id'] : ''; ?><?php echo isset($_GET['plan_id']) ? '&plan_id=' . $_GET['plan_id'] : ''; ?>"
                       class="px-3 py-2 rounded-lg <?php echo $i == $page ? 'bg-purple-600 text-white' : 'bg-gray-100 hover:bg-gray-200'; ?>">
                        <?php echo $i; ?>
                    </a>
                    <?php endfor; ?>
                    
                    <?php if ($page < $total_pages): ?>
                    <a href="?page=<?php echo $page + 1; ?>&status=<?php echo $status; ?><?php echo isset($_GET['user_id']) ? '&user_id=' . $_GET['user_id'] : ''; ?><?php echo isset($_GET['plan_id']) ? '&plan_id=' . $_GET['plan_id'] : ''; ?>"
                       class="px-3 py-2 bg-gray-100 rounded-lg hover:bg-gray-200">
                        Next <i class="fas fa-chevron-right"></i>
                    </a>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>
    
    <!-- Manual Investment -->
    <div class="mt-6 bg-white rounded-xl shadow p-6">
        <h4 class="text-lg font-bold mb-4">Create Manual Investment</h4>
        <form id="manualInvestmentForm" class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
                <label class="block text-gray-700 text-sm mb-1">User ID</label>
                <input type="number" id="manual_inv_user_id" required
                       class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
            </div>
            
            <div>
                <label class="block text-gray-700 text-sm mb-1">Plan</label>
                <select id="manual_inv_plan_id" required
                       class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                    <option value="">Select Plan</option>
                    <?php foreach ($plans as $plan): ?>
                    <option value="<?php echo $plan['id']; ?>"><?php echo htmlspecialchars($plan['name']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div>
                <label class="block text-gray-700 text-sm mb-1">Amount ($)</label>
                <input type="number" step="0.01" id="manual_inv_amount" required
                       class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
            </div>
            
            <div>
                <label class="block text-gray-700 text-sm mb-1">Start Date</label>
                <input type="date" id="manual_inv_start_date" 
                       value="<?php echo date('Y-m-d'); ?>"
                       class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
            </div>
            
            <div class="md:col-span-2">
                <button type="button" onclick="createManualInvestment()"
                        class="w-full bg-purple-600 text-white py-3 rounded-lg hover:bg-purple-700">
                    <i class="fas fa-plus-circle mr-2"></i>Create Manual Investment
                </button>
            </div>
        </form>
    </div>
</div>

<script>
function exportInvestments() {
    const params = new URLSearchParams(window.location.search);
    window.open(`../api/export-investments.php?${params.toString()}`, '_blank');
}

function createManualInvestment() {
    const userId = document.getElementById('manual_inv_user_id').value;
    const planId = document.getElementById('manual_inv_plan_id').value;
    const amount = document.getElementById('manual_inv_amount').value;
    const startDate = document.getElementById('manual_inv_start_date').value;
    
    if (!userId || !planId || !amount || amount <= 0) {
        showNotification('Please fill all fields with valid values', 'error');
        return;
    }
    
    if (confirm(`Create manual investment of $${amount} for user ID ${userId}?`)) {
        $.ajax({
            url: '../api/admin-actions.php',
            method: 'POST',
            data: {
                action: 'manual_investment',
                user_id: userId,
                plan_id: planId,
                amount: amount,
                start_date: startDate
            },
            success: function(response) {
                const result = typeof response === 'string' ? JSON.parse(response) : response;
                showNotification(result.message, result.success ? 'success' : 'error');
                if (result.success) {
                    document.getElementById('manualInvestmentForm').reset();
                    location.reload();
                }
            }
        });
    }
}

// Quick actions
function quickInvestmentAction(investmentId, action) {
    const actions = {
        'complete': 'Mark as completed',
        'cancel': 'Cancel and return principal',
        'delete': 'Delete and return principal'
    };
    
    if (confirm(`${actions[action]}?`)) {
        window.location.href = `?action=${action}&id=${investmentId}`;
    }
}
</script>

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