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

$where = '';
$params = [];
if ($search) {
    $where = "WHERE u.name LIKE :search OR u.phone LIKE :search OR CAST(u.id AS CHAR) LIKE :search";
    $params[':search'] = "%$search%";
}

$stmt = $pdo->prepare("SELECT COUNT(*) FROM users u $where");
foreach ($params as $key => $value) {
    $stmt->bindValue($key, $value);
}
$stmt->execute();
$totalUsers = $stmt->fetchColumn();
$totalPages = ceil($totalUsers / $limit);

$stmt = $pdo->prepare("SELECT u.*, 
    (SELECT COUNT(*) FROM investments WHERE user_id = u.id) as total_investments,
    (SELECT SUM(invested_amount) FROM investments WHERE user_id = u.id AND is_active = 1) as total_invested
    FROM users u $where ORDER BY u.id 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();
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<div class="space-y-6">
    <!-- Header com Busca -->
    <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 Usuários</h3>
            <form method="GET" class="flex gap-2 w-full md:w-auto">
                <input type="hidden" name="page" value="users">
                <input type="text" name="search" value="<?= htmlspecialchars($search) ?>" placeholder="Buscar por nome, telefone ou ID..." class="px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent flex-1 md:w-64">
                <button type="submit" class="px-6 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition">
                    <i data-lucide="search"></i>
                </button>
            </form>
        </div>
    </div>

    <!-- Tabela de Usuários -->
    <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">Nome</th>
                        <th class="px-6 py-4 text-left">Telefone</th>
                        <th class="px-6 py-4 text-left">Saldo</th>
                        <th class="px-6 py-4 text-left">Investimentos</th>
                        <th class="px-6 py-4 text-left">Total Investido</th>
                        <th class="px-6 py-4 text-center">Ações</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($users as $user): ?>
                    <tr class="border-t hover:bg-gray-50">
                        <td class="px-6 py-4">#<?= $user['id'] ?></td>
                        <td class="px-6 py-4 font-semibold"><?= htmlspecialchars($user['name']) ?></td>
                        <td class="px-6 py-4"><?= htmlspecialchars($user['phone']) ?></td>
                        <td class="px-6 py-4">
                            <span class="font-semibold text-green-600">R$ <?= number_format($user['balance'], 2, ',', '.') ?></span>
                        </td>
                        <td class="px-6 py-4"><?= $user['total_investments'] ?? 0 ?></td>
                        <td class="px-6 py-4">R$ <?= number_format($user['total_invested'] ?? 0, 2, ',', '.') ?></td>
                        <td class="px-6 py-4">
                            <div class="flex gap-2 justify-center">
                                <button onclick="editUser(<?= $user['id'] ?>, '<?= htmlspecialchars($user['name']) ?>', '<?= htmlspecialchars($user['phone']) ?>', <?= $user['balance'] ?>)" class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition text-sm">
                                    <i data-lucide="edit"></i>
                                </button>
                                <button onclick="viewInvestments(<?= $user['id'] ?>)" class="px-4 py-2 bg-purple-500 text-white rounded-lg hover:bg-purple-600 transition text-sm">
                                    <i data-lucide="trending-up"></i>
                                </button>
                                <button onclick="deleteUser(<?= $user['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=users&p=<?= $i ?>&search=<?= urlencode($search) ?>" 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 Editar Usuário -->
<div id="editUserModal" 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">Editar Usuário</h3>
        <form method="POST" action="admin.php">
            <input type="hidden" name="action" value="update_balance">
            <input type="hidden" name="user_id" id="edit_user_id">
            <div class="space-y-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Nome</label>
                    <input type="text" id="edit_user_name" readonly class="w-full px-4 py-2 border border-gray-300 rounded-lg bg-gray-50">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Telefone</label>
                    <input type="text" id="edit_user_phone" readonly class="w-full px-4 py-2 border border-gray-300 rounded-lg bg-gray-50">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Saldo (R$)</label>
                    <input type="number" step="0.01" name="balance" id="edit_user_balance" 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">
                    Salvar
                </button>
                <button type="button" onclick="closeModal('editUserModal')" 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 editUser(id, name, phone, balance) {
    document.getElementById('edit_user_id').value = id;
    document.getElementById('edit_user_name').value = name;
    document.getElementById('edit_user_phone').value = phone;
    document.getElementById('edit_user_balance').value = balance;
    document.getElementById('editUserModal').classList.remove('hidden');
    document.getElementById('editUserModal').classList.add('flex');
    lucide.createIcons();
}

function viewInvestments(userId) {
    window.location.href = '?page=investments&user_id=' + userId;
}

function deleteUser(id) {
    if (confirm('Tem certeza que deseja excluir este usuário? Todos os investimentos serão excluídos também.')) {
        const form = document.createElement('form');
        form.method = 'POST';
        form.action = 'admin.php';
        form.innerHTML = `
            <input type="hidden" name="action" value="delete_user">
            <input type="hidden" name="user_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>
