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

$where = "WHERE w.status = :status";
$params = [':status' => $status];

if ($search) {
    $where .= " AND (u.name LIKE :search OR u.phone LIKE :search OR w.reference_id LIKE :search)";
    $params[':search'] = "%$search%";
}

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

$stmt = $pdo->prepare("SELECT w.*, u.name as user_name, u.phone as user_phone FROM withdrawal w JOIN users u ON w.user_id = u.id $where ORDER BY w.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();
$withdrawals = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Estatísticas
$totalPending = $pdo->query("SELECT COUNT(*) FROM withdrawal WHERE status = 'pending'")->fetchColumn();
$totalApproved = $pdo->query("SELECT COUNT(*) FROM withdrawal WHERE status = 'approved'")->fetchColumn();
$totalRecused = $pdo->query("SELECT COUNT(*) FROM withdrawal WHERE status = 'recused'")->fetchColumn();
?>
<div class="space-y-6">
    <!-- Estatísticas -->
    <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
        <div class="bg-gradient-to-br from-orange-500 to-orange-600 rounded-xl p-6 text-white shadow-lg">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-orange-100 text-sm">Pendentes</p>
                    <p class="text-3xl font-bold mt-2"><?= $totalPending ?></p>
                </div>
                <i data-lucide="clock" class="w-12 h-12 text-orange-200"></i>
            </div>
        </div>
        <div class="bg-gradient-to-br from-green-500 to-green-600 rounded-xl p-6 text-white shadow-lg">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-green-100 text-sm">Aprovados</p>
                    <p class="text-3xl font-bold mt-2"><?= $totalApproved ?></p>
                </div>
                <i data-lucide="check-circle" class="w-12 h-12 text-green-200"></i>
            </div>
        </div>
        <div class="bg-gradient-to-br from-red-500 to-red-600 rounded-xl p-6 text-white shadow-lg">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-red-100 text-sm">Recusados</p>
                    <p class="text-3xl font-bold mt-2"><?= $totalRecused ?></p>
                </div>
                <i data-lucide="x-circle" class="w-12 h-12 text-red-200"></i>
            </div>
        </div>
    </div>

    <!-- Filtros -->
    <div class="bg-white rounded-xl shadow-lg p-6">
        <div class="flex flex-col md:flex-row gap-4 items-center justify-between">
            <div class="flex gap-2">
                <a href="?page=withdrawals&status=pending" class="px-4 py-2 rounded-lg transition <?= $status === 'pending' ? 'bg-orange-500 text-white' : 'bg-gray-100 text-gray-700 hover:bg-gray-200' ?>">
                    Pendentes
                </a>
                <a href="?page=withdrawals&status=approved" class="px-4 py-2 rounded-lg transition <?= $status === 'approved' ? 'bg-green-500 text-white' : 'bg-gray-100 text-gray-700 hover:bg-gray-200' ?>">
                    Aprovados
                </a>
                <a href="?page=withdrawals&status=recused" class="px-4 py-2 rounded-lg transition <?= $status === 'recused' ? 'bg-red-500 text-white' : 'bg-gray-100 text-gray-700 hover:bg-gray-200' ?>">
                    Recusados
                </a>
            </div>
            <form method="GET" class="flex gap-2">
                <input type="hidden" name="page" value="withdrawals">
                <input type="hidden" name="status" value="<?= htmlspecialchars($status) ?>">
                <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>
        </div>
    </div>

    <!-- Tabela de Saques -->
    <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">Valor</th>
                        <th class="px-6 py-4 text-left">Taxa</th>
                        <th class="px-6 py-4 text-left">Líquido</th>
                        <th class="px-6 py-4 text-left">Chave PIX</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 ($withdrawals as $with): ?>
                    <tr class="border-t hover:bg-gray-50">
                        <td class="px-6 py-4">#<?= $with['id'] ?></td>
                        <td class="px-6 py-4">
                            <div>
                                <div class="font-semibold"><?= htmlspecialchars($with['user_name']) ?></div>
                                <div class="text-sm text-gray-500"><?= htmlspecialchars($with['user_phone']) ?></div>
                            </div>
                        </td>
                        <td class="px-6 py-4 font-semibold">R$ <?= number_format($with['value'], 2, ',', '.') ?></td>
                        <td class="px-6 py-4 text-red-600">R$ <?= number_format($with['value_taxa'], 2, ',', '.') ?></td>
                        <td class="px-6 py-4 text-green-600 font-semibold">R$ <?= number_format($with['with_liquid'], 2, ',', '.') ?></td>
                        <td class="px-6 py-4 text-sm">
                            <div class="max-w-xs truncate"><?= htmlspecialchars($with['key_beneficiary']) ?></div>
                            <div class="text-xs text-gray-500"><?= htmlspecialchars($with['type_pix']) ?></div>
                        </td>
                        <td class="px-6 py-4">
                            <?php
                            $statusColors = [
                                'pending' => 'bg-orange-100 text-orange-800',
                                'approved' => 'bg-green-100 text-green-800',
                                'recused' => 'bg-red-100 text-red-800'
                            ];
                            $statusTexts = [
                                'pending' => 'Pendente',
                                'approved' => 'Aprovado',
                                'recused' => 'Recusado'
                            ];
                            ?>
                            <span class="px-2 py-1 rounded text-xs <?= $statusColors[$with['status']] ?? 'bg-gray-100 text-gray-800' ?>">
                                <?= $statusTexts[$with['status']] ?? $with['status'] ?>
                            </span>
                        </td>
                        <td class="px-6 py-4 text-sm text-gray-500"><?= date('d/m/Y H:i', strtotime($with['created_at'])) ?></td>
                        <td class="px-6 py-4">
                            <div class="flex gap-2 justify-center">
                                <?php if ($with['status'] === 'pending'): ?>
                                    <form method="POST" action="with.php" class="inline">
                                        <input type="hidden" name="id_with" value="<?= $with['id'] ?>">
                                        <button type="submit" name="payment_pix" class="px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600 transition text-sm">
                                            <i data-lucide="check"></i> Aprovar
                                        </button>
                                    </form>
                                    <button onclick="recuseWithdrawal(<?= $with['id'] ?>)" class="px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 transition text-sm">
                                        <i data-lucide="x"></i> Recusar
                                    </button>
                                <?php endif; ?>
                            </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=withdrawals&status=<?= urlencode($status) ?>&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>

<script>
function recuseWithdrawal(id) {
    if (confirm('Tem certeza que deseja recusar este saque?')) {
        const form = document.createElement('form');
        form.method = 'POST';
        form.action = 'admin.php';
        form.innerHTML = `
            <input type="hidden" name="action" value="recuse_withdrawal">
            <input type="hidden" name="withdrawal_id" value="${id}">
        `;
        document.body.appendChild(form);
        form.submit();
    }
}

lucide.createIcons();
</script>
