<?php
require_once __DIR__.'/includes/config.php';
require_login();

$portals = get_portals();

function popplay_dns_check($url) {
    $url = trim((string)$url);
    if ($url === '') {
        return array('online' => false, 'ping' => null, 'http_code' => 0, 'error' => 'DNS vazio');
    }

    if (!preg_match('#^https?://#i', $url)) {
        $url = 'http://' . $url;
    }

    $start = microtime(true);
    $httpCode = 0;
    $error = '';

    if (function_exists('curl_init')) {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_NOBODY, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 4);
        curl_setopt($ch, CURLOPT_TIMEOUT, 6);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_USERAGENT, 'POPPLAY-DNS-MONITOR/1.0');

        curl_exec($ch);
        $httpCode = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlErr = curl_error($ch);
        curl_close($ch);

        if ($curlErr) {
            $error = $curlErr;
        }
    } else {
        $context = stream_context_create(array(
            'http' => array('method' => 'HEAD', 'timeout' => 6),
            'ssl' => array('verify_peer' => false, 'verify_peer_name' => false)
        ));
        $headers = @get_headers($url, 0, $context);
        if (is_array($headers) && isset($headers[0]) && preg_match('/\s(\d{3})\s/', $headers[0], $m)) {
            $httpCode = (int)$m[1];
        } else {
            $error = 'Sem resposta HTTP';
        }
    }

    $ping = (int)round((microtime(true) - $start) * 1000);

    // Considera online qualquer resposta HTTP válida abaixo de 500.
    // 401/403 também indicam que o servidor respondeu.
    $online = ($httpCode > 0 && $httpCode < 500);

    return array(
        'online' => $online,
        'ping' => $online ? $ping : null,
        'http_code' => $httpCode,
        'error' => $error
    );
}

$checks = array();
if (isset($_GET['check_ping'])) {
    foreach ($portals as $idx => $portalUrl) {
        if (trim((string)$portalUrl) === '') continue;
        $checks[$idx + 1] = popplay_dns_check($portalUrl);
    }
}

include __DIR__.'/includes/header.php';
?>

<style>
    .dns-status-pill{display:inline-flex;align-items:center;gap:6px;padding:6px 10px;border-radius:999px;font-weight:700;font-size:12px;}
    .dns-online{background:rgba(0,200,83,.15);color:#00e676;border:1px solid rgba(0,230,118,.35);}
    .dns-offline{background:rgba(255,23,68,.13);color:#ff5252;border:1px solid rgba(255,82,82,.35);}
    .ping-box{display:inline-block;padding:6px 10px;border-radius:10px;background:rgba(255,122,0,.12);border:1px solid rgba(255,122,0,.35);color:#ffb15c;font-weight:700;}
    .dns-actions{display:flex;gap:10px;flex-wrap:wrap;margin:12px 0 18px;}
    .small-muted{font-size:12px;opacity:.75;}
</style>

<div class="card">
    <h3>DNS configurados</h3>
    <?php if(isset($_GET['ok'])): ?><p class="ok">DNS salvo com sucesso.</p><?php endif; ?>
    <p class="muted">Lista individual: <b><?=h(dns_owner_label())?></b>. O app chama este domínio; estes DNS são os servidores para onde o script redireciona.</p>

    <div class="dns-actions">
        <a class="btn" href="dns_create.php">Editar DNS</a>
        <a class="btn" href="dns.php?check_ping=1">Atualizar Ping</a>
    </div>

    <table>
        <tr>
            <th>ID</th>
            <th>URL</th>
            <th>Status</th>
            <th>Ping</th>
            <th>HTTP</th>
            <th>Última checagem</th>
        </tr>
        <?php for($i=1;$i<=20;$i++):
            $v = $portals[$i-1] ?? '';
            if(!$v) continue;
            $check = $checks[$i] ?? null;
        ?>
        <tr>
            <td>DNS<?=$i?></td>
            <td><?=h($v)?></td>
            <td>
                <?php if($check): ?>
                    <?php if($check['online']): ?>
                        <span class="dns-status-pill dns-online">● Online</span>
                    <?php else: ?>
                        <span class="dns-status-pill dns-offline">● Offline</span>
                    <?php endif; ?>
                    <?php if(!$check['online'] && !empty($check['error'])): ?>
                        <div class="small-muted"><?=h($check['error'])?></div>
                    <?php endif; ?>
                <?php else: ?>
                    <span class="muted">Aguardando teste</span>
                <?php endif; ?>
            </td>
            <td>
                <?php if($check && $check['online']): ?>
                    <span class="ping-box"><?=h($check['ping'])?> ms</span>
                <?php else: ?>
                    <span class="muted">--</span>
                <?php endif; ?>
            </td>
            <td><?= $check ? h((string)$check['http_code']) : '<span class="muted">--</span>' ?></td>
            <td><?= $check ? date('d/m/Y H:i:s') : '<span class="muted">--</span>' ?></td>
        </tr>
        <?php endfor; ?>
    </table>

    <?php if(!$portals): ?>
        <p class="bad">Nenhum DNS cadastrado.</p>
    <?php endif; ?>

    <p class="muted small-muted" style="margin-top:12px;">
        Observação: este monitor usa teste HTTP para medir resposta do DNS. Em hospedagem cPanel isso é mais seguro que ping ICMP, que muitas vezes fica bloqueado.
    </p>
</div>

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