<?php
$userId = $_GET['user_id'] ?? null;
$search = $_GET['search'] ?? '';
$page = intval($_GET['p'] ?? 1);
$limit = 20;
$offset = ($page - 1) * $limit;

$where = '';
$params = [];
if ($userId) {
    $where = "WHERE i.user_id = :user_id";
    $params[':user_id'] = $userId;
} elseif ($search) {
    $where = "WHERE u.name LIKE :search OR u.phone LIKE :search OR i.name LIKE :search";
    $params[':search'] = "%$search%";
}

$stmt = $pdo->prepare("SELECT COUNT(*) FROM investments i JOIN users u ON i.user_id = u.id $where");
foreach ($params as $key => $value) {
    $stmt->bindValue($key, $value);
}
$stmt->execute();
$totalInvestments = $stmt->fetchColumn();
$totalPages = ceil($totalInvestments / $limit);

$stmt = $pdo->prepare("SELECT i.*, u.name as user_name, u.phone as user_phone, u.id as user_id FROM investments i JOIN users u ON i.user_id = u.id $where ORDER BY i.created_at DESC LIMIT :limit OFFSET :offset");
foreach ($params as $key => $value) {
    $stmt->bindValue($key, $value);
}
$stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();
$investments = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Buscar produtos para o modal de adicionar
$products = $pdo->query("SELECT * FROM investment_products WHERE is_active = 1 ORDER BY name")->fetchAll(PDO::FETCH_ASSOC);
?>
<div class="space-y-6">
    <!-- Header -->
    <div class="bg-white rounded-xl shadow-lg p-6">
        <div class="flex flex-col md:flex-row gap-4 items-center justify-between">
            <h3 class="text-2xl font-bold text-gray-800">Gerenciar Investimentos</h3>
            <div class="flex gap-3">
                <?php if ($userId): ?>
                    <a href="?page=investments" class="px-4 py-2 bg-gray-500 text-white rounded-lg hover:bg-gray-600 transition">
                        <i data-lucide="arrow-left"></i> Voltar
                    </a>
                <?php endif; ?>
                <form method="GET" class="flex gap-2">
                    <input type="hidden" name="page" value="investments">
                    <?php if ($userId): ?>
                        <input type="hidden" name="user_id" value="<?= $userId ?>">
                    <?php endif; ?>
                    <input type="text" name="search" value="<?= htmlspecialchars($search) ?>" placeholder="Buscar..." class="px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500">
                    <button type="submit" class="px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition">
                        <i data-lucide="search"></i>
                    </button>
                </form>
                <button onclick="openAddInvestmentModal()" class="px-6 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition">
                    <i data-lucide="plus"></i> Adicionar Investimento
                </button>
            </div>
        </div>
    </div>

    <!-- Tabela de Investimentos -->
    <div class="bg-white rounded-xl shadow-lg overflow-hidden">
        <div class="overflow-x-auto">
            <table class="w-full">
                <thead class="bg-gradient-to-r from-indigo-600 to-purple-600 text-white">
                    <tr>
                        <th class="px-6 py-4 text-left">ID</th>
                        <th class="px-6 py-4 text-left">Usuário</th>
                        <th class="px-6 py-4 text-left">Produto</th>
                        <th class="px-6 py-4 text-left">Investido</th>
                        <th class="px-6 py-4 text-left">Retorno Total</th>
                        <th class="px-6 py-4 text-left">Já Recebido</th>
                        <th class="px-6 py-4 text-left">Status</th>
                        <th class="px-6 py-4 text-left">Data</th>
                        <th class="px-6 py-4 text-center">Ações</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($investments as $inv): ?>
                    <tr class="border-t hover:bg-gray-50">
                        <td class="px-6 py-4">#<?= $inv['id'] ?></td>
                        <td class="px-6 py-4">
                            <div>
                                <div class="font-semibold"><?= htmlspecialchars($inv['user_name']) ?></div>
                                <div class="text-sm text-gray-500"><?= htmlspecialchars($inv['user_phone']) ?></div>
                            </div>
                        </td>
                        <td class="px-6 py-4"><?= htmlspecialchars($inv['name']) ?></td>
                        <td class="px-6 py-4 font-semibold">R$ <?= number_format($inv['invested_amount'], 2, ',', '.') ?></td>
                        <td class="px-6 py-4 text-green-600 font-semibold">R$ <?= number_format($inv['total_return'], 2, ',', '.') ?></td>
                        <td class="px-6 py-4">R$ <?= number_format($inv['total_paid'], 2, ',', '.') ?></td>
                        <td class="px-6 py-4">
                            <span class="px-2 py-1 rounded text-xs <?= $inv['is_active'] ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800' ?>">
                                <?= $inv['is_active'] ? 'Ativo' : 'Inativo' ?>
                            </span>
                        </td>
                        <td class="px-6 py-4 text-sm text-gray-500"><?= date('d/m/Y H:i', strtotime($inv['created_at'])) ?></td>
                        <td class="px-6 py-4">
                            <div class="flex gap-2 justify-center">
                                <button onclick="deleteInvestment(<?= $inv['id'] ?>)" class="px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 transition text-sm">
                                    <i data-lucide="trash-2"></i>
                                </button>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        
        <!-- Paginação -->
        <?php if ($totalPages > 1): ?>
        <div class="px-6 py-4 border-t flex justify-center gap-2">
            <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                <a href="?page=investments&p=<?= $i ?>&search=<?= urlencode($search) ?><?= $userId ? '&user_id=' . $userId : '' ?>" class="px-4 py-2 <?= $i === $page ? 'bg-indigo-600 text-white' : 'bg-gray-100 text-gray-700 hover:bg-gray-200' ?> rounded-lg transition">
                <?= $i ?>
            </a>
            <?php endfor; ?>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- Modal Adicionar Investimento -->
<div id="addInvestmentModal" class="fixed inset-0 bg-black/50 hidden items-center justify-center z-50">
    <div class="bg-white rounded-xl p-6 max-w-md w-full mx-4">
        <h3 class="text-2xl font-bold mb-4">Adicionar Investimento</h3>
        <form method="POST" action="admin.php">
            <input type="hidden" name="action" value="add_investment">
            <div class="space-y-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Usuário (ID)</label>
                    <input type="number" name="user_id" id="add_investment_user_id" required placeholder="Digite o ID do usuário..." class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500">
                    <p class="text-xs text-gray-500 mt-1">Digite o ID numérico do usuário</p>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Produto</label>
                    <select name="product_id" id="add_investment_product_id" required class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500">
                        <option value="">Selecione um produto</option>
                        <?php foreach ($products as $product): ?>
                            <option value="<?= $product['id'] ?>" data-return="<?= $product['total_return'] ?>" data-days="<?= $product['total_days'] ?>" data-type="<?= $product['type'] ?>" data-name="<?= htmlspecialchars($product['name']) ?>" data-img="<?= htmlspecialchars($product['img']) ?>">
                                <?= htmlspecialchars($product['name']) ?> - R$ <?= number_format($product['value'], 2, ',', '.') ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Valor Investido (R$)</label>
                    <input type="number" step="0.01" name="invested_amount" id="add_investment_amount" required class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500">
                </div>
            </div>
            <div class="flex gap-3 mt-6">
                <button type="submit" class="flex-1 px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition">
                    Adicionar
                </button>
                <button type="button" onclick="closeModal('addInvestmentModal')" class="flex-1 px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition">
                    Cancelar
                </button>
            </div>
        </form>
    </div>
</div>

<script>
function openAddInvestmentModal() {
    document.getElementById('addInvestmentModal').classList.remove('hidden');
    document.getElementById('addInvestmentModal').classList.add('flex');
    lucide.createIcons();
}

function deleteInvestment(id) {
    if (confirm('Tem certeza que deseja excluir este investimento? O valor será reembolsado ao usuário.')) {
        const form = document.createElement('form');
        form.method = 'POST';
        form.action = 'admin.php';
        form.innerHTML = `
            <input type="hidden" name="action" value="delete_investment">
            <input type="hidden" name="investment_id" value="${id}">
        `;
        document.body.appendChild(form);
        form.submit();
    }
}


function closeModal(modalId) {
    document.getElementById(modalId).classList.add('hidden');
    document.getElementById(modalId).classList.remove('flex');
}

lucide.createIcons();
</script>
