<?php
require_once '../config/db.php';
require_once 'layout.php';

header('Content-Type: text/html; charset=utf-8');

// Fetch Packages
try {
    $packages = $pdo->query("SELECT * FROM diamond_packages ORDER BY price ASC")->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    die("Error DB: " . $e->getMessage());
}

renderAdminSidebar('economy');
?>

<!-- Header -->
<div class="flex justify-between items-center mb-8">
    <div>
        <h2 class="text-3xl font-bold text-white tracking-tight">Economía & Paquetes</h2>
        <p class="text-gray-400 mt-1">Gestiona los precios y ofertas de diamantes.</p>
    </div>
    <div class="flex gap-4">
        <a href="economy_settings.php" class="bg-dark-700 hover:bg-dark-600 text-white font-bold py-2 px-6 rounded-xl flex items-center gap-2 transition hover:scale-105 transform duration-200">
            <i class="fas fa-cog"></i> Configurar Precios Globales
        </a>
        <button onclick="openPackageModal()" class="bg-brand-600 hover:bg-brand-700 text-white font-bold py-2 px-6 rounded-xl flex items-center gap-2 shadow-lg shadow-brand-500/20 transition hover:scale-105 transform duration-200">
            <i class="fas fa-plus"></i> Nuevo Paquete
        </button>
    </div>
</div>

<!-- Packages Grid -->
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
    <?php foreach ($packages as $pkg): 
        $tagColor = match($pkg['tag']) {
            'popular' => 'bg-orange-500',
            'best_value' => 'bg-purple-500',
            default => 'hidden'
        };
        $tagLabel = match($pkg['tag']) {
            'popular' => 'Más Popular',
            'best_value' => 'Mejor Valor',
            default => ''
        };
        $pkgJson = htmlspecialchars(json_encode($pkg), ENT_QUOTES, 'UTF-8');
    ?>
    <div class="bg-dark-800 rounded-2xl border border-dark-700 p-6 relative overflow-hidden group hover:border-brand-500/50 transition duration-300">
        <!-- Tag -->
        <div class="absolute top-0 right-0">
            <div class="<?php echo $tagColor; ?> text-white text-[10px] font-bold px-3 py-1 rounded-bl-xl uppercase tracking-wider shadow-lg">
                <?php echo $tagLabel; ?>
            </div>
        </div>

        <div class="text-center mt-4">
            <div class="w-20 h-20 mx-auto bg-brand-500/10 rounded-2xl flex items-center justify-center mb-4 group-hover:scale-110 transition duration-300">
                <i class="fas fa-gem text-4xl text-brand-500 drop-shadow-[0_0_15px_rgba(139,92,246,0.5)]"></i>
            </div>
            
            <h3 class="text-2xl font-black text-white"><?php echo number_format($pkg['diamonds']); ?></h3>
            <p class="text-brand-400 text-sm font-bold uppercase tracking-wide">Diamantes</p>

            <?php if ($pkg['bonus'] > 0): ?>
                <div class="mt-2 inline-block px-3 py-1 bg-green-500/20 text-green-400 rounded-full text-xs font-bold border border-green-500/20">
                    +<?php echo number_format($pkg['bonus']); ?> Bonus
                </div>
            <?php else: ?>
                <div class="h-6 mt-2"></div> <!-- Spacer -->
            <?php endif; ?>
        </div>

        <div class="mt-6 pt-6 border-t border-dark-700 flex justify-between items-center relative z-10">
            <p class="text-2xl font-bold text-white">$<?php echo number_format($pkg['price'], 2); ?></p>
            <div class="flex gap-2">
                <button onclick='openPackageModal(<?php echo $pkgJson; ?>)' class="w-10 h-10 rounded-xl bg-dark-700 hover:bg-white hover:text-dark-900 text-gray-400 flex items-center justify-center transition duration-200">
                    <i class="fas fa-edit"></i>
                </button>
                <button onclick='deletePackage(<?php echo $pkg["id"]; ?>)' class="w-10 h-10 rounded-xl bg-dark-700 hover:bg-red-500 hover:text-white text-gray-400 flex items-center justify-center transition duration-200">
                    <i class="fas fa-trash"></i>
                </button>
            </div>
        </div>
        
        <!-- Background Glow -->
        <div class="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-32 h-32 bg-brand-500/20 blur-[50px] rounded-full pointer-events-none group-hover:bg-brand-500/30 transition duration-500"></div>
    </div>
    <?php endforeach; ?>
    
    <!-- Empty State -->
    <?php if (empty($packages)): ?>
        <div class="col-span-full py-12 text-center rounded-2xl border-2 border-dashed border-dark-700 bg-dark-800/50">
            <i class="fas fa-cubes text-4xl text-dark-700 mb-4"></i>
            <p class="text-gray-500 font-medium">No hay paquetes creados aún.</p>
        </div>
    <?php endif; ?>
</div>

<!-- Package Modal -->
<div id="packageModal" class="fixed inset-0 z-50 hidden">
    <div class="absolute inset-0 bg-black/90 backdrop-blur-sm" onclick="closeModal()"></div>
    <div class="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 w-full max-w-md bg-dark-800 rounded-2xl border border-dark-700 shadow-2xl overflow-hidden scale-100 transition-all duration-300">
        <div class="p-6 border-b border-dark-700 bg-dark-900/50 flex justify-between items-center">
            <h3 class="text-xl font-bold text-white" id="modalTitle">Nuevo Paquete</h3>
            <button onclick="closeModal()" class="text-gray-400 hover:text-white"><i class="fas fa-times"></i></button>
        </div>
        
        <form id="packageForm" onsubmit="savePackage(event)" class="p-6 space-y-4">
            <input type="hidden" id="pkgId">
            
            <div>
                <label class="block text-sm font-medium text-gray-400 mb-1">Nombre (Opcional)</label>
                <input type="text" id="pkgName" placeholder="Ej: Starter Pack" class="w-full bg-dark-900 border border-dark-700 rounded-xl px-4 py-3 text-white focus:border-brand-500 focus:outline-none focus:ring-1 focus:ring-brand-500 transition">
            </div>

            <div class="grid grid-cols-2 gap-4">
                <div>
                     <label class="block text-sm font-medium text-gray-400 mb-1">Diamantes</label>
                    <input type="number" id="pkgDiamonds" required class="w-full bg-dark-900 border border-dark-700 rounded-xl px-4 py-3 text-white focus:border-brand-500 focus:outline-none">
                </div>
                <div>
                     <label class="block text-sm font-medium text-gray-400 mb-1">Bonus</label>
                    <input type="number" id="pkgBonus" value="0" class="w-full bg-dark-900 border border-dark-700 rounded-xl px-4 py-3 text-white focus:border-brand-500 focus:outline-none">
                </div>
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-400 mb-1">Precio ($ USD)</label>
                <div class="relative">
                    <span class="absolute left-4 top-3 text-gray-500">$</span>
                    <input type="number" step="0.01" id="pkgPrice" required class="w-full bg-dark-900 border border-dark-700 rounded-xl pl-8 pr-4 py-3 text-white focus:border-brand-500 focus:outline-none">
                </div>
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-400 mb-1">Etiqueta Promocional</label>
                <select id="pkgTag" class="w-full bg-dark-900 border border-dark-700 rounded-xl px-4 py-3 text-white focus:border-brand-500 focus:outline-none">
                    <option value="none">Sin etiqueta</option>
                    <option value="popular">🔥 Más Popular</option>
                    <option value="best_value">⭐ Mejor Valor</option>
                </select>
            </div>

            <div class="pt-4">
                <button type="submit" class="w-full py-3 rounded-xl bg-brand-600 text-white font-bold hover:bg-brand-700 shadow-lg shadow-brand-500/20 transition flex items-center justify-center gap-2">
                    <i class="fas fa-save"></i> Guardar Paquete
                </button>
            </div>
        </form>
    </div>
</div>

<script>
const modal = document.getElementById('packageModal');

function closeModal() {
    modal.classList.add('hidden');
}

function openPackageModal(pkg = null) {
    modal.classList.remove('hidden');
    if (pkg) {
        document.getElementById('modalTitle').innerText = 'Editar Paquete';
        document.getElementById('pkgId').value = pkg.id;
        document.getElementById('pkgName').value = pkg.name;
        document.getElementById('pkgDiamonds').value = pkg.diamonds;
        document.getElementById('pkgBonus').value = pkg.bonus;
        document.getElementById('pkgPrice').value = pkg.price;
        document.getElementById('pkgTag').value = pkg.tag;
    } else {
        document.getElementById('modalTitle').innerText = 'Nuevo Paquete';
        document.getElementById('packageForm').reset();
        document.getElementById('pkgId').value = '';
    }
}

async function savePackage(e) {
    e.preventDefault();
    
    const data = {
        id: document.getElementById('pkgId').value,
        name: document.getElementById('pkgName').value,
        diamonds: document.getElementById('pkgDiamonds').value,
        bonus: document.getElementById('pkgBonus').value,
        price: document.getElementById('pkgPrice').value,
        tag: document.getElementById('pkgTag').value
    };

    try {
        const res = await fetch('../api/admin/packages/save.php', {
            method: 'POST',
            body: JSON.stringify(data)
        });
        const resp = await res.json();
        
        if (resp.success) {
            location.reload();
        } else {
            alert('Error: ' + resp.message);
        }
    } catch (err) {
        alert('Error de red');
    }
}

async function deletePackage(id) {
    if (!confirm('¿Estás seguro de eliminar este paquete?')) return;
    
    try {
        const res = await fetch('../api/admin/packages/delete.php', {
            method: 'POST',
            body: JSON.stringify({ id })
        });
        const resp = await res.json();
        
        if (resp.success) {
            location.reload();
        } else {
            alert('Error: ' + resp.message);
        }
    } catch (err) {
        alert('Error de red');
    }
}
</script>

<?php renderAdminFooter(); ?>
