<?php
session_start();
require_once 'conexao.php';

// --- 1. SEGURANÇA: APENAS ADMIN ---
if (!isset($_SESSION['logado']) || $_SESSION['nivel'] !== 'admin') {
    header("Location: index.php"); // Expulsa se não for admin
    exit;
}

$isAdmin = true;
$usuarioLogado = $_SESSION['usuario'];
$msg = ""; $msg_tipo = "";

// --- 2. 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) { }

// --- 3. AÇÕES (DESBLOQUEAR) ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['acao']) && $_POST['acao'] === 'desbloquear') {
        $id_firewall = (int)$_POST['id'];
        try {
            $connUser->prepare("DELETE FROM firewall WHERE id = ?")->execute([$id_firewall]);
            $msg = "IP Desbloqueado com sucesso!";
            $msg_tipo = "success";
        } catch (Exception $e) {
            $msg = "Erro: " . $e->getMessage();
            $msg_tipo = "danger";
        }
    }
    
    if (isset($_POST['acao']) && $_POST['acao'] === 'limpar_historico') {
        $connUser->query("DELETE FROM firewall WHERE bloqueado = 'nao'");
        $msg = "Histórico limpo!";
        $msg_tipo = "primary";
    }
}

// --- 4. LISTAGEM ---
$lista_ips = $connUser->query("SELECT * FROM firewall ORDER BY bloqueado DESC, data_bloqueio 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, maximum-scale=1.0, user-scalable=no">
    <title>Firewall IPs | <?= 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; }
        body { background: var(--bg-body); color: var(--text-color); font-family: 'Segoe UI', sans-serif; overflow-x: hidden; margin: 0; padding: 0; }
        
        .sidebar { width: 260px; height: 100vh; position: fixed; background: var(--bg-card); padding: 20px; border-right: 1px solid #333; z-index: 1050; overflow-y: auto; transition: 0.3s; }
        .main-content { margin-left: 260px; padding: 20px; transition: 0.3s; }
        
        @media (max-width: 992px) { 
            .sidebar { transform: translateX(-100%); } .sidebar.show { transform: translateX(0); } 
            .main-content { margin-left: 0; padding: 10px 0; } 
            .mobile-toggle { display: block !important; margin-left: 15px; } 
            .card-custom.table-card { border-radius: 0; border-left: none; border-right: none; }
        }

        .nav-link { color: #a6a6b7; padding: 10px 12px; border-radius: 8px; margin-bottom: 2px; display: flex; align-items: center; gap: 10px; text-decoration: none; }
        .nav-link.active, .nav-link:hover { background: var(--primary); color: #fff; }
        .nav-group-title { font-size: 0.75rem; text-transform: uppercase; color: #5e5873; font-weight: 700; margin: 20px 0 10px 12px; }
        
        .card-custom { background: var(--bg-card) !important; border: 1px solid #333; border-radius: 12px; margin-left: 10px; margin-right: 10px; }
        .table-custom { width: 100%; border-collapse: collapse; }
        .table-custom th { background-color: #2b2b40; color: #b9b9c3; font-size: 0.75rem; font-weight: 600; text-transform: uppercase; padding: 15px; border-bottom: 1px solid #444; }
        .table-custom td { padding: 15px; border-bottom: 1px solid #2b2b3c; vertical-align: middle; color: #fff; }
        
        .btn-unlock { background: rgba(40, 199, 111, 0.2); color: #28c76f; border: none; padding: 5px 10px; border-radius: 5px; font-weight: bold; transition: 0.2s; }
        .btn-unlock:hover { background: #28c76f; color: #fff; }
        
        .status-blocked { color: #ea5455; font-weight: bold; background: rgba(234, 84, 85, 0.1); padding: 3px 8px; border-radius: 4px; }
        .status-risk { color: #ff9f43; font-weight: bold; }

        .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.5); z-index: 1040; }
        .overlay.show { display: block; }
    </style>
</head>
<body>

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

<nav class="sidebar" id="sidebar">
    <h4 class="mb-4 fw-bold text-white text-center"><i class="fas fa-tv text-primary"></i> <?= htmlspecialchars($nomePainel) ?></h4>
    <div class="nav flex-column">
        <a href="index.php" class="nav-link"><i class="fas fa-home"></i> Dashboard</a>
        
        <div class="nav-group-title">ADMINISTRATIVO</div>
        <a href="gerenciar_perfis.php" class="nav-link"><i class="fas fa-layer-group"></i> Perfis</a>
        <a href="gerenciar_dns.php" class="nav-link"><i class="fas fa-network-wired"></i> Servidores</a>
        <a href="gerenciar_email.php" class="nav-link"><i class="fas fa-envelope"></i> E-mails</a>
        <a href="gerenciar_ips.php" class="nav-link active"><i class="fas fa-shield-alt"></i> Firewall IPs</a>

        <div class="nav-group-title">MENU</div>
        <a href="revendedores.php" class="nav-link"><i class="fas fa-store"></i> Revendedores</a>
        <a href="clientes.php" class="nav-link"><i class="fas fa-users"></i> Clientes</a>
        <a href="testes.php" class="nav-link"><i class="fas fa-stopwatch"></i> Testes</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="container-fluid">
        <div class="d-flex justify-content-between align-items-center mb-4 flex-wrap gap-2 px-2">
            <h3 class="fw-bold m-0">Gestão de Bloqueios (Firewall)</h3>
            <form method="POST" onsubmit="return confirm('Limpar histórico de IPs não bloqueados?')">
                <input type="hidden" name="acao" value="limpar_historico">
                <button class="btn btn-outline-secondary btn-sm fw-bold"><i class="fas fa-broom me-2"></i>LIMPAR LOGS</button>
            </form>
        </div>

        <?php if($msg): ?><div class="alert alert-<?= $msg_tipo ?> alert-dismissible fade show mx-2"><?= $msg ?><button class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>

        <div class="card card-custom p-0 overflow-hidden shadow-lg mx-2">
            <div class="table-responsive">
                <table class="table-custom">
                    <thead>
                        <tr>
                            <th class="ps-4">Endereço IP</th>
                            <th>Usuário Tentado</th>
                            <th class="text-center">Tentativas</th>
                            <th>Status</th>
                            <th>Última Tentativa</th>
                            <th class="text-end pe-4">Ação</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if(count($lista_ips) > 0): ?>
                            <?php foreach($lista_ips as $row): 
                                $isBlock = ($row['bloqueado'] === 'sim');
                            ?>
                            <tr>
                                <td class="fw-bold font-monospace text-info ps-4"><?= $row['ip'] ?></td>
                                <td>
                                    <span class="text-white-50 small me-1">Login:</span>
                                    <span class="fw-bold text-white"><?= htmlspecialchars($row['usuario']) ?></span>
                                </td>
                                <td class="text-center">
                                    <span class="badge rounded-pill <?= $isBlock ? 'bg-danger' : 'bg-warning text-dark' ?>">
                                        <?= $row['tentativas'] ?> / 5
                                    </span>
                                </td>
                                <td>
                                    <?php if($isBlock): ?>
                                        <span class="status-blocked"><i class="fas fa-ban me-1"></i> BLOQUEADO</span>
                                    <?php else: ?>
                                        <span class="status-risk"><i class="fas fa-exclamation-triangle me-1"></i> Em Risco</span>
                                    <?php endif; ?>
                                </td>
                                <td class="small text-white-50"><?= date('d/m/Y H:i:s', strtotime($row['data_bloqueio'])) ?></td>
                                <td class="text-end pe-4">
                                    <?php if($isBlock): ?>
                                        <form method="POST" class="d-inline">
                                            <input type="hidden" name="acao" value="desbloquear">
                                            <input type="hidden" name="id" value="<?= $row['id'] ?>">
                                            <button type="submit" class="btn-unlock" title="Liberar Acesso">
                                                <i class="fas fa-unlock-alt me-1"></i> DESBLOQUEAR
                                            </button>
                                        </form>
                                    <?php else: ?>
                                        <span class="text-white-50 small">---</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="6" class="text-center py-5 text-muted">
                                    <i class="fas fa-shield-alt fa-3x mb-3"></i><br>
                                    Nenhum bloqueio ou tentativa suspeita registrada.
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</main>

<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'); 
    }
</script>
</body>
</html>
