<?php
// gerenciar_ips.php - GERENCIADOR DO FAIL2BAN (COM VISUAL PADRÃO DO PAINEL)
session_start();
error_reporting(0); // Erros ocultados para manter o visual limpo

// Trava o relógio do sistema para o horário oficial do Brasil
date_default_timezone_set('America/Sao_Paulo');

require_once 'config.php';

$pdo = getConexaoAtiva(); // Banco Principal
$pdo_int = getConexaoInterna(); // Banco Local

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

// BLOQUEIO DE SEGURANÇA: SÓ ADMIN ENTRA AQUI
if (!isset($_SESSION['user_id'])) { header("Location: login.php"); exit; }
$role = $_SESSION['user_role'] ?? 'reseller';
if ($role !== 'admin') { header("Location: dashboard.php"); exit; }

$my_id = $_SESSION['user_id'];
$nome_usuario = $_SESSION['username'] ?? 'Usuário';

// --- BUSCA DE PERSONALIZAÇÃO E MODO ---
$nome_painel = 'TOP IPTV';
$cor_primaria = '#007bff';
$modo_ativo = 'interno';

try {
    $modo_ativo = $pdo_int->query("SELECT modo_ativo FROM configuracoes LIMIT 1")->fetchColumn() ?: 'interno';
    $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;
    }
} catch (Exception $e) {}

// --- PROCESSA O DESBLOQUEIO ---
$mensagem = "";
if (isset($_POST['acao']) && $_POST['acao'] == 'desbloquear') {
    $ip_alvo = escapeshellarg(trim($_POST['ip']));
    $regra_alvo = escapeshellarg(trim($_POST['regra']));
    shell_exec("sudo /usr/bin/fail2ban-client set $regra_alvo unbanip $ip_alvo");
    $mensagem = "<div style='padding: 15px; margin-bottom: 20px; border-radius: 8px; background: rgba(40, 167, 69, 0.1); border: 1px solid #28a745; color: #28a745;'>IP <strong>{$_POST['ip']}</strong> desbloqueado com sucesso da regra {$_POST['regra']}!</div>";
}

// --- CORREÇÃO DO ERRO NULL NO PHP 8+ ---
$jails_raw = shell_exec("sudo /usr/bin/fail2ban-client status | grep 'Jail list:' | sed -E 's/^.*:\s+//'");
$jails_raw = $jails_raw ? (string)$jails_raw : ""; 
$jails = array_filter(explode(",", str_replace(" ", "", $jails_raw)));

$bloqueios = [];
if (!empty($jails)) {
    foreach ($jails as $jail) {
        $jail_status = shell_exec("sudo /usr/bin/fail2ban-client status " . escapeshellarg($jail));
        if ($jail_status) {
            preg_match('/Banned IP list:\s+(.*)/', (string)$jail_status, $matches);
            if (isset($matches[1]) && !empty(trim($matches[1]))) {
                $ips = explode(" ", trim($matches[1]));
                foreach ($ips as $ip) {
                    if (!empty($ip)) {
                        $bloqueios[] = ['ip' => $ip, 'regra' => $jail];
                    }
                }
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Segurança & Firewall - <?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; }
        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 */
        .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; }

        /* ESTRUTURA PRINCIPAL E BARRAS */
        .main-content { flex: 1; display: flex; flex-direction: column; overflow-y: auto; width: 100%; position: relative; }
        .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); }
        .menu-toggle { display: none; background: none; border: none; color: white; font-size: 22px; cursor: pointer; padding: 5px; margin-right: 15px; }
        .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); }
        
        .content-area { padding: 20px; flex: 1; }
        
        /* CARD E TABELAS FAIL2BAN */
        .card { background: var(--bg-card); border-radius: 12px; border: 1px solid var(--border-color); padding: 20px; margin-bottom: 20px;}
        .table-custom { width: 100%; border-collapse: collapse; margin-top: 15px;}
        .table-custom th, .table-custom td { padding: 12px 15px; text-align: left; border-bottom: 1px solid var(--border-color); }
        .table-custom th { color: var(--text-muted); font-size: 12px; text-transform: uppercase; }
        .badge-danger { background: rgba(220,53,69,0.1); color: var(--danger); padding: 4px 10px; border-radius: 4px; border: 1px solid var(--danger); font-size: 11px; font-weight: bold;}
        .btn-unlock { background: var(--success); color: white; border: none; padding: 8px 15px; border-radius: 5px; cursor: pointer; font-weight: bold; transition: 0.2s;}
        .btn-unlock:hover { filter: brightness(1.1); }
        
        /* MODO CLARO / ESCURO HERDADO DO DASHBOARD */
        body.light-mode { 
            --bg-dark: #f4f6f9; 
            --bg-sidebar: #ffffff; 
            --bg-card: #ffffff; 
            --text-main: #333333; 
            --text-muted: #6c757d; 
            --border-color: #dee2e6; 
        }
        body.light-mode .topbar h2, body.light-mode .sidebar-header, body.light-mode .menu-toggle, body.light-mode .table-custom td[style*="color:white"] { color: var(--text-main) !important; }
        body.light-mode .menu-item:hover, body.light-mode .menu-item.active { background-color: #f8f9fa; color: var(--accent); }

        @media (max-width: 768px) {
            .menu-toggle { display: block; }
            .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; }
            .topbar { padding: 15px 20px; justify-content: flex-start;}
            .topbar-right { margin-left: auto; }
            .content-area { padding: 15px; padding-bottom: 120px;}
        }
    </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; display:flex; align-items:center;">
                    <i class="fas fa-shield-alt" style="color: #8a94a1; margin-right: 8px; font-size: 20px;"></i> Segurança & Firewall
                </h2>
            </div>
            
            <div class="topbar-right" style="display: flex; align-items: center;">
                <span class="mode-badge"><i class="fas fa-database"></i> <?php echo defined('MODO_SISTEMA') ? strtoupper(MODO_SISTEMA) : strtoupper($modo_ativo); ?></span>
            </div>
        </header>

        <div class="content-area">
            <?= $mensagem; ?>

            <div class="card">
                <h3 style="margin-top:0; color:var(--text-main); display:flex; align-items:center; gap:10px;">
                    <i class="fas fa-ban" style="color:var(--danger);"></i> IPs Banidos (Fail2Ban)
                </h3>
                
                <div style="overflow-x:auto;">
                    <table class="table-custom">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>Endereço IP</th>
                                <th>Regra Violada (Jail)</th>
                                <th style="text-align:center;">Ação</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if(count($bloqueios) > 0): ?>
                                <?php foreach($bloqueios as $index => $b): ?>
                                    <tr>
                                        <td><?= $index + 1; ?></td>
                                        <td style="color:white; font-weight:bold;"><?= htmlspecialchars($b['ip']); ?></td>
                                        <td><span class="badge-danger"><?= htmlspecialchars($b['regra']); ?></span></td>
                                        <td style="text-align:center;">
                                            <form method="POST" action="">
                                                <input type="hidden" name="acao" value="desbloquear">
                                                <input type="hidden" name="ip" value="<?= htmlspecialchars($b['ip']); ?>">
                                                <input type="hidden" name="regra" value="<?= htmlspecialchars($b['regra']); ?>">
                                                <button type="submit" class="btn-unlock" onclick="return confirm('Desbloquear o IP <?= htmlspecialchars($b['ip']); ?>?');">
                                                    <i class="fas fa-unlock"></i> Liberar IP
                                                </button>
                                            </form>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="4" style="text-align:center; padding:30px; color:var(--text-muted);">Nenhum IP bloqueado no momento. O seu servidor está limpo! 🚀</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
                
                <div style="margin-top: 20px; font-size: 12px; color: var(--text-muted);">
                    <strong>Sensores ativos a monitorizar o painel:</strong> 
                    <?php if(!empty($jails)) { foreach($jails as $j) echo "<span style='margin-left:5px; padding:2px 6px; background:var(--bg-sidebar); border:1px solid var(--border-color); border-radius:4px;'>$j</span>"; } else { echo "A aguardar leitura do servidor (verifique permissões sudo)."; } ?>
                </div>
            </div>
        </div>
        
        <?php include 'rodape.php'; ?>
    </div>

    <script>
        // Espia as configurações de tema salvas pelo Dashboard
        document.addEventListener('DOMContentLoaded', () => {
            if (localStorage.getItem('temaPainel') === 'light') {
                document.body.classList.add('light-mode');
            }
        });

        // Função do Menu Mobile
        function toggleMenu() { 
            document.getElementById('sidebar').classList.toggle('active'); 
            document.getElementById('overlay').classList.toggle('active'); 
        }
    </script>
    <script src="tema.js"></script>
</body>
</html>
