<?php
/**
 * dns.php - Sistema de Gestão de Servidores DNS v5.0
 * Foco: Estabilidade total e Responsividade Mobile
 */

// Inicia o buffer de saida para permitir redirecionamentos via header sem erros
ob_start();
include "includes/header.php";

$table_name = "dns";
$current_page = basename($_SERVER["SCRIPT_NAME"]);

// ============================================================
// 📡 BACKEND: TESTADOR DE CONEXÃO (API PING) - MANTIDO INTACTO
// ============================================================
if (isset($_POST['action']) && $_POST['action'] === 'test_dns') {
    if (ob_get_length()) ob_clean();
    header('Content-Type: application/json');

    $originalUrl = $_POST['url'];
    $response = ['status' => 'offline', 'ms' => 0, 'msg' => 'Offline'];

    $testUrl = $originalUrl;
    if (!preg_match("~^(?:f|ht)tps?://~i", $testUrl)) {
        $testUrl = "http://" . $testUrl;
    }

    $ch = curl_init($testUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_NOBODY, true); 
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);    
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)');
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); 
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    $starttime = microtime(true);
    $exec = curl_exec($ch);
    $stoptime = microtime(true);
    
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($exec !== false && $httpCode > 0 && $httpCode < 500) {
        $ping = round(($stoptime - $starttime) * 1000);
        $response['status'] = 'online';
        $response['ms'] = $ping;
        $response['msg'] = $ping . "ms";
    }
    echo json_encode($response);
    exit;
}

// 1. Verificação de integridade da conexão
if (!isset($db) || !is_object($db)) {
    die("<div class='alert alert-danger m-5'>Erro interno: Conexão com o banco falhou.</div>");
}

/**
 * PROCESSAMENTO DE AÇÕES (CRUD) - MANTIDO 100% ORIGINAL
 */
if (isset($_POST["submit"])) {
    unset($_POST["submit"]);
    $success = $db->insert($table_name, $_POST);
    $status = $success ? 1 : 500;
    header("Location: {$current_page}?status={$status}");
    exit;
}

if (isset($_POST["submitU"]) && isset($_GET["update"])) {
    unset($_POST["submitU"]);
    $id = (int)$_GET["update"];
    $success = $db->update($table_name, $_POST, "id = :id", [":id" => $id]);
    $status = $success ? 1 : 500;
    header("Location: {$current_page}?status={$status}");
    exit;
}

if (isset($_GET["delete"])) {
    $id = (int)$_GET["delete"];
    $success = $db->delete($table_name, "id = :id", [":id" => $id]);
    header("Location: {$current_page}?status=2");
    exit;
}

if (isset($_GET["deleteall"])) {
    $db->delete($table_name, "1=1", []);
    header("Location: {$current_page}?status=2");
    exit;
}

$res = $db->select($table_name, "*", "", "id DESC");
$resU = (isset($_GET["update"])) ? $db->select($table_name, "*", "id = :id", "", [":id" => (int)$_GET["update"]]) : [];
?>

<style>
    :root {
        --primary: #4f46e5; --secondary: #6366f1; --dark: #0f172a;
        --success: #10b981; --danger: #ef4444; --bg: #f8fafc;
        --surface: #ffffff; --border: #e2e8f0; --radius: 16px;
    }

    body { background-color: var(--bg); font-family: 'Inter', sans-serif; color: var(--dark); }
    .dashboard-container { width: 100%; max-width: 1200px; margin: 1.5rem auto; padding: 0 1rem; }

    /* Cards e UI */
    .glass-card { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1); overflow: hidden; }
    .card-header-gradient { background: #1e293b; color: white; padding: 1.2rem; display: flex; align-items: center; justify-content: space-between; border: none; }

    /* Tabela Responsiva */
    .table-responsive { width: 100%; overflow-x: auto; -webkit-overflow-scrolling: touch; }
    .custom-table { width: 100%; border-collapse: collapse; min-width: 700px; }
    .custom-table th { background: #f1f5f9; color: #64748b; font-size: 0.75rem; text-transform: uppercase; padding: 1rem; font-weight: 700; }
    .custom-table td { padding: 1rem; border-bottom: 1px solid var(--border); vertical-align: middle; }

    /* Badges de Status */
    .ping-badge { font-size: 0.75rem; font-weight: 700; padding: 6px 12px; border-radius: 99px; display: inline-flex; align-items: center; gap: 6px; }
    .online { background: #dcfce7; color: #15803d; }
    .offline { background: #fee2e2; color: #b91c1c; }
    .loading { background: #f1f5f9; color: #64748b; }

    .pulse-dot { width: 7px; height: 7px; border-radius: 50%; background: currentColor; animation: pulse 1.5s infinite; }
    @keyframes pulse { 0% { opacity: 1; } 50% { opacity: 0.3; } 100% { opacity: 1; } }

    /* Botões */
    .btn-custom { padding: 0.6rem 1.2rem; border-radius: 10px; font-weight: 600; border: none; cursor: pointer; display: inline-flex; align-items: center; gap: 8px; text-decoration: none; transition: 0.2s; }
    .btn-primary-custom { background: var(--primary); color: white !important; }
    .btn-primary-custom:hover { background: var(--secondary); transform: translateY(-1px); }
    .action-btn { width: 36px; height: 36px; border-radius: 8px; display: inline-flex; align-items: center; justify-content: center; border: 1px solid var(--border); background: white; color: #64748b; transition: 0.2s; }
    .action-btn:hover { background: #f1f5f9; color: var(--primary); }

    code { background: #f1f5f9; padding: 4px 8px; border-radius: 6px; color: #475569; font-size: 0.85rem; word-break: break-all; }

    @media (max-width: 768px) {
        .card-header-gradient { flex-direction: column; gap: 15px; text-align: center; }
        .btn-custom { width: 100%; justify-content: center; }
    }
</style>

<div class="dashboard-container">
    
    <?php if (isset($_GET['status'])): ?>
        <div class="alert alert-dismissible fade show shadow-sm border-0 mb-4 animated fadeInDown" style="background: white; border-left: 5px solid <?= ($_GET['status'] == 500) ? '#ef4444' : '#10b981' ?> !important; border-radius: 12px;">
            <div class="d-flex align-items-center">
                <i class="fa-solid <?= ($_GET['status'] == 500) ? 'fa-circle-xmark text-danger' : 'fa-circle-check text-success' ?> fa-lg me-3"></i>
                <div class="fw-bold"><?= ($_GET['status'] == 1) ? "Dados salvos com sucesso!" : (($_GET['status'] == 2) ? "Registro removido!" : "Ocorreu um erro no servidor.") ?></div>
                <button type="button" class="btn-close ms-auto" data-bs-dismiss="alert"></button>
            </div>
        </div>
    <?php endif; ?>

    <?php if (isset($_GET["create"]) || isset($_GET["update"])): 
        $isEdit = isset($_GET["update"]);
        $editData = $isEdit ? ($resU[0] ?? []) : [];
    ?>
        <div class="row justify-content-center">
            <div class="col-lg-6">
                <div class="glass-card">
                    <div class="card-header-gradient">
                        <h5 class="m-0"><i class="fa-solid <?= $isEdit ? 'fa-pen-to-square' : 'fa-plus' ?> me-2"></i><?= $isEdit ? 'Editar DNS' : 'Novo Servidor DNS' ?></h5>
                    </div>
                    <div class="card-body p-4">
                        <form method="post">
                            <div class="mb-3">
                                <label class="small fw-bold text-muted text-uppercase mb-2">Apelido do Servidor</label>
                                <input type="text" class="form-control" name="title" value="<?= htmlspecialchars($editData['title'] ?? '') ?>" placeholder="Ex: Servidor BR" required>
                            </div>
                            <div class="mb-4">
                                <label class="small fw-bold text-muted text-uppercase mb-2">URL de Conexão</label>
                                <input type="text" class="form-control font-monospace" name="url" value="<?= htmlspecialchars($editData['url'] ?? '') ?>" placeholder="http://servidor.com:8080" required>
                            </div>
                            <div class="d-flex gap-2">
                                <button type="submit" name="<?= $isEdit ? 'submitU' : 'submit' ?>" class="btn-custom btn-primary-custom flex-grow-1">
                                    <i class="fa-solid fa-save"></i> Salvar DNS
                                </button>
                                <a href="<?= $current_page ?>" class="btn-custom bg-light flex-grow-1 text-center">Cancelar</a>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

    <?php else: ?>
        <div class="glass-card">
            <div class="card-header-gradient">
                <div class="d-flex align-items-center gap-3">
                    <i class="fa-solid fa-server fa-lg text-secondary"></i>
                    <h5 class="m-0">Meus Servidores DNS</h5>
                </div>
                <div class="d-flex gap-2">
                    <button onclick="testAllDNS()" class="btn-custom bg-white text-dark btn-sm shadow-sm">
                        <i class="fa-solid fa-bolt text-warning"></i> Testar Todos
                    </button>
                    <a href="?create" class="btn-custom btn-primary-custom btn-sm shadow-sm">
                        <i class="fa-solid fa-plus"></i> Novo DNS
                    </a>
                </div>
            </div>

            <div class="table-responsive">
                <table class="custom-table">
                    <thead>
                        <tr>
                            <th class="ps-4">Servidor / ID</th>
                            <th>Endpoint URL</th>
                            <th>Saúde / Latência</th>
                            <th class="text-center">Gerenciar</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (count($res) > 0): ?>
                            <?php foreach ($res as $row): ?>
                                <tr>
                                    <td class="ps-4">
                                        <div class="fw-bold"><?= htmlspecialchars($row['title']) ?></div>
                                        <div class="text-muted small">ID: #<?= $row['id'] ?></div>
                                    </td>
                                    <td><code><?= htmlspecialchars($row['url']) ?></code></td>
                                    <td id="ping-<?= $row['id'] ?>">
                                        <span class="ping-badge loading"><i class="fa-solid fa-spinner fa-spin me-2"></i>Aguardando</span>
                                    </td>
                                    <td>
                                        <div class="d-flex justify-content-center gap-2">
                                            <button onclick="checkSingleDNS('<?= $row['url'] ?>', <?= $row['id'] ?>)" class="action-btn" title="Ping individual">
                                                <i class="fa-solid fa-rotate"></i>
                                            </button>
                                            <a href="?update=<?= $row['id'] ?>" class="action-btn"><i class="fa-solid fa-edit"></i></a>
                                            <a href="?delete=<?= $row['id'] ?>" class="action-btn text-danger" onclick="return confirm('Excluir este DNS?')"><i class="fa-solid fa-trash"></i></a>
                                        </div>
                                    </td>
                                    <span class="dns-url d-none" data-id="<?= $row['id'] ?>"><?= $row['url'] ?></span>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="4" class="text-center py-5">
                                    <div class="text-muted">Nenhum servidor encontrado. Clique em "Novo DNS" para começar.</div>
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
            
            <?php if (count($res) > 0): ?>
            <div class="p-3 bg-light border-top text-end">
                <a href="?deleteall=1" class="text-danger small fw-bold" onclick="return confirm('ATENÇÃO: Apagar TODOS os servidores?')">
                    <i class="fa-solid fa-circle-exclamation"></i> LIMPAR TODOS OS DADOS
                </a>
            </div>
            <?php endif; ?>
        </div>
    <?php endif; ?>
</div>

<script>
    function checkSingleDNS(url, id) {
        const target = document.getElementById('ping-' + id);
        if(!target) return;
        target.innerHTML = '<span class="ping-badge loading"><i class="fa-solid fa-spinner fa-spin me-2"></i>Lendo</span>';

        const formData = new FormData();
        formData.append('action', 'test_dns');
        formData.append('url', url);

        fetch(window.location.href, { method: 'POST', body: formData })
        .then(res => res.json())
        .then(data => {
            if(data.status === 'online') {
                const colorClass = data.ms < 200 ? 'online' : 'loading';
                target.innerHTML = `<span class="ping-badge ${colorClass}"><span class="pulse-dot"></span> ${data.msg}</span>`;
            } else {
                target.innerHTML = `<span class="ping-badge offline">Offline</span>`;
            }
        })
        .catch(() => { target.innerHTML = `<span class="ping-badge offline">Erro API</span>`; });
    }

    function testAllDNS() {
        document.querySelectorAll('.dns-url').forEach((el, i) => {
            setTimeout(() => { checkSingleDNS(el.textContent.trim(), el.dataset.id); }, i * 150);
        });
    }

    // Auto-hider para alertas
    setTimeout(() => {
        const alerts = document.querySelectorAll('.alert');
        alerts.forEach(a => {
            a.style.opacity = '0';
            a.style.transition = '0.5s';
            setTimeout(() => a.remove(), 500);
        });
    }, 4000);

    <?php if (!isset($_GET["create"]) && !isset($_GET["update"])): ?>
    window.addEventListener('load', testAllDNS);
    <?php endif; ?>
</script>

<?php 
include "includes/footer.php";
ob_end_flush();
?>