<?php
session_start();
date_default_timezone_set('America/Sao_Paulo');

require_once 'config.php'; 

$pdo = getConexaoAtiva();
$pdo_int = getConexaoInterna();

$pdo->exec("SET NAMES utf8mb4");
$pdo_int->exec("SET NAMES utf8mb4");

// Verificação de segurança
if (!isset($_SESSION['user_id'])) { header("Location: login.php"); exit; }
$user_id_logado = $_SESSION['user_id']; 
$role = $_SESSION['user_role'] ?? 'reseller';
$nome_usuario = $_SESSION['username'] ?? 'Usuário'; 

// Apenas administradores devem gerenciar DNS/Servidores
if ($role !== 'admin') {
    die("<h2 style='color:white; text-align:center; padding:50px; font-family:sans-serif;'>Acesso Negado. Apenas administradores podem gerenciar o DNS.</h2>");
}

// ====================================================================
// INTELIGÊNCIA ARTIFICIAL: DETECTA SE É XUI ONE OU XTREAM UI
// ====================================================================
$modo_ativo = 'interno';
try {
    $modo_ativo = $pdo_int->query("SELECT modo_ativo FROM configuracoes LIMIT 1")->fetchColumn() ?: 'interno';
} catch (Exception $e) {}

$tabela_servidores = 'streaming_servers'; // Padrão Xtream UI
if ($modo_ativo === 'xui') {
    try { 
        $pdo->query("SELECT 1 FROM servers LIMIT 1"); 
        $tabela_servidores = 'servers'; // Padrão XUI One
    } catch (Exception $e) {}
}

// Verifica dinamicamente se existe a coluna domain_name e cria se não existir (Proteção extra)
$colunas_server = [];
try {
    $colunas_server = $pdo->query("SHOW COLUMNS FROM $tabela_servidores")->fetchAll(PDO::FETCH_COLUMN);
} catch (Exception $e) {}

$has_domain = in_array('domain_name', $colunas_server);
if (!$has_domain) {
    try {
        $pdo->exec("ALTER TABLE $tabela_servidores ADD COLUMN domain_name VARCHAR(255) DEFAULT ''");
        $has_domain = true;
    } catch (Exception $e) {}
}

// --- BUSCA DE PERSONALIZAÇÃO E SALDO ---
$nome_painel = 'TOP IPTV'; $logo_url = ''; $cor_primaria = '#007bff';
try {
    $config_painel = $pdo_int->query("SELECT * FROM painel_config LIMIT 1")->fetch(PDO::FETCH_ASSOC);
    if ($config_painel) {
        $nome_painel = !empty($config_painel['nome_painel']) ? $config_painel['nome_painel'] : $nome_painel;
        $cor_primaria = !empty($config_painel['cor_primaria']) ? $config_painel['cor_primaria'] : $cor_primaria;
        $logo_url = $config_painel['logo_url'] ?? '';
    }
} catch (Exception $e) {}

try {
    $tabela_rev = ($modo_ativo === 'xui') ? 'users' : 'reg_users';
    $user_credits = $pdo->query("SELECT credits FROM $tabela_rev WHERE id = " . intval($user_id_logado))->fetchColumn() ?: 0;
} catch (Exception $e) { $user_credits = 0; }

$mensagem = "";

// =========================================================================
// PROCESSAMENTO: SALVAR ALTERAÇÃO DE DNS / IP
// =========================================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action_save'])) {
    $id_server = intval($_POST['server_id']);
    $server_name = trim($_POST['server_name']);
    $server_ip = trim($_POST['server_ip']);
    $domain_name = trim($_POST['domain_name'] ?? '');

    try {
        if ($has_domain) {
            $stmt = $pdo->prepare("UPDATE $tabela_servidores SET server_name = ?, server_ip = ?, domain_name = ? WHERE id = ?");
            $stmt->execute([$server_name, $server_ip, $domain_name, $id_server]);
        } else {
            $stmt = $pdo->prepare("UPDATE $tabela_servidores SET server_name = ?, server_ip = ? WHERE id = ?");
            $stmt->execute([$server_name, $server_ip, $id_server]);
        }
        $mensagem = "<div class='alert success'><i class='fas fa-check-circle'></i> DNS / Servidor atualizado com sucesso!</div>";
    } catch (Exception $e) {
        $mensagem = "<div class='alert danger'><i class='fas fa-times-circle'></i> Erro ao atualizar servidor: " . $e->getMessage() . "</div>";
    }
}

// =========================================================================
// BUSCA LISTA DE SERVIDORES
// =========================================================================
$servidores = [];
try {
    $servidores = $pdo->query("SELECT * FROM $tabela_servidores ORDER BY id ASC")->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $mensagem = "<div class='alert danger'><i class='fas fa-times-circle'></i> Erro ao buscar tabela de servidores.</div>";
}
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <link rel="stylesheet" href="tema.css">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Gerenciador de DNS - <?php echo htmlspecialchars($nome_painel); ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root { --bg-dark: #121519; --bg-sidebar: #1e2227; --bg-card: #272c33; --text-main: #d1d5da; --text-muted: #8a94a1; --accent: <?php echo $cor_primaria; ?>; --border-color: #3a4149; --success: #28a745; --danger: #dc3545; --warning: #f39c12; --info: #17a2b8; }
        body { margin: 0; font-family: 'Segoe UI', sans-serif; background-color: var(--bg-dark); color: var(--text-main); display: flex; height: 100vh; overflow: hidden; }
        
        /* SIDEBAR CSS */
        .sidebar { width: 260px; background-color: var(--bg-sidebar); border-right: 1px solid var(--border-color); display: flex; flex-direction: column; z-index: 1001; transition: 0.3s; flex-shrink: 0; }
        .sidebar-header { padding: 25px 20px; text-align: center; font-size: 22px; font-weight: bold; color: white; border-bottom: 1px solid var(--border-color); }
        .sidebar-logo { width: 100%; max-width: 180px; height: auto; max-height: 60px; object-fit: contain; display: block; margin: 0 auto; }
        .user-info { padding: 20px; text-align: center; border-bottom: 1px solid var(--border-color); }
        .user-info .badge { background: rgba(0, 123, 255, 0.2); color: var(--accent); padding: 4px 10px; border-radius: 4px; font-size: 11px; text-transform: uppercase; font-weight: bold; margin-top: 5px; display: inline-block; }
        .credits-badge { display: block; margin-top: 10px; color: var(--success); font-weight: bold; font-size: 13px; }
        .menu-list { list-style: none; padding: 0; margin: 0; overflow-y: auto; flex: 1; }
        .menu-item { padding: 14px 20px; color: var(--text-main); text-decoration: none; display: flex; align-items: center; transition: 0.2s; border-left: 3px solid transparent; font-size: 15px; cursor: pointer; }
        .menu-item i:first-child { margin-right: 12px; width: 20px; text-align: center; color: var(--text-muted); }
        .menu-item:hover, .menu-item.active { background-color: #2c3138; color: white; border-left-color: var(--accent); }
        .menu-item.active i:first-child { color: var(--accent); }
        .submenu { display: none; background: #16191d; list-style: none; padding: 0; margin: 0; }
        .submenu .menu-item { padding-left: 52px; font-size: 13px; border-left: none; }
        .arrow-icon { margin-left: auto; transition: 0.3s; font-size: 11px; }
        .rotate { transform: rotate(180deg); }
        .menu-category { padding: 20px 20px 8px; font-size: 10px; text-transform: uppercase; color: var(--text-muted); font-weight: bold; letter-spacing: 1px; }
        .logout-btn { padding: 15px; background-color: #dc3545; color: white; text-align: center; text-decoration: none; font-weight: bold; }
        .sidebar-overlay { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.7); z-index: 1000; }
        
        .main-content { flex: 1; display: flex; flex-direction: column; overflow-y: auto; overflow-x: hidden; transition: 0.3s; position: relative; width: 100vw; max-width: 100%; }
        .topbar { display: flex; justify-content: space-between; align-items: center; padding: 15px 30px; background-color: var(--bg-sidebar); border-bottom: 1px solid var(--border-color); }
        
        /* CORREÇÃO DO BOTÃO: nowrap e flex-shrink para não quebrar no mobile */
        .mode-badge { padding: 6px 15px; background: rgba(40, 167, 69, 0.15); color: var(--success); border-radius: 20px; font-size: 12px; font-weight: bold; border: 1px solid var(--success); white-space: nowrap; flex-shrink: 0; display: inline-block; }
        
        .content-area { padding: 30px; flex: 1; overflow-y: auto; overflow-x: hidden; padding-bottom: 100px; box-sizing: border-box; width: 100%; }
        .menu-toggle { display: none; background: none; border: none; color: white; font-size: 24px; cursor: pointer; }
        
        .page-header { margin-bottom: 25px; }
        .page-header h3 { font-size: 24px; color: white; margin: 0 0 5px 0; display: flex; align-items: center; gap: 10px; }
        .page-header h3 i { color: var(--accent); font-size: 26px; }
        
        .card-table { background: var(--bg-card); border-radius: 10px; border: 1px solid var(--border-color); overflow-x: auto; width: 100%; display: block; -webkit-overflow-scrolling: touch; }
        table { width: 100%; border-collapse: collapse; min-width: 600px; }
        th { background: #16191d; padding: 15px; text-align: left; color: var(--text-muted); font-size: 11px; text-transform: uppercase; }
        td { padding: 15px; border-bottom: 1px solid var(--border-color); font-size: 14px; }
        .badge { padding: 4px 8px; border-radius: 4px; font-size: 10px; font-weight: bold; text-transform: uppercase; }
        .bg-success { background: rgba(46, 204, 113, 0.2); color: #2ecc71; border: 1px solid #2ecc71;}
        .bg-danger { background: rgba(231, 76, 60, 0.2); color: #e74c3c; border: 1px solid #e74c3c;}
        
        .btn-action { width: auto; padding: 8px 15px; border-radius: 6px; border: none; cursor: pointer; color: white; display: inline-flex; align-items: center; justify-content: center; gap: 5px; font-weight: bold; font-size: 12px; transition: 0.2s;}
        .btn-action:hover { filter: brightness(1.2); }
        
        .modal { display: none; position: fixed; z-index: 2000; left: 0; top: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.85); align-items: center; justify-content: center; }
        .modal-content { background: var(--bg-card); width: 90%; max-width: 450px; padding: 25px; border-radius: 12px; border: 1px solid var(--border-color); position: relative; }
        .form-group-modal { margin-bottom: 15px; }
        .form-group-modal label { display: block; margin-bottom: 5px; font-size: 12px; color: var(--text-muted); font-weight: bold;}
        .form-group-modal input { width: 100%; padding: 12px; background: #121519; border: 1px solid var(--border-color); color: white; border-radius: 5px; box-sizing: border-box; font-size: 14px;}
        .btn-save-modal { width: 100%; padding: 14px; background: var(--accent); border: none; color: white; border-radius: 5px; font-weight: bold; cursor: pointer; transition: 0.2s; font-size: 14px; margin-top: 10px;}
        
        .alert { padding: 15px; border-radius: 8px; margin-bottom: 20px; font-weight: bold; font-size: 14px; transition: opacity 0.5s ease; border: 1px solid transparent; }
        .alert.success { background: rgba(40, 167, 69, 0.1); color: var(--success); border-color: var(--success); }
        .alert.danger { background: rgba(220, 53, 69, 0.15); color: #e74c3c; border-color: #e74c3c; }

        @media (max-width: 768px) {
            .sidebar { position: fixed; left: -260px; height: 100%; box-shadow: 10px 0 20px rgba(0,0,0,0.5); }
            .sidebar.active { left: 0; }
            .sidebar-overlay.active { display: block; }
            .menu-toggle { display: block; margin-right: 15px; }
            .topbar { padding: 15px 20px; justify-content: flex-start; }
            .topbar h2 { display: none; } /* Esconde o título longo no celular */
            .topbar-right { margin-left: auto; }
            .content-area { padding: 15px; padding-bottom: 120px; }
            .modal-content { width: 90%; margin: auto; }
        }
    </style>
</head>
<body>

    <div class="sidebar-overlay" id="overlay" onclick="toggleMenu()"></div>
    
    <?php include 'sidebar.php'; ?>

    <div class="main-content">
        <header class="topbar">
            <div style="display:flex; align-items:center;">
                <button class="menu-toggle" onclick="toggleMenu()"><i class="fas fa-bars"></i></button>
                <h2 style="margin:0; font-size: 18px; color:white;">Gerenciar DNS do Servidor</h2>
            </div>
            <div class="topbar-right">
                <span class="mode-badge"><i class="fas fa-database"></i> MODO: <?php echo defined('MODO_SISTEMA') ? strtoupper(MODO_SISTEMA) : strtoupper($modo_ativo); ?></span>
            </div>
        </header>

        <div class="content-area">
            
            <div class="page-header">
                <h3><i class="fas fa-link"></i> DNS do Servidor (XUI/Xtream)</h3>
                <p style="color:var(--text-muted); margin:0; font-size: 13px;">Altere o DNS ou IP de transmissão. <strong>Cuidado:</strong> Mudar o DNS afeta todas as listas e conexões ativas imediatamente.</p>
            </div>

            <?php echo $mensagem; ?>

            <div class="card-table">
                <table>
                    <thead>
                        <tr>
                            <th>ID do Servidor</th>
                            <th>Nome do Servidor</th>
                            <th>Domínio / DNS</th>
                            <th>Endereço IP</th>
                            <th>Status Nativo</th>
                            <th style="text-align: right;">Ações</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if(empty($servidores)): ?>
                            <tr><td colspan="6" style="text-align:center;">Nenhum servidor encontrado na tabela <?php echo htmlspecialchars($tabela_servidores); ?>.</td></tr>
                        <?php else: foreach ($servidores as $s): 
                            $status_servidor = isset($s['status']) ? (int)$s['status'] : 1;
                            $badge_class = $status_servidor == 1 ? 'bg-success' : 'bg-danger';
                            $badge_text = $status_servidor == 1 ? 'ONLINE' : 'OFFLINE';
                        ?>
                            <tr>
                                <td><span style="color:var(--text-muted); font-weight:bold;">#<?php echo $s['id']; ?></span></td>
                                <td>
                                    <strong style="color: white; font-size: 15px;"><?php echo htmlspecialchars($s['server_name']); ?></strong>
                                </td>
                                <td>
                                    <code style="color: var(--info);"><?php echo htmlspecialchars($s['domain_name'] ?? 'Não definido'); ?></code>
                                </td>
                                <td>
                                    <code><?php echo htmlspecialchars($s['server_ip']); ?></code>
                                </td>
                                <td>
                                    <span class="badge <?php echo $badge_class; ?>"><?php echo $badge_text; ?></span>
                                </td>
                                <td style="text-align: right;">
                                    <button type="button" class="btn-action" style="background:var(--accent);" 
                                        data-id="<?php echo $s['id']; ?>" 
                                        data-name="<?php echo htmlspecialchars($s['server_name'], ENT_QUOTES); ?>" 
                                        data-domain="<?php echo htmlspecialchars($s['domain_name'] ?? '', ENT_QUOTES); ?>" 
                                        data-ip="<?php echo htmlspecialchars($s['server_ip'], ENT_QUOTES); ?>" 
                                        onclick="openEditModal(this)">
                                        <i class="fas fa-edit"></i> Alterar DNS
                                    </button>
                                </td>
                            </tr>
                        <?php endforeach; endif; ?>
                    </tbody>
                </table>
            </div>

        </div>
        <?php include 'rodape.php'; ?>
    </div>

    <div id="modalDNS" class="modal">
        <div class="modal-content">
            <h3 id="modalTitle" style="margin-top:0; color:white;"><i class="fas fa-edit"></i> Alterar DNS do Servidor</h3>
            <p style="color:var(--warning); font-size:12px; margin-bottom: 20px;">
                <i class="fas fa-exclamation-triangle"></i> Informe a URL <strong>exata</strong> que seus clientes usarão (ex: <code>meudns.com</code>).
            </p>
            <form method="POST">
                <input type="hidden" name="action_save" value="1">
                <input type="hidden" name="server_id" id="m_server_id">
                
                <div class="form-group-modal">
                    <label>Nome do Servidor (Server Name)</label>
                    <input type="text" name="server_name" id="m_server_name" required placeholder="Ex: Main Server">
                </div>

                <div class="form-group-modal">
                    <label>Domínio / DNS (Domain Name)</label>
                    <input type="text" name="domain_name" id="m_domain_name" placeholder="Ex: tvsbr.top">
                </div>

                <div class="form-group-modal">
                    <label>Endereço IP Real (Server IP)</label>
                    <input type="text" name="server_ip" id="m_server_ip" required placeholder="Ex: 82.153.205.4">
                </div>
                
                <button type="submit" class="btn-save-modal">SALVAR ALTERAÇÕES</button>
                <button type="button" onclick="closeAllModals()" style="width:100%; background:none; border:none; color:var(--text-muted); margin-top:15px; cursor:pointer; font-weight: bold;">Cancelar</button>
            </form>
        </div>
    </div>

    <script>
        function toggleMenu() { 
            document.getElementById('sidebar').classList.toggle('active'); 
            document.getElementById('overlay').classList.toggle('active'); 
        }

        function toggleSubmenu(id) { 
            var sub = document.getElementById(id); 
            var arrow = document.getElementById('arrow-' + id); 
            if (sub.style.display === "block") { 
                sub.style.display = "none"; 
                if(arrow) arrow.classList.remove('rotate'); 
            } else { 
                sub.style.display = "block"; 
                if(arrow) arrow.classList.add('rotate'); 
            } 
        }
        
        function openEditModal(btn) { 
            document.getElementById('m_server_id').value = btn.getAttribute('data-id'); 
            document.getElementById('m_server_name').value = btn.getAttribute('data-name'); 
            document.getElementById('m_domain_name').value = btn.getAttribute('data-domain'); 
            document.getElementById('m_server_ip').value = btn.getAttribute('data-ip'); 
            document.getElementById('modalDNS').style.display = 'flex'; 
        }

        function closeAllModals() { 
            var modals = document.querySelectorAll('.modal'); 
            for(var i=0; i<modals.length; i++) { 
                modals[i].style.display = 'none'; 
            } 
        }

        // Esconder alertas automaticamente
        setTimeout(function() { 
            try { 
                var alerts = document.querySelectorAll('.alert'); 
                for(var i=0; i<alerts.length; i++) { 
                    alerts[i].style.opacity = '0'; 
                } 
                setTimeout(function(){ 
                    for(var j=0; j<alerts.length; j++) { 
                        alerts[j].style.display = 'none'; 
                    } 
                }, 500); 
            } catch(e) {} 
        }, 4000);
    </script>
    <script src="tema.js"></script>
</body>
</html>
