<?php
session_start();

// Apenas Admin tem acesso
if (!isset($_SESSION['logado']) || $_SESSION['nivel'] !== 'admin') { 
    header("Location: index.php"); 
    exit; 
}

require_once 'conexao.php'; 

// --- CORREÇÃO DOS ERROS DE VARIÁVEL NO MENU ---
$isAdmin = true;
$usuarioLogado = $_SESSION['usuario'] ?? '';
$total_msg_nao_lidas = 0;
try {
    if (!empty($usuarioLogado)) {
        $stmtMsg = $connUser->prepare("SELECT COUNT(*) FROM chamados_suporte WHERE destinatario = ? AND lida = 'nao'");
        $stmtMsg->execute([$usuarioLogado]);
        $total_msg_nao_lidas = $stmtMsg->fetchColumn();
    }
} catch (Exception $e) { }
// ----------------------------------------------

$msg = "";
$msg_tipo = "";

// --- 1. CONFIGURAÇÕES VISUAIS ---
$nomePainel = "IPTV PANEL"; 
$corPrimaria = "#7367f0"; 
try {
    $conf = $connGeral->query("SELECT NomePainel, TemaPainel FROM site_config LIMIT 1")->fetch(PDO::FETCH_ASSOC);
    if ($conf) {
        if (!empty($conf['NomePainel'])) $nomePainel = $conf['NomePainel'];
        if (!empty($conf['TemaPainel'])) $corPrimaria = $conf['TemaPainel'];
    }
} catch (Exception $e) { }

// --- 2. PROCESSAMENTO DAS AÇÕES ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $acao = $_POST['acao'];
        $id   = $_POST['id'] ?? 0;

        $nome      = $_POST['nome'] ?? '';
        $url       = $_POST['url'] ?? '';
        $porta     = $_POST['porta'] ?? '';
        $usuario   = $_POST['usuario'] ?? '';
        $senha     = $_POST['senha'] ?? '';
        $protocolo = $_POST['protocolo'] ?? 'http';
        $atualizar = $_POST['atualizar'] ?? '';

        if ($acao === 'criar') {
            $sql = "INSERT INTO painel (nome, url, porta, usuario, senha, protocolo, block, atualizar) VALUES (?, ?, ?, ?, ?, ?, 'nao', ?)";
            $connGeral->prepare($sql)->execute([$nome, $url, $porta, $usuario, $senha, $protocolo, $atualizar]);
            $msg = "Servidor <b>$nome</b> adicionado com sucesso!"; $msg_tipo = "success";
        }

        if ($acao === 'editar') {
            $sql = "UPDATE painel SET nome=?, url=?, porta=?, usuario=?, senha=?, protocolo=?, atualizar=? WHERE id=?";
            $connGeral->prepare($sql)->execute([$nome, $url, $porta, $usuario, $senha, $protocolo, $atualizar, $id]);
            $msg = "Dados atualizados com sucesso!"; $msg_tipo = "primary";
        }

        if ($acao === 'toggle_block') {
            $curr = $connGeral->query("SELECT block FROM painel WHERE id=$id")->fetchColumn();
            $novo = ($curr == 'sim') ? 'nao' : 'sim';
            $connGeral->prepare("UPDATE painel SET block=? WHERE id=?")->execute([$novo, $id]);
            $msg = "Status alterado com sucesso!"; $msg_tipo = "warning";
        }

        if ($acao === 'excluir') {
            $connGeral->prepare("DELETE FROM painel WHERE id=?")->execute([$id]);
            $msg = "Servidor removido!"; $msg_tipo = "danger";
        }
    } catch (PDOException $e) { $msg = "Erro: " . $e->getMessage(); $msg_tipo = "danger"; }
}

// --- 3. LISTAR SERVIDORES ---
$lista = $connGeral->query("SELECT * FROM painel ORDER BY id DESC")->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>

<?php include 'tema_global.php'; ?>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gerenciar DNS | <?= htmlspecialchars($nomePainel) ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        :root { 
            --primary: <?= $corPrimaria ?>; 
            --bg-body: #151521; 
            --bg-card: #1e1e2d; 
            --text-color: #d0d2d6;
            --border-color: #2b2b40;
            --overlay-desk: rgba(0, 0, 0, 0.65); 
            --overlay-mob: rgba(0, 0, 0, 0.85); 
        }
        body.light-mode { 
            --bg-body: #f4f5f8; 
            --bg-card: #ffffff; 
            --text-color: #5e5873; 
            --border-color: #ebe9f1; 
            --overlay-desk: rgba(255, 255, 255, 0.1); 
            --overlay-mob: rgba(255, 255, 255, 0);
        }
        body { background: var(--bg-body); color: var(--text-color); font-family: 'Segoe UI', sans-serif; overflow-x: hidden; margin: 0; }
        
        /* Sidebar Restourada */
        .sidebar { width: 260px; height: 100vh; position: fixed; background: var(--bg-card); border-right: 1px solid var(--border-color); z-index: 1050; padding: 20px; overflow-y: auto; transition: 0.3s; }
        .sidebar .nav-link { white-space: nowrap !important; overflow: hidden; text-overflow: ellipsis; display: flex; align-items: center; color: #a6a6b7; padding: 12px 15px; border-radius: 8px; text-decoration: none; margin-bottom: 5px; font-weight: 500; transition: 0.2s; }
        .sidebar .nav-link:hover, .sidebar .nav-link.active { background: var(--primary); color: #fff; box-shadow: 0 4px 15px rgba(0,0,0,0.2); }
        .sidebar .nav-link i.fa-fw { margin-right: 8px; text-align: center; }
        .nav-group-title { font-size: 0.75rem; text-transform: uppercase; color: #5e5873; font-weight: 700; margin: 25px 0 10px 12px; letter-spacing: 1px; }
        
        /* Layout Flexbox Ajustado para forçar Rodapé no Final */
        .main-content { margin-left: 260px; transition: 0.3s; }
        
        .top-header { background: linear-gradient(90deg, var(--bg-card) 0%, var(--overlay-desk) 100%), var(--primary); padding: 15px 30px; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid rgba(255,255,255,0.1); margin-bottom: 30px;}
        .header-title { font-size: 1.3rem; font-weight: 800; color: #fff; text-transform: uppercase; letter-spacing: 1px; margin: 0; }

        /* Elementos Premium */
        .card-custom { background-color: var(--bg-card) !important; border: 1px solid var(--border-color) !important; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 15px rgba(0,0,0,0.05); }
        
        /* Tabela Dinâmica que respeita Tema Claro/Escuro DE VERDADE */
        .table-custom { width: 100%; margin-bottom: 0; border-collapse: separate; border-spacing: 0; background: transparent !important; }
        .table-custom th { background-color: var(--bg-card) !important; border-bottom: 1px solid var(--border-color) !important; color: #a6a6b7 !important; font-size: 0.8rem; text-transform: uppercase; font-weight: 700; padding: 15px; white-space: nowrap; }
        .table-custom td { background-color: var(--bg-card) !important; border-bottom: 1px solid var(--border-color) !important; color: var(--text-color) !important; vertical-align: middle; padding: 15px; font-size: 0.95rem; }
        .table-custom tbody tr:hover td { background-color: rgba(115, 103, 240, 0.08) !important; } /* Efeito sutil ao passar o mouse */
        
        /* Inputs Customizados Dinâmicos */
        .form-control, .form-select { background-color: rgba(0,0,0,0.1) !important; border: 1px solid var(--border-color) !important; color: var(--text-color) !important; border-radius: 8px; padding: 10px 15px; transition: 0.2s; }
        body.light-mode .form-control, body.light-mode .form-select { background-color: rgba(0,0,0,0.03) !important; }
        .form-control:focus, .form-select:focus { border-color: var(--primary) !important; box-shadow: 0 0 0 0.25rem rgba(115, 103, 240, 0.25) !important; background-color: transparent !important;}

        @media (max-width: 992px) { 
            .sidebar { transform: translateX(-100%); } 
            .sidebar.show { transform: translateX(0); box-shadow: 5px 0 30px rgba(0,0,0,0.9); } 
            .main-content { margin-left: 0; } 
            .mobile-toggle { display: block !important; margin-right: 15px; } 
            .top-header { flex-direction: row; padding: 15px 20px; background: linear-gradient(var(--overlay-mob), var(--overlay-mob)), var(--primary); }
        }
        .mobile-toggle { display: none; background: none; border: none; color: #fff; font-size: 1.5rem; }
        .overlay { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.7); z-index: 1040; backdrop-filter: blur(3px); }
        .overlay.show { display: block; }
    </style>
</head>
<body>
<?php include 'menu.php'; ?>
<div class="overlay" id="overlay" onclick="toggleMenu()"></div>

<!-- Aplicamos d-flex, flex-column e min-vh-100 para forçar o Rodapé no chão -->
<main class="main-content d-flex flex-column min-vh-100">
    <div class="top-header">
        <div class="d-flex align-items-center">
            <button class="mobile-toggle" onclick="toggleMenu()"><i class="fas fa-bars"></i></button>
            <div class="header-title"><i class="fas fa-network-wired me-2"></i> Servidores DNS</div>
        </div>
        <button class="btn btn-light fw-bold px-4 shadow-sm rounded-pill" data-bs-toggle="modal" data-bs-target="#modalCriar" style="letter-spacing: 0.5px;">
            <i class="fas fa-plus me-1"></i> NOVO
        </button>
    </div>

    <!-- Container flex-grow-1 estica o meio, empurrando o Rodapé para baixo -->
    <div class="container-fluid p-3 p-md-4 flex-grow-1">
        
        <?php if($msg): ?>
            <div class="alert alert-<?= $msg_tipo ?> alert-dismissible fade show border-0 shadow-sm fw-bold">
                <?= $msg ?>
                <button class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <div class="card card-custom">
            <div class="table-responsive">
                <table class="table table-custom align-middle">
                    <thead>
                        <tr>
                            <th class="ps-4">Nome do Servidor</th>
                            <th>URL / IP</th>
                            <th>Porta</th>
                            <th>Protocolo</th>
                            <th>Status</th>
                            <th class="text-end pe-4">Ações</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if(empty($lista)): ?>
                            <tr><td colspan="6" class="text-center py-5 text-muted">Nenhum servidor cadastrado.</td></tr>
                        <?php else: foreach($lista as $item): 
                            $is_block = ($item['block'] == 'sim');
                        ?>
                        <tr>
                            <td class="ps-4 fw-bold"><?= htmlspecialchars($item['nome']) ?></td>
                            <td class="text-info"><?= htmlspecialchars($item['url']) ?></td>
                            <td><span class="badge bg-dark border border-secondary shadow-sm px-2 py-1 fs-6 text-white"><?= htmlspecialchars($item['porta']) ?></span></td>
                            <td class="text-uppercase small fw-bold opacity-75"><?= htmlspecialchars($item['protocolo']) ?></td>
                            <td>
                                <?= $is_block ? 
                                '<span class="badge bg-danger bg-opacity-10 text-danger border border-danger px-2 py-1">Bloqueado</span>' : 
                                '<span class="badge bg-success bg-opacity-10 text-success border border-success px-2 py-1">Ativo</span>' ?>
                            </td>
                            <td class="text-end pe-4">
                                <div class="d-flex gap-2 justify-content-end">
                                    <form method="POST" class="m-0">
                                        <input type="hidden" name="acao" value="toggle_block">
                                        <input type="hidden" name="id" value="<?= $item['id'] ?>">
                                        <button class="btn btn-sm btn-outline-<?= $is_block ? 'success' : 'warning' ?> shadow-sm rounded-3" title="<?= $is_block ? 'Desbloquear' : 'Bloquear' ?>">
                                            <i class="fas <?= $is_block ? 'fa-lock-open' : 'fa-lock' ?>"></i>
                                        </button>
                                    </form>
                                    <button class="btn btn-sm btn-outline-info shadow-sm rounded-3" onclick='abrirEditar(<?= json_encode($item) ?>)' title="Editar">
                                        <i class="fas fa-pen"></i>
                                    </button>
                                    <form method="POST" class="m-0">
                                        <input type="hidden" name="acao" value="excluir">
                                        <input type="hidden" name="id" value="<?= $item['id'] ?>">
                                        <button class="btn btn-sm btn-outline-danger shadow-sm rounded-3" onclick="return confirm('Tem certeza que deseja excluir este servidor?')" title="Excluir">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
        
    </div>
    
    <!-- Rodapé protegido no chão pela div mt-auto (Margin-Top: Auto) -->
    <div class="mt-auto w-100">
        <?php include 'rodape.php'; ?>
    </div>
    
</main>

<div class="modal fade" id="modalCriar" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content border-secondary" style="background-color: var(--bg-card);">
            <form method="POST" id="formDNS">
                <input type="hidden" name="acao" value="criar" id="inputAcao">
                <input type="hidden" name="id" id="inputId">
                <div class="modal-header border-secondary">
                    <h5 class="modal-title fw-bold" style="color: var(--text-color);" id="modalTitulo"><i class="fas fa-network-wired me-2 text-primary"></i> Adicionar Novo Servidor</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" style="filter: invert(1) grayscale(100%) brightness(200%);"></button>
                </div>
                <div class="modal-body p-4">
                    <div class="row g-3">
                        <div class="col-md-6 mb-2">
                            <label class="form-label small fw-bold" style="color: var(--text-color); opacity: 0.7;">NOME DO PAINEL</label>
                            <input type="text" name="nome" id="nome" class="form-control" placeholder="Ex: Servidor BR" required>
                        </div>
                        <div class="col-md-6 mb-2">
                            <label class="form-label small fw-bold" style="color: var(--text-color); opacity: 0.7;">URL / DNS</label>
                            <input type="text" name="url" id="url" class="form-control" placeholder="Ex: seudominio.com" required>
                        </div>
                    </div>
                    <div class="row g-3">
                        <div class="col-4 mb-2">
                            <label class="form-label small fw-bold" style="color: var(--text-color); opacity: 0.7;">PORTA</label>
                            <input type="number" name="porta" id="porta" class="form-control" value="80" required>
                        </div>
                        <div class="col-4 mb-2">
                            <label class="form-label small fw-bold" style="color: var(--text-color); opacity: 0.7;">PROTOCOLO</label>
                            <select name="protocolo" id="protocolo" class="form-select">
                                <option value="http">HTTP</option>
                                <option value="https">HTTPS</option>
                            </select>
                        </div>
                        <div class="col-4 mb-2">
                            <label class="form-label small fw-bold" style="color: var(--text-color); opacity: 0.7;">LINK ATUALIZAÇÃO</label>
                            <input type="text" name="atualizar" id="atualizar" class="form-control" placeholder="Opcional">
                        </div>
                    </div>
                    <hr class="border-secondary my-4">
                    <div class="row g-3">
                        <div class="col-md-6 mb-2">
                            <label class="form-label small fw-bold" style="color: var(--text-color); opacity: 0.7;">USUÁRIO INTERNO (API)</label>
                            <input type="text" name="usuario" id="usuario" class="form-control" placeholder="Opcional">
                        </div>
                        <div class="col-md-6 mb-2">
                            <label class="form-label small fw-bold" style="color: var(--text-color); opacity: 0.7;">SENHA INTERNA (API)</label>
                            <input type="text" name="senha" id="senha" class="form-control" placeholder="Opcional">
                        </div>
                    </div>
                </div>
                <div class="modal-footer border-secondary">
                    <button type="submit" class="btn btn-primary w-100 fw-bold py-2 shadow-sm rounded-pill">SALVAR SERVIDOR</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    function toggleMenu() { 
        document.getElementById('sidebar').classList.toggle('show'); 
        document.getElementById('overlay').classList.toggle('show'); 
    }
    
    function abrirEditar(dados) {
        document.getElementById('inputAcao').value = 'editar'; 
        document.getElementById('inputId').value = dados.id;
        document.getElementById('modalTitulo').innerHTML = '<i class="fas fa-pen me-2 text-warning"></i> Editar Servidor';
        document.getElementById('nome').value = dados.nome; 
        document.getElementById('url').value = dados.url;
        document.getElementById('porta').value = dados.porta; 
        document.getElementById('protocolo').value = dados.protocolo;
        document.getElementById('atualizar').value = dados.atualizar; 
        document.getElementById('usuario').value = dados.usuario;
        document.getElementById('senha').value = dados.senha; 
        new bootstrap.Modal(document.getElementById('modalCriar')).show();
    }
</script>
</body>
</html>
