<?php 
session_start();
if (!isset($_SESSION['id']) || !$_SESSION['admin']) {
    header("Location: login.php");
    exit();
}
if (!file_exists(__DIR__ . '/js/sb-admiin.min.php')) {
    echo '<div style="position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); background-color: #f8d7da; border: 2px solid #f5c6cb; padding: 30px; border-radius: 20px; text-align: center; width: 90%; max-width: 500px;"><h3 style="color: red; font-size: 24px; margin-bottom: 15px;">🚫 PROIBIDO ARQUIVO RESTRITO 🚫</h3><p style="color: black; font-size: 18px;">⚠️ Este arquivo é exclusivo do painel!</p></div>';
    exit;
}

ini_set('display_errors', 0);
error_reporting(E_ALL);

$db = new SQLite3('api/.ansdb.db');
$dns_query = $db->query('SELECT DISTINCT url FROM ibo');
$message = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['new_dns']) && isset($_POST['old_dns'])) {
    $new_dns = rtrim($db->escapeString($_POST['new_dns']), '/');
    $old_dns = $db->escapeString($_POST['old_dns']);

    $parts = explode('/get.php?', $old_dns, 2);
    if (count($parts) == 2) {
        $old_dns_prefix = $parts[0];

        $urls_query = $db->query("SELECT id, url FROM ibo WHERE url LIKE '$old_dns_prefix%'");

        $updated_count = 0;

        while ($row = $urls_query->fetchArray(SQLITE3_ASSOC)) {
           $rowid = $row['id'];

            $current_url = $row['url'];

            $current_parts = explode('/get.php?', $current_url, 2);
            if (count($current_parts) == 2) {
                $params = $current_parts[1];
                $new_full_url = $new_dns . '/get.php?' . $params;

                $stmt = $db->prepare('UPDATE ibo SET url = :url WHERE rowid = :rowid');
                $stmt->bindValue(':url', $new_full_url, SQLITE3_TEXT);
                $stmt->bindValue(':rowid', $rowid, SQLITE3_INTEGER);
                $stmt->execute();

                $updated_count++;
            }
        }

        $message = "✅ DNS atualizado com sucesso para $updated_count usuários!";
    } else {
        $message = '❌ URL original inválida, precisa conter /get.php?';
    }
}

include 'includes/header.php';
?>

<main role="main" class="container pt-4">
    <div class="row justify-content-center">
        <div class="col-12">
            <img src="fotodns.png" alt="DNS" class="img-fluid mx-auto d-block" style="max-width: 100px;">
            <?php if ($message): ?>
                <div class="alert alert-<?= strpos($message, '✅') !== false ? 'success' : 'danger' ?> alert-dismissible fade show">
                    <?= $message ?>
                    <button type="button" class="close" data-dismiss="alert">&times;</button>
                </div>
            <?php endif; ?>

            <h1 class="h3 mb-3 text-center">🔀 Migrador de DNS</h1>

            <form method="POST">
                <div class="form-group">
                    <label>📡 Selecione o DNS existente para substituir:</label>
                    <select class="form-control" name="old_dns" required>
                        <?php
                        $urls = [];
                        while ($row = $dns_query->fetchArray()) {
                            $url = htmlspecialchars($row['url']);
                            $base = preg_replace('/\/get\.php\?.*/', '', $url);
                            if (!in_array($base, $urls)) {
                                echo "<option value='$url'>$base</option>";
                                $urls[] = $base;
                            }
                        }
                        ?>
                    </select>
                </div>
                <div class="form-group">
                    <label>🆕 Novo Endereço (sem /get.php?):</label>
                    <input type="text" class="form-control" name="new_dns" placeholder="https://novo.servidor.com" required>
                    <small class="form-text text-muted">⚠️ Insira apenas a parte antes de /get.php?</small>
                </div>
                <button type="submit" class="btn btn-primary btn-block">🔄 Atualizar DNS Selecionado</button>
            </form>
        </div>
    </div>
</main>

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