<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Conectar ao banco de dados
$db = new SQLite3('a/.eggziedb.db');

// Função para atualizar a DNS em um link M3U
function update_dns_in_url($url, $old_dns, $new_dns) {
    // Remove o host antigo da URL e adiciona o novo host
    return preg_replace('/^http:\/\/' . preg_quote($old_dns, '/') . '/i', 'http://' . $new_dns, $url);
}

// Atualizar DNS
if (isset($_POST['update_dns'])) {
    $selected_dns = $_POST['selected_dns'];
    $new_dns = $_POST['new_dns'];

    if (!empty($selected_dns) && !empty($new_dns)) {
        // Buscar todos os URLs que contêm a DNS selecionada
        $stmt = $db->prepare('SELECT id, url FROM ibo WHERE url LIKE :selected_dns');
        $stmt->bindValue(':selected_dns', '%' . $selected_dns . '%', SQLITE3_TEXT);
        $results = $stmt->execute();

        while ($row = $results->fetchArray()) {
            $id = $row['id'];
            $url = $row['url'];

            // Atualiza o URL com a nova DNS
            $new_url = update_dns_in_url($url, $selected_dns, $new_dns);

            // Atualiza o URL na base de dados
            $update_stmt = $db->prepare('UPDATE ibo SET url = :new_url WHERE id = :id');
            $update_stmt->bindValue(':new_url', $new_url, SQLITE3_TEXT);
            $update_stmt->bindValue(':id', $id, SQLITE3_INTEGER);
            $update_stmt->execute();
        }

        header('Location: DNS.php'); // Redireciona para evitar envio duplo do formulário
        exit;
    }
}

// Buscar DNS únicas cadastradas
$dns_result = $db->query('SELECT DISTINCT url FROM ibo');

// Extrair e formatar DNS completa (somente host e porta)
function extract_dns($url) {
    $parsed_url = parse_url($url);
    // Reconstruir o host e a porta
    $host = isset($parsed_url['host']) ? $parsed_url['host'] : '';
    $port = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '';
    return $host . $port;
}

// Criar um array para DNS únicas
$unique_dns = [];
while ($row = $dns_result->fetchArray()) {
    $url = htmlspecialchars($row['url']);
    $dns = extract_dns($url);
    if (!in_array($dns, $unique_dns)) {
        $unique_dns[] = $dns;
    }
}

include 'includes/header.php';
?>
<main role="main" class="container-fluid pt-4 px-5">
    <div class="row justify-content-center">
        <div class="col-lg-6 col-md-8 col-sm-12">
            <!-- Imagem acima do container -->
            <div class="text-center mb-4">
                <img src="https://i.imgur.com/NZNGhpx.png" alt="Imagem de Atualização DNS" class="img-fluid" style="max-width: 80%; height: auto;">
            </div>
            <div class="card border-left-primary shadow mb-4" style="border-radius: 0.5rem;">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary"><i class="fas fa-fw fa-server"></i> Atualizar DNS</h6>
                </div>
                <div class="card-body" style="padding: 1.5rem;">
                    <form method="post" class="mb-3">
                        <div class="form-group">
                            <label for="selected_dns">Selecionar DNS:</label>
                            <select name="selected_dns" id="selected_dns" class="form-control">
                                <option value="">Selecione uma DNS</option>
                                <?php foreach ($unique_dns as $dns) { ?>
                                    <option value="<?php echo htmlspecialchars($dns); ?>">
                                        <?php echo htmlspecialchars($dns); ?>
                                    </option>
                                <?php } ?>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="new_dns">Nova DNS:</label>
                            <input type="text" name="new_dns" id="new_dns" class="form-control" placeholder="Digite a nova DNS">
                        </div>
                        <button type="submit" name="update_dns" class="btn btn-primary">Atualizar DNS</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</main>
<?php
include 'includes/footer.php';
?>