<?php
// Silencia avisos para manter o visual limpo
ini_set('display_errors', 0);
error_reporting(E_ALL & ~E_DEPRECATED & ~E_NOTICE);

include 'includes/header.php';

$configFile = 'add-lista/config.php';

// Carrega os servidores atuais
if (file_exists($configFile)) {
    include $configFile;
} else {
    $servidores = [];
}

// Lógica para Salvar / Adicionar / Apagar
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['save_dns'])) {
        $nomes = $_POST['dns_name'];
        $urls = $_POST['dns_url'];
        $newServidores = [];

        foreach ($nomes as $index => $nome) {
            if (!empty($nome) && !empty($urls[$index])) {
                $newServidores[$nome] = $urls[$index];
            }
        }

        // Gera o conteúdo do arquivo PHP
        $content = "<?php\n// add-lista/config.php\n\n\$servidores = [\n";
        foreach ($newServidores as $nome => $url) {
            $content .= "    \"$nome\" => \"$url\",\n";
        }
        $content .= "];\n?>";

        if (file_put_contents($configFile, $content)) {
            echo "<script>window.location.href='dns_manager.php?status=success';</script>";
        }
    }
}
?>

<style>
    #content-wrapper, #content, .container-fluid, main { background-color: #06070a !important; }
    
    .flux-card {
        background: #0f111a !important;
        border: 1px solid rgba(139, 92, 246, 0.05) !important;
        border-radius: 2rem !important;
    }

    .flux-input {
        background: rgba(255,255,255,0.03) !important;
        border: 1px solid rgba(139, 92, 246, 0.1) !important;
        border-radius: 12px !important;
        color: white !important;
        padding: 12px !important;
        font-size: 13px;
    }

    .label-thai {
        color: #8b5cf6;
        font-size: 10px;
        text-transform: uppercase;
        font-weight: 900;
        letter-spacing: 1.5px;
        margin-bottom: 5px;
        display: block;
    }

    .btn-remove {
        background: rgba(239, 68, 68, 0.1);
        color: #ef4444;
        border: 1px solid rgba(239, 68, 68, 0.2);
    }
    
    .btn-remove:hover { background: #ef4444; color: white; }

    /* Estilo do Alerta de Informação */
    .info-banner {
        background: rgba(139, 92, 246, 0.05);
        border: 1px dashed rgba(139, 92, 246, 0.3);
        border-radius: 1.5rem;
        padding: 20px;
        margin-bottom: 30px;
        display: flex;
        align-items: center;
        gap: 20px;
    }
</style>

<main class="py-8 px-4">
    <div class="max-w-5xl mx-auto">
        
        <div class="mb-8 flex flex-col md:flex-row items-center justify-between gap-4">
            <div>
                <h1 class="text-3xl font-black text-white tracking-tighter italic uppercase">Gerenciar DNS</h1>
                <p class="text-[9px] text-violet-500 font-bold uppercase tracking-[0.4em]">VU FLUX • CONFIGURAÇÃO DE SERVIDORES</p>
            </div>
            <button type="button" onclick="addDnsRow()" class="px-6 py-3 bg-violet-600 hover:bg-violet-700 text-white text-[10px] font-black rounded-full transition-all shadow-lg shadow-violet-900/20 uppercase">
                <i class="fas fa-plus mr-2"></i> Adicionar Nova DNS
            </button>
        </div>

        <div class="info-banner animate__animated animate__fadeIn">
            <div class="w-12 h-12 rounded-full bg-violet-600/20 flex items-center justify-center text-violet-500 shrink-0">
                <i class="fas fa-info-circle text-xl"></i>
            </div>
            <div>
                <h4 class="text-white text-xs font-black uppercase mb-1">Aviso Importante</h4>
                <p class="text-gray-400 text-[11px] leading-relaxed">
                    Esta ferramenta gerencia exclusivamente as DNS exibidas na <strong>área externa de adicionar usuário</strong>. 
                    As alterações feitas aqui afetarão a lista de seleção que seus clientes veem ao importar conteúdos via link M3U no portal público.
                </p>
            </div>
        </div>

        <form method="post" id="dns-form">
            <div class="flux-card p-6 md:p-8 shadow-2xl">
                <div id="dns-container" class="space-y-4">
                    <?php if (!empty($servidores)): ?>
                        <?php foreach ($servidores as $nome => $url): ?>
                            <div class="grid grid-cols-1 md:grid-cols-12 gap-4 items-end bg-white/[0.02] p-4 rounded-2xl border border-white/5 dns-row">
                                <div class="md:col-span-4">
                                    <label class="label-thai">Nome Exibido</label>
                                    <input type="text" name="dns_name[]" value="<?php echo $nome; ?>" class="w-full flux-input" placeholder="Ex: Servidor VIP" required>
                                </div>
                                <div class="md:col-span-7">
                                    <label class="label-thai">URL do Servidor (DNS)</label>
                                    <input type="text" name="dns_url[]" value="<?php echo $url; ?>" class="w-full flux-input font-mono" placeholder="http://exemplo.com:80" required>
                                </div>
                                <div class="md:col-span-1">
                                    <button type="button" onclick="removeRow(this)" class="w-full h-[46px] rounded-xl btn-remove transition-all flex items-center justify-center">
                                        <i class="fas fa-trash-alt"></i>
                                    </button>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <p id="empty-msg" class="text-center text-gray-600 py-8 italic">Nenhuma DNS cadastrada. Clique em adicionar.</p>
                    <?php endif; ?>
                </div>

                <div class="mt-8">
                    <button type="submit" name="save_dns" class="w-full py-4 bg-emerald-500 hover:bg-emerald-600 text-white rounded-2xl text-[11px] font-black shadow-xl shadow-emerald-900/20 flex items-center justify-center gap-3 transition-all uppercase tracking-widest">
                        <i class="fas fa-save text-lg"></i> Salvar Configurações
                    </button>
                </div>
            </div>
        </form>
    </div>
</main>

<script>
function addDnsRow() {
    const container = document.getElementById('dns-container');
    const emptyMsg = document.getElementById('empty-msg');
    if(emptyMsg) emptyMsg.remove();

    const div = document.createElement('div');
    div.className = "grid grid-cols-1 md:grid-cols-12 gap-4 items-end bg-white/[0.02] p-4 rounded-2xl border border-white/5 dns-row animate__animated animate__fadeInUp";
    div.innerHTML = `
        <div class="md:col-span-4">
            <label class="label-thai">Nome Exibido</label>
            <input type="text" name="dns_name[]" class="w-full flux-input" placeholder="Novo Servidor" required>
        </div>
        <div class="md:col-span-7">
            <label class="label-thai">URL do Servidor (DNS)</label>
            <input type="text" name="dns_url[]" class="w-full flux-input font-mono" placeholder="http://url-do-servidor.com" required>
        </div>
        <div class="md:col-span-1">
            <button type="button" onclick="removeRow(this)" class="w-full h-[46px] rounded-xl btn-remove transition-all flex items-center justify-center">
                <i class="fas fa-trash-alt"></i>
            </button>
        </div>
    `;
    container.appendChild(div);
}

function removeRow(btn) {
    btn.closest('.dns-row').remove();
}

<?php if(isset($_GET['status']) && $_GET['status'] == 'success'): ?>
    alert('Configurações salvas com sucesso!');
<?php endif; ?>
</script>

<?php include 'includes/footer.php'; ?>