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

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

renderAdminSidebar('economy');
?>

<!-- Header -->
<div class="flex justify-between items-center mb-8">
    <div>
        <h2 class="text-3xl font-bold text-white tracking-tight">Configuración Global</h2>
        <p class="text-gray-400 mt-1">Ajusta los valores generales de la economía del sitio.</p>
    </div>
     <a href="economy.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-arrow-left"></i> Volver a Paquetes
    </a>
</div>

<!-- Settings Form -->
<div class="max-w-2xl mx-auto bg-dark-800 rounded-2xl border border-dark-700 p-8 shadow-xl">
    <form id="settingsForm" onsubmit="saveSettings(event)" class="space-y-6">
        
        <!-- Exchange Rate -->
        <div class="p-4 bg-brand-500/10 rounded-xl border border-brand-500/20">
            <h3 class="text-lg font-bold text-white mb-4 flex items-center gap-2">
                <i class="fas fa-coins text-brand-400"></i> Tasa de Cambio
            </h3>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                     <label class="block text-sm font-medium text-gray-400 mb-1">Valor de 1 Diamante (USD)</label>
                    <div class="relative">
                        <span class="absolute left-4 top-3 text-gray-500">$</span>
                        <input type="number" step="0.0001" id="diamond_exchange_rate" placeholder="0.01" 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>
                    <p class="text-xs text-gray-500 mt-1">Ej: 0.01 significa 100 diamantes = $1.00 USD</p>
                </div>
            </div>
        </div>

        <!-- Withdrawals -->
        <div class="p-4 bg-dark-900/50 rounded-xl border border-dark-700">
             <h3 class="text-lg font-bold text-white mb-4 flex items-center gap-2">
                <i class="fas fa-university text-gray-400"></i> Retiros
            </h3>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                     <label class="block text-sm font-medium text-gray-400 mb-1">Mínimo de Diamantes para Retiro</label>
                    <input type="number" id="min_withdrawal_diamonds" placeholder="100" 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">Comisión por Retiro (%)</label>
                    <input type="number" step="0.1" id="withdrawal_fee_percent" placeholder="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>

        <!-- Contenido Premium & Suscripciones -->
        <div class="p-4 bg-purple-500/10 rounded-xl border border-purple-500/20">
             <h3 class="text-lg font-bold text-white mb-4 flex items-center gap-2">
                <i class="fas fa-lock text-purple-400"></i> Premium & Suscripciones
            </h3>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                     <label class="block text-sm font-medium text-gray-400 mb-1">Comisión por Desbloqueo Chat (%)</label>
                    <input type="number" step="0.1" id="chat_unlock_fee_percent" placeholder="20" 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">
                    <p class="text-xs text-gray-500 mt-1">Fee para mensajes de pago / media bloqueada.</p>
                </div>
                <div>
                     <label class="block text-sm font-medium text-gray-400 mb-1">Comisión por Suscripciones (%)</label>
                    <input type="number" step="0.1" id="subscription_fee_percent" placeholder="25" 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">
                    <p class="text-xs text-gray-500 mt-1">Fee para suscripciones mensuales a creadores.</p>
                </div>
                <div>
                     <label class="block text-sm font-medium text-gray-400 mb-1">Comisión por Ítems del Cofre (%)</label>
                    <input type="number" step="0.1" id="chest_item_fee_percent" placeholder="15" 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">
                    <p class="text-xs text-gray-500 mt-1">Fee para ítems obtenidos de cofres.</p>
                </div>
            </div>
        </div>

        <!-- Marketplace -->
        <div class="p-4 bg-orange-500/10 rounded-xl border border-orange-500/20">
             <h3 class="text-lg font-bold text-white mb-4 flex items-center gap-2">
                <i class="fas fa-store text-orange-400"></i> Marketplace
            </h3>
            <div class="space-y-6">
                <div>
                     <label class="block text-sm font-medium text-gray-400 mb-1">Comisión General por Venta (%)</label>
                    <input type="number" step="0.1" id="sales_fee_percent" placeholder="10" 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">
                    <p class="text-xs text-gray-500 mt-1">Porcentaje base que KLKAPP retiene si no hay una comisión por categoría específica.</p>
                </div>

                <div class="pt-4 border-t border-dark-700">
                    <label class="block text-sm font-medium text-gray-200 mb-3">Comisiones por Categoría (%)</label>
                    <div id="category_fees_container" class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <!-- Dynamic categories from JS -->
                    </div>
                </div>
            </div>
        </div>

        <div class="pt-4 border-t border-dark-700 flex justify-end">
            <button type="submit" class="bg-green-600 hover:bg-green-700 text-white font-bold py-3 px-8 rounded-xl shadow-lg shadow-green-500/20 transition hover:scale-105 transform duration-200 flex items-center gap-2">
                <i class="fas fa-save"></i> Guardar Cambios
            </button>
        </div>
    </form>
</div>

<script>
const categories = [
    "Personalizado", "Conferencias", "Digital Classrooms", "Work Meetings", 
    "Tutoriales", "PDF & Docs", "Llamadas", "Videollamadas", "Ventas", 
    "Shopping", "Store", "Consulta Online", "Talleres", "Música", 
    "Gaming", "Fitness", "Fotografía", "Arte", "Tecnología", "Viajes", "Cocina"
];

async function loadSettings() {
    const container = document.getElementById('category_fees_container');
    container.innerHTML = categories.map(cat => `
        <div class="bg-dark-900/50 p-3 rounded-xl border border-dark-700">
            <label class="block text-[10px] uppercase font-bold text-gray-500 mb-1">${cat}</label>
            <div class="relative">
                <input type="number" step="0.1" data-category="${cat}" placeholder="10" class="category-fee-input w-full bg-dark-800 border border-dark-700 rounded-lg px-3 py-2 text-white text-sm focus:border-brand-500 focus:outline-none">
                <span class="absolute right-3 top-2 text-gray-600 text-sm">%</span>
            </div>
        </div>
    `).join('');

    try {
        const res = await fetch('../api/admin/settings/get.php');
        const resp = await res.json();
        
        if (resp.success) {
            const data = resp.data;
            document.getElementById('diamond_exchange_rate').value = data.diamond_exchange_rate;
            document.getElementById('min_withdrawal_diamonds').value = data.min_withdrawal_diamonds;
            document.getElementById('withdrawal_fee_percent').value = data.withdrawal_fee_percent;
            document.getElementById('sales_fee_percent').value = data.sales_fee_percent || 0;
            document.getElementById('chat_unlock_fee_percent').value = data.chat_unlock_fee_percent || 0;
            document.getElementById('subscription_fee_percent').value = data.subscription_fee_percent || 0;
            document.getElementById('chest_item_fee_percent').value = data.chest_item_fee_percent || 0;

            if (data.marketplace_category_fees) {
                const catFees = JSON.parse(data.marketplace_category_fees);
                document.querySelectorAll('.category-fee-input').forEach(input => {
                    const cat = input.dataset.category;
                    if (catFees[cat] !== undefined) {
                        input.value = catFees[cat];
                    }
                });
            }
        }
    } catch (err) {
        console.error('Error loading settings', err);
    }
}

async function saveSettings(e) {
    e.preventDefault();
    
    const catFees = {};
    document.querySelectorAll('.category-fee-input').forEach(input => {
        if (input.value !== '') {
            catFees[input.dataset.category] = input.value;
        }
    });

    const data = {
        diamond_exchange_rate: document.getElementById('diamond_exchange_rate').value,
        min_withdrawal_diamonds: document.getElementById('min_withdrawal_diamonds').value,
        withdrawal_fee_percent: document.getElementById('withdrawal_fee_percent').value,
        sales_fee_percent: document.getElementById('sales_fee_percent').value,
        chat_unlock_fee_percent: document.getElementById('chat_unlock_fee_percent').value,
        subscription_fee_percent: document.getElementById('subscription_fee_percent').value,
        chest_item_fee_percent: document.getElementById('chest_item_fee_percent').value,
        marketplace_category_fees: JSON.stringify(catFees)
    };

    try {
        const res = await fetch('../api/admin/settings/save.php', {
            method: 'POST',
            body: JSON.stringify(data)
        });
        const resp = await res.json();
        
        if (resp.success) {
            alert('✅ Configuración guardada correctamente.');
        } else {
            alert('Error: ' + resp.message);
        }
    } catch (err) {
        alert('Error de red');
    }
}

// Load on start
loadSettings();
</script>

<?php renderAdminFooter(); ?>
