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

// Caminho ajustado para a raiz
include "includes/header.php";

// Banco de dados na raiz (ajuste o path se necessário)
$db_path = './a/.eggziedb.db';
$message = "";

try {
    $db = new SQLite3($db_path);

    // 1. Busca quais DNS existem no banco
    $res = $db->query("SELECT url, COUNT(*) as total FROM ibo GROUP BY url");
    $dns_existentes = [];
    if ($res) {
        while ($row = $res->fetchArray(SQLITE3_ASSOC)) {
            $dns_existentes[] = $row;
        }
    }

    // 2. Lógica da Migração
    if (isset($_POST['migrar'])) {
        $dns_antiga = $_POST['dns_antiga'];
        $dns_nova   = trim($_POST['dns_nova']);

        if (!empty($dns_antiga) && !empty($dns_nova)) {
            $stmt = $db->prepare("UPDATE ibo SET url = :nova WHERE url = :antiga");
            $stmt->bindValue(':nova', $dns_nova, SQLITE3_TEXT);
            $stmt->bindValue(':antiga', $dns_antiga, SQLITE3_TEXT);
            
            if ($stmt->execute()) {
                $afetados = $db->changes();
                $message = "success|$afetados";
                // Atualiza a lista após migrar
                $res = $db->query("SELECT url, COUNT(*) as total FROM ibo GROUP BY url");
                $dns_existentes = [];
                while ($row = $res->fetchArray(SQLITE3_ASSOC)) { $dns_existentes[] = $row; }
            }
        }
    }
    $db->close();
} catch (Exception $e) {
    echo "<div class='alert alert-danger'>Erro ao conectar no banco de dados.</div>";
}

$status = "";
$count = 0;
if(!empty($message)) {
    list($status, $count) = explode('|', $message);
}
?>

<style>
    #content-wrapper, #content, .container-fluid, main {
        background-color: #06070a !important;
    }
    .flux-card {
        background: #0f111a !important;
        border: 1px solid rgba(255,255,255,0.05) !important;
        border-radius: 2rem !important;
    }
    .dns-item {
        background: rgba(255,255,255,0.02);
        border: 1px solid rgba(255,255,255,0.05);
        transition: all 0.3s ease;
        margin-bottom: 8px;
    }
    .dns-item:hover {
        border-color: #f97316;
        background: rgba(249, 115, 22, 0.05);
    }
    .flux-input {
        background: rgba(255,255,255,0.03) !important;
        border: 1px solid rgba(255, 255, 255, 0.1) !important;
        border-radius: 15px !important;
        color: #60a5fa !important;
        padding: 15px !important;
        width: 100%;
    }
</style>

<main class="py-8 px-4">
    <div class="max-w-4xl mx-auto">
        <div class="mb-8 text-center md:text-left">
            <h1 class="text-3xl font-black text-white tracking-tighter italic uppercase">Migração DNS</h1>
            <p class="text-[10px] text-orange-500 font-bold uppercase tracking-[0.4em]">VU FLUX • SISTEMA EM MASSA</p>
        </div>

        <?php if($status == "success"): ?>
            <div class="mb-6 p-4 bg-emerald-500/10 border border-emerald-500/50 text-emerald-400 rounded-2xl flex items-center gap-3 animate-pulse">
                <i class="fas fa-check-circle text-lg"></i>
                <span class="text-xs font-bold uppercase">Sucesso: <?php echo $count; ?> usuários migrados!</span>
            </div>
        <?php endif; ?>

        <div class="flux-card overflow-hidden shadow-2xl">
            <div class="bg-gradient-to-r from-orange-600/20 to-transparent p-6 border-b border-white/5 text-white">
                <h3 class="font-bold uppercase text-sm tracking-widest">Painel de Migração</h3>
            </div>

            <form method="POST" class="p-8 space-y-6">
                <div>
                    <label class="block text-[10px] font-black uppercase text-orange-500 mb-4">1. DNS DE ORIGEM</label>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                        <?php if(empty($dns_existentes)): ?>
                            <p class="text-gray-600 italic text-xs py-4">Nenhum dado encontrado...</p>
                        <?php else: ?>
                            <?php foreach($dns_existentes as $item): ?>
                                <label class="dns-item flex items-center justify-between p-4 rounded-2xl cursor-pointer group">
                                    <div class="flex items-center gap-3 text-white">
                                        <input type="radio" name="dns_antiga" value="<?php echo $item['url']; ?>" required class="accent-orange-500">
                                        <span class="text-xs font-mono"><?php echo $item['url']; ?></span>
                                    </div>
                                    <span class="text-[9px] font-black bg-white/5 px-2 py-1 rounded-lg text-gray-400">
                                        <?php echo $item['total']; ?> USERs
                                    </span>
                                </label>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>

                <div>
                    <label class="block text-[10px] font-black uppercase text-blue-500 mb-4">2. DNS DE DESTINO</label>
                    <input type="url" name="dns_nova" required class="flux-input" placeholder="http://novo-servidor.com:80">
                </div>

                <button type="submit" name="migrar" onclick="return confirm('ATENÇÃO: Operação irreversível. Continuar?')"
                        class="w-full py-5 bg-orange-600 hover:bg-orange-500 text-white rounded-2xl text-xs font-black shadow-xl transition-all uppercase tracking-widest">
                    <i class="fas fa-bolt mr-2"></i> Executar Migração Agora
                </button>
            </form>
        </div>
    </div>
</main>

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