<?php
$dns_file = __DIR__ . '/dns.json';
$portals_file = __DIR__ . '/portals.json';

function write_portals_json($dns_file, $portals_file) {
    $raw = @file_get_contents($dns_file);
    $data = is_string($raw) ? json_decode($raw, true) : null;
    if (!is_array($data)) { $data = []; }

    $out = [];
    foreach ($data as $item) {
        if (is_array($item)) {
            if (isset($item['url']) && is_string($item['url'])) {
                $u = trim($item['url']);
                if ($u !== '') $out[] = $u;
            }
        } elseif (is_string($item)) {
            $u = trim($item);
            if ($u !== '') $out[] = $u;
        }
    }

    $payload = json_encode(['dns' => array_values($out)], JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
    if (!is_string($payload)) { $payload = "{\n  \"dns\": []\n}\n"; }

    @file_put_contents($portals_file, $payload);
    return $payload;
}

// If included from index.php, we don't want to echo automatically.
if (defined('NEUTRO_PANEL_INCLUDED')) {
    return;
}

header('Content-Type: application/json; charset=utf-8');
echo write_portals_json($dns_file, $portals_file);
