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

require_once 'conexao.php'; // Traz a variável $connGeral

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

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

        // CAMPOS DO FORMULÁRIO
        $nome      = $_POST['nome'] ?? '';
        $url       = $_POST['url'] ?? '';
        $porta     = $_POST['porta'] ?? '';
        $usuario   = $_POST['usuario'] ?? '';
        $senha     = $_POST['senha'] ?? '';
        $protocolo = $_POST['protocolo'] ?? 'http';
        $atualizar = $_POST['atualizar'] ?? '';

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

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

        // BLOQUEAR / DESBLOQUEAR
        if ($acao === 'toggle_block') {
            // Busca estado atual
            $curr = $connGeral->query("SELECT block FROM painel WHERE id=$id")->fetchColumn();
            $novo_status = ($curr == 'sim') ? 'nao' : 'sim';
            
            $connGeral->prepare("UPDATE painel SET block=? WHERE id=?")->execute([$novo_status, $id]);
            
            $msg = "Status do servidor alterado!"; 
            $msg_tipo = "warning";
        }

        // EXCLUIR SERVIDOR
        if ($acao === 'excluir') {
            $connGeral->prepare("DELETE FROM painel WHERE id=?")->execute([$id]);
            $msg = "Servidor removido!"; 
            $msg_tipo = "danger";
        }

    } catch (PDOException $e) {
        $msg = "Erro no Banco Geral: " . $e->getMessage();
        $msg_tipo = "danger";
    }
}

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

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gerenciar DNS/Servidores | Painel</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 { --bg-body: #151521; --bg-card: #1e1e2d; --primary: #7367f0; }
        body { background: var(--bg-body); color: #fff; font-family: 'Segoe UI', sans-serif; }
        
        .sidebar { width: 260px; height: 100vh; position: fixed; background: #1e1e2d; padding: 20px; border-right: 1px solid #333; z-index: 1000; transition: 0.3s; }
        .main-content { margin-left: 260px; padding: 30px; transition: 0.3s; }
        
        .form-label { color: #ffffff !important; font-weight: 700; margin-bottom: 5px; display: block; }
        .card-custom { background: var(--bg-card); border: 1px solid rgba(255,255,255,0.05); border-radius: 12px; }
        .form-control, .form-select { background: #2b2b40 !important; border: 1px solid #444 !important; color: #fff !important; }
        
        @media (max-width: 768px) { 
            .sidebar { transform: translateX(-100%); } .sidebar.show { transform: translateX(0); }
            .main-content { margin-left: 0; padding: 15px; } .mobile-toggle { display: block !important; }
        }
        .mobile-toggle { display: none; font-size: 1.5rem; color: #fff; background: none; border: none; margin-bottom: 20px; }
        .overlay { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.5); z-index: 999; }
        .overlay.show { display: block; }

        .nav-link { color: #a6a6b7; text-decoration: none; display: flex; align-items: center; gap: 10px; padding: 10px; border-radius: 8px; }
        .nav-link.active { background: var(--primary); color: #fff; }
    </style>
</head>
<body>

<div class="overlay" id="overlay" onclick="toggleMenu()"></div>

<nav class="sidebar" id="sidebar">
    <h4 class="mb-4 fw-bold text-white"><i class="fas fa-tv text-primary"></i> Painel v3.0</h4>
    <div class="nav flex-column gap-2">
        <a href="index.php" class="nav-link text-white"><i class="fas fa-home"></i> Dashboard</a>
        
        <?php if ($_SESSION['nivel'] === 'admin'): ?>
            <div class="mt-2 mb-1 px-3 text-uppercase fw-bold text-light" style="font-size: 0.75rem; opacity: 0.7;">Administração</div>
            <a href="config_geral.php" class="nav-link text-white"><i class="fas fa-cogs text-info"></i> Config. Geral</a>
            <a href="gerenciar_dns.php" class="nav-link active text-white"><i class="fas fa-network-wired text-success"></i> Servidores DNS</a>
            <a href="permissoes_server.php" class="nav-link text-white"><i class="fas fa-server text-warning"></i> Permissões CSP</a>
            <a href="revendedores.php" class="nav-link text-white"><i class="fas fa-store"></i> Revendedores</a>
            <div class="mb-2 border-bottom border-secondary opacity-50"></div>
        <?php else: ?>
            <a href="configuracoes.php" class="nav-link text-white"><i class="fas fa-wallet"></i> Meus Pagamentos</a>
        <?php endif; ?>

        <a href="clientes.php" class="nav-link text-white"><i class="fas fa-users"></i> Clientes</a>
        <a href="sair.php" class="nav-link text-danger mt-4"><i class="fas fa-sign-out-alt"></i> Sair</a>
    </div>
</nav>

<main class="main-content">
    <button class="mobile-toggle" onclick="toggleMenu()"><i class="fas fa-bars"></i></button>

    <div class="d-flex justify-content-between align-items-center mb-4">
        <h3 class="fw-bold">Gerenciar Servidores/DNS</h3>
        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#modalCriar">
            <i class="fas fa-plus me-2"></i> Adicionar Servidor
        </button>
    </div>

    <?php if($msg): ?>
        <div class="alert alert-<?= $msg_tipo ?> alert-dismissible fade show">
            <?= $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-dark table-hover mb-0 align-middle">
                <thead>
                    <tr class="text-muted small text-uppercase">
                        <th class="ps-4">Nome</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 foreach($lista as $item): 
                        $is_block = ($item['block'] == 'sim');
                        $badge = $is_block ? '<span class="badge bg-danger">Bloqueado</span>' : '<span class="badge bg-success">Ativo</span>';
                    ?>
                    <tr>
                        <td class="ps-4 fw-bold"><?= $item['nome'] ?></td>
                        <td><?= $item['url'] ?></td>
                        <td><?= $item['porta'] ?></td>
                        <td class="text-uppercase"><?= $item['protocolo'] ?></td>
                        <td><?= $badge ?></td>
                        <td class="text-end pe-4">
                            <form method="POST" class="d-inline">
                                <input type="hidden" name="acao" value="toggle_block">
                                <input type="hidden" name="id" value="<?= $item['id'] ?>">
                                <button class="btn btn-sm <?= $is_block ? 'btn-secondary' : 'btn-warning' ?> rounded-circle me-1">
                                    <i class="fas <?= $is_block ? 'fa-lock-open' : 'fa-lock' ?>"></i>
                                </button>
                            </form>
                            
                            <button class="btn btn-sm btn-info rounded-circle me-1" onclick='abrirEditar(<?= json_encode($item) ?>)'>
                                <i class="fas fa-pen text-white"></i>
                            </button>

                            <form method="POST" class="d-inline">
                                <input type="hidden" name="acao" value="excluir">
                                <input type="hidden" name="id" value="<?= $item['id'] ?>">
                                <button class="btn btn-sm btn-danger rounded-circle" onclick="return confirm('Tem certeza?')">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </form>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</main>

<div class="modal fade" id="modalCriar" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content bg-dark border-secondary">
            <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 text-white">
                    <h5 class="modal-title" id="modalTitulo">Adicionar Novo Servidor</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Nome do Painel</label>
                            <input type="text" name="nome" id="nome" class="form-control" placeholder="Ex: Servidor Principal" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">URL / DNS</label>
                            <input type="text" name="url" id="url" class="form-control" placeholder="Ex: dns.exemplo.com" required>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-4 mb-3">
                            <label class="form-label">Porta</label>
                            <input type="number" name="porta" id="porta" class="form-control" value="80">
                        </div>
                        <div class="col-4 mb-3">
                            <label class="form-label">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-3">
                            <label class="form-label">Link Atualização</label>
                            <input type="text" name="atualizar" id="atualizar" class="form-control" placeholder="Opcional">
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Usuário Interno (Opcional)</label>
                            <input type="text" name="usuario" id="usuario" class="form-control">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Senha Interna (Opcional)</label>
                            <input type="text" name="senha" id="senha" class="form-control">
                        </div>
                    </div>
                </div>
                
                <div class="modal-footer border-secondary">
                    <button type="submit" class="btn btn-primary w-100 fw-bold">Salvar Dados</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'); }

    // Reutiliza o mesmo modal para criar e editar
    function abrirEditar(dados) {
        document.getElementById('inputAcao').value = 'editar';
        document.getElementById('inputId').value = dados.id;
        document.getElementById('modalTitulo').innerText = '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();
    }
    
    // Reseta o modal quando fechar para não ficar com dados antigos
    document.getElementById('modalCriar').addEventListener('hidden.bs.modal', function () {
        document.getElementById('formDNS').reset();
        document.getElementById('inputAcao').value = 'criar';
        document.getElementById('modalTitulo').innerText = 'Adicionar Novo Servidor';
    });
</script>
</body>
</html>
