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

$stmt = $pdo->prepare("SELECT * FROM investment_products $where ORDER BY id DESC");
foreach ($params as $key => $value) {
    $stmt->bindValue($key, $value);
}
$stmt->execute();
$products = $stmt->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 Produtos</h3>
            <div class="flex gap-3">
                <form method="GET" class="flex gap-2">
                    <input type="hidden" name="page" value="products">
                    <input type="text" name="search" value="<?= htmlspecialchars($search) ?>" placeholder="Buscar produtos..." 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="openAddProductModal()" class="px-6 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition">
                    <i data-lucide="plus"></i> Novo Produto
                </button>
            </div>
        </div>
    </div>

    <!-- Grid de Produtos -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        <?php foreach ($products as $product): ?>
        <div class="bg-white rounded-xl shadow-lg overflow-hidden hover:shadow-xl transition">
            <div class="h-48 bg-gradient-to-br from-indigo-500 to-purple-600 flex items-center justify-center">
                <?php if ($product['img']): ?>
                    <img src="<?= htmlspecialchars($product['img']) ?>" alt="<?= htmlspecialchars($product['name']) ?>" class="w-full h-full object-cover">
                <?php else: ?>
                    <i data-lucide="package" class="w-16 h-16 text-white"></i>
                <?php endif; ?>
            </div>
            <div class="p-6">
                <h4 class="text-xl font-bold text-gray-800 mb-2"><?= htmlspecialchars($product['name']) ?></h4>
                <p class="text-gray-600 text-sm mb-4 line-clamp-2"><?= htmlspecialchars($product['description'] ?? '') ?></p>
                <div class="space-y-2 mb-4">
                    <div class="flex justify-between text-sm">
                        <span class="text-gray-600">Valor:</span>
                        <span class="font-semibold">R$ <?= number_format($product['value'], 2, ',', '.') ?></span>
                    </div>
                    <div class="flex justify-between text-sm">
                        <span class="text-gray-600">Retorno Total:</span>
                        <span class="font-semibold text-green-600"><?= number_format($product['total_return'], 2, ',', '.') ?>%</span>
                    </div>
                    <div class="flex justify-between text-sm">
                        <span class="text-gray-600">Duração:</span>
                        <span class="font-semibold"><?= $product['total_days'] ?> dias</span>
                    </div>
                    <div class="flex justify-between text-sm">
                        <span class="text-gray-600">Status:</span>
                        <span class="px-2 py-1 rounded text-xs <?= $product['is_active'] ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800' ?>">
                            <?= $product['is_active'] ? 'Ativo' : 'Inativo' ?>
                        </span>
                    </div>
                </div>
                <div class="flex gap-2">
                    <button onclick="editProduct(<?= htmlspecialchars(json_encode($product)) ?>)" class="flex-1 px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition text-sm">
                        <i data-lucide="edit"></i> Editar
                    </button>
                    <button onclick="deleteProduct(<?= $product['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>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
</div>

<!-- Modal Adicionar/Editar Produto -->
<div id="productModal" class="fixed inset-0 bg-black/50 hidden items-center justify-center z-50">
    <div class="bg-white rounded-xl p-6 max-w-2xl w-full mx-4 max-h-[90vh] overflow-y-auto">
        <h3 class="text-2xl font-bold mb-4" id="productModalTitle">Novo Produto</h3>
        <form method="POST" action="../../app/Controllers/addProducts.php" enctype="multipart/form-data">
            <input type="hidden" name="product_id" id="product_id">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Nome</label>
                    <input type="text" name="name" id="product_name" 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">Valor (R$)</label>
                    <input type="number" step="0.01" name="value" id="product_value" 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">Retorno Diário (%)</label>
                    <input type="number" step="0.01" name="daily_return" id="product_daily_return" 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">Retorno Total (%)</label>
                    <input type="number" step="0.01" name="total_return" id="product_total_return" 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">Duração (dias)</label>
                    <input type="number" name="total_days" id="product_total_days" 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" id="product_type" required class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500">
                        <option value="diary">Diário</option>
                        <option value="cicle">Ciclo</option>
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Limite de Compra</label>
                    <input type="number" name="limit_purchase" id="product_limit_purchase" value="1" 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">Disponibilidade</label>
                    <input type="number" name="available" id="product_available" value="1000" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500">
                </div>
                <div class="md:col-span-2">
                    <label class="block text-sm font-medium text-gray-700 mb-2">Descrição</label>
                    <textarea name="description" id="product_description" rows="3" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500"></textarea>
                </div>
                <div class="md:col-span-2">
                    <label class="block text-sm font-medium text-gray-700 mb-2">Imagem</label>
                    <input type="file" name="img" accept="image/*" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500">
                </div>
                <div class="md:col-span-2">
                    <label class="flex items-center gap-2">
                        <input type="checkbox" name="is_active" id="product_is_active" value="1" checked class="w-4 h-4">
                        <span class="text-sm text-gray-700">Produto Ativo</span>
                    </label>
                </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('productModal')" 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 openAddProductModal() {
    document.getElementById('productModalTitle').textContent = 'Novo Produto';
    document.getElementById('product_id').value = '';
    document.getElementById('product_name').value = '';
    document.getElementById('product_value').value = '';
    document.getElementById('product_daily_return').value = '';
    document.getElementById('product_total_return').value = '';
    document.getElementById('product_total_days').value = '';
    document.getElementById('product_type').value = 'diary';
    document.getElementById('product_limit_purchase').value = '1';
    document.getElementById('product_available').value = '1000';
    document.getElementById('product_description').value = '';
    document.getElementById('product_is_active').checked = true;
    document.getElementById('productModal').classList.remove('hidden');
    document.getElementById('productModal').classList.add('flex');
    lucide.createIcons();
}

function editProduct(product) {
    document.getElementById('productModalTitle').textContent = 'Editar Produto';
    document.getElementById('product_id').value = product.id;
    document.getElementById('product_name').value = product.name;
    document.getElementById('product_value').value = product.value;
    document.getElementById('product_daily_return').value = product.daily_return;
    document.getElementById('product_total_return').value = product.total_return;
    document.getElementById('product_total_days').value = product.total_days;
    document.getElementById('product_type').value = product.type;
    document.getElementById('product_limit_purchase').value = product.limit_purchase;
    document.getElementById('product_available').value = product.available;
    document.getElementById('product_description').value = product.description || '';
    document.getElementById('product_is_active').checked = product.is_active == 1;
    document.getElementById('productModal').classList.remove('hidden');
    document.getElementById('productModal').classList.add('flex');
    lucide.createIcons();
}

function deleteProduct(id) {
    if (confirm('Tem certeza que deseja excluir este produto?')) {
        const form = document.createElement('form');
        form.method = 'POST';
        form.action = 'admin.php';
        form.innerHTML = `
            <input type="hidden" name="action" value="delete_product">
            <input type="hidden" name="product_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>
