<?php
$search = $_GET['search'] ?? '';
$where = '';
$params = [];
if ($search) {
    $where = "WHERE code LIKE :search";
    $params[':search'] = "%$search%";
}

$stmt = $pdo->prepare("SELECT c.*, 
    (SELECT COUNT(*) FROM cupons_rescued WHERE cupom_id = c.id) as times_used,
    (SELECT COUNT(DISTINCT user_id) FROM cupons_rescued WHERE cupom_id = c.id) as unique_users
    FROM cupons c $where ORDER BY c.created_at DESC");
foreach ($params as $key => $value) {
    $stmt->bindValue($key, $value);
}
$stmt->execute();
$coupons = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Buscar usuários para o modal
$users = $pdo->query("SELECT id, name, phone FROM users ORDER BY name LIMIT 100")->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 Cupons</h3>
            <div class="flex gap-3">
                <form method="GET" class="flex gap-2">
                    <input type="hidden" name="page" value="coupons">
                    <input type="text" name="search" value="<?= htmlspecialchars($search) ?>" placeholder="Buscar cupons..." 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="openAddCouponModal()" class="px-6 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition">
                    <i data-lucide="plus"></i> Novo Cupom
                </button>
            </div>
        </div>
    </div>

    <!-- Tabela de Cupons -->
    <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">Código</th>
                        <th class="px-6 py-4 text-left">Valor</th>
                        <th class="px-6 py-4 text-left">Usuário Destinatário</th>
                        <th class="px-6 py-4 text-left">Usos</th>
                        <th class="px-6 py-4 text-left">Expira em</th>
                        <th class="px-6 py-4 text-left">Status</th>
                        <th class="px-6 py-4 text-left">Criado em</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($coupons as $coupon): ?>
                    <tr class="border-t hover:bg-gray-50">
                        <td class="px-6 py-4">#<?= $coupon['id'] ?></td>
                        <td class="px-6 py-4">
                            <div class="font-mono font-semibold"><?= htmlspecialchars($coupon['code']) ?></div>
                            <div class="text-xs text-gray-500">Link: index.php?code=<?= htmlspecialchars($coupon['code']) ?></div>
                        </td>
                        <td class="px-6 py-4 font-semibold text-green-600">R$ <?= number_format($coupon['value'], 2, ',', '.') ?></td>
                        <td class="px-6 py-4">
                            <?php if ($coupon['target_user_id']): ?>
                                <span class="text-sm">Usuário #<?= $coupon['target_user_id'] ?></span>
                            <?php else: ?>
                                <span class="text-sm text-gray-500">Todos os usuários</span>
                            <?php endif; ?>
                        </td>
                        <td class="px-6 py-4">
                            <div class="text-sm"><?= $coupon['times_used'] ?> vezes</div>
                            <div class="text-xs text-gray-500"><?= $coupon['unique_users'] ?> usuários únicos</div>
                        </td>
                        <td class="px-6 py-4 text-sm">
                            <?= $coupon['expire_at'] ? date('d/m/Y H:i', strtotime($coupon['expire_at'])) : 'Sem expiração' ?>
                        </td>
                        <td class="px-6 py-4">
                            <span class="px-2 py-1 rounded text-xs <?= $coupon['status'] === 'active' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800' ?>">
                                <?= $coupon['status'] === 'active' ? 'Ativo' : 'Inativo' ?>
                            </span>
                        </td>
                        <td class="px-6 py-4 text-sm text-gray-500"><?= date('d/m/Y H:i', strtotime($coupon['created_at'])) ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Modal Adicionar Cupom -->
<div id="addCouponModal" 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 max-h-[90vh] overflow-y-auto">
        <h3 class="text-2xl font-bold mb-4">Novo Cupom</h3>
        <form method="POST" action="../../app/Controllers/addCupom.php">
            <div class="space-y-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Código do Cupom</label>
                    <input type="text" name="code_cupom" required maxlength="50" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500" placeholder="Ex: PROMO2024">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Valor (R$)</label>
                    <input type="number" step="0.01" min="0" name="value" required class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500" placeholder="0.00">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Data de Expiração</label>
                    <input type="datetime-local" name="expire_at" required class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Usuário Destinatário</label>
                    <select name="user_id" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500">
                        <option value="">Todos os usuários</option>
                        <?php foreach ($users as $user): ?>
                            <option value="<?= $user['id'] ?>"><?= htmlspecialchars($user['name']) ?> (<?= htmlspecialchars($user['phone']) ?>)</option>
                        <?php endforeach; ?>
                    </select>
                    <p class="text-xs text-gray-500 mt-1">Deixe vazio para cupom público ou selecione um usuário específico</p>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Limite de Uso por Usuário</label>
                    <input type="number" min="1" name="limit_purchase_user" value="1" required class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Limite de Uso Geral</label>
                    <input type="number" min="1" name="limit_purchase_geral" value="100" required class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Tipo</label>
                    <select name="type" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500">
                        <option value="fixed">Fixo</option>
                        <option value="aleatory">Aleatório</option>
                    </select>
                </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">
                    Criar Cupom
                </button>
                <button type="button" onclick="closeModal('addCouponModal')" 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 openAddCouponModal() {
    document.getElementById('addCouponModal').classList.remove('hidden');
    document.getElementById('addCouponModal').classList.add('flex');
    lucide.createIcons();
}

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

lucide.createIcons();
</script>
