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

// --- TRAVA DE SEGURANÇA TOTAL ---
if (!isset($_SESSION['logado']) || $_SESSION['logado'] !== true) {
    header("Location: login.php"); exit;
}

$isAdmin = (strtolower($_SESSION['nivel']) === 'admin');
$usuarioLogado = $_SESSION['usuario'];

// --- PROTEÇÃO EXTRA: SÓ ADMIN ACESSA ESTA PÁGINA ---
if (!$isAdmin) {
    die("<script>alert('Acesso negado! Apenas administradores podem gerenciar bloqueios.'); window.location.href='index.php';</script>");
}

// --- CONFIGS VISUAIS (Para manter o padrão do topo) ---
$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) { }

// =========================================================================
// PROCESSA AÇÕES DE LIBERAÇÃO
// =========================================================================
$msg_acao = "";
$msg_tipo = "success";

if (isset($_GET['acao']) && isset($_GET['valor'])) {
    $valor = $_GET['valor'];
    
    try {
        if ($_GET['acao'] === 'liberar_ip_banido') {
            $connUser->prepare("DELETE FROM ip_bloqueados_teste WHERE ip = ?")->execute([$valor]);
            $connUser->prepare("DELETE FROM log_ip_testes WHERE ip = ?")->execute([$valor]);
            $msg_acao = "IP <b>$valor</b> liberado e histórico zerado com sucesso!";
        }
        elseif ($_GET['acao'] === 'zerar_wpp') {
            $connUser->prepare("DELETE FROM log_ip_testes WHERE whatsapp = ?")->execute([$valor]);
            $msg_acao = "Limites do WhatsApp <b>$valor</b> zerados com sucesso!";
        }
    } catch (Exception $e) {
        $msg_acao = "Erro ao processar: " . $e->getMessage();
        $msg_tipo = "danger";
    }
}

// =========================================================================
// BUSCA DOS DADOS NO BANCO
// =========================================================================
try {
    $ips_banidos = $connUser->query("SELECT * FROM ip_bloqueados_teste ORDER BY data_bloqueio DESC")->fetchAll(PDO::FETCH_ASSOC);
    
    $wpps_limite = $connUser->query("
        SELECT whatsapp, COUNT(*) as qtd_testes, MAX(data_registro) as ultimo_teste 
        FROM log_ip_testes 
        WHERE whatsapp IS NOT NULL AND whatsapp != '' 
        GROUP BY whatsapp 
        ORDER BY qtd_testes DESC
    ")->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    die("Erro ao carregar dados: " . $e->getMessage());
}

$badgeTopo = '<span style="background: rgba(234, 84, 85, 0.2); color: #ea5455; border: 1px solid rgba(234, 84, 85, 0.5); padding: 4px 10px; border-radius: 50px; font-size: 0.7rem; font-weight: bold; letter-spacing: 1px; white-space: nowrap;"><i class="fas fa-shield-alt me-1"></i> SEGURANÇA</span>';
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gerenciar Bloqueios | <?= 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">
    
    <?php @include 'tema_global.php'; ?>

    <style>
        :root { --primary: <?= $corPrimaria ?>; --bg-body: #151521; --bg-card: #1e1e2d; --text-color: #d0d2d6; --border-color: #2b2b40; }
        
        body { background-color: var(--bg-body); color: var(--text-color); font-family: 'Segoe UI', sans-serif; overflow-x: hidden; margin: 0; }
        
        ::-webkit-scrollbar { width: 8px; height: 8px; }
        ::-webkit-scrollbar-track { background: var(--bg-body); }
        ::-webkit-scrollbar-thumb { background: #444; border-radius: 4px; }
        ::-webkit-scrollbar-thumb:hover { background: var(--primary); }

        .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: transform 0.3s ease, box-shadow 0.3s ease; }
        .nav-link { color: #a6a6b7; padding: 12px 15px; border-radius: 8px; display: flex; align-items: center; gap: 12px; text-decoration: none; margin-bottom: 5px; font-weight: 500; transition: 0.2s; }
        .nav-link:hover, .nav-link.active { background: var(--primary); color: #fff; box-shadow: 0 4px 15px rgba(0,0,0,0.2); }
        .nav-group-title { font-size: 0.75rem; text-transform: uppercase; color: #5e5873; font-weight: 700; margin: 25px 0 10px 12px; letter-spacing: 1px; }
        
        .main-content { margin-left: 260px; padding: 0; transition: 0.3s; min-height: 100vh; }
        
        /* HEADER - LAYOUT CORRIGIDO */
        .top-header { background: linear-gradient(90deg, var(--bg-card) 0%, var(--primary) 100%); padding: 15px 30px; display: flex; align-items: center; justify-content: space-between; box-shadow: 0 2px 10px rgba(0,0,0,0.3); margin-bottom: 30px; border-bottom: 1px solid rgba(255,255,255,0.1); }
        .header-title { font-size: 1.5rem; font-weight: 800; color: #fff; letter-spacing: 1px; text-transform: uppercase; margin: 0; text-align: center; flex-grow: 1; }
        .mobile-toggle { display: none; color: #fff; font-size: 1.5rem; background: none; border: none; cursor: pointer; padding: 0; }
        .ghost-spacer { display: none; width: 24px; } /* Espaçador invisível para manter o título perfeitamente no centro no celular */
        
        .content-wrapper { padding: 0 30px 30px 30px; position: relative; z-index: 10; }
        
        .section-card { background: var(--bg-card); border-radius: 12px; border: 1px solid var(--border-color); margin-bottom: 25px; overflow: hidden; width: 100%; box-shadow: 0 4px 6px rgba(0,0,0,0.1); }
        .section-header { padding: 15px 20px; border-bottom: 1px solid var(--border-color); font-weight: 600; font-size: 1.1rem; color: #fff; display: flex; justify-content: space-between; align-items: center; }
        .section-body { padding: 0; }
        
        .table-responsive { overflow-x: auto; -webkit-overflow-scrolling: touch; width: 100%; }
        .table-custom { width: 100%; border-collapse: collapse; min-width: 500px; margin-bottom: 0; }
        .table-custom th { text-align: left; padding: 15px; color: #b9b9c3; font-size: 0.8rem; text-transform: uppercase; font-weight: 600; border-bottom: 1px solid var(--border-color); background: #252535; white-space: nowrap; }
        .table-custom td { padding: 15px; border-bottom: 1px solid var(--border-color); font-size: 0.9rem; color: #fff; vertical-align: middle; white-space: nowrap; }
        
        .status-badge { padding: 4px 10px; border-radius: 4px; font-size: 0.75rem; font-weight: 700; text-transform: uppercase; }
        .badge-danger-custom { background: rgba(234, 84, 85, 0.2); color: #ea5455; border: 1px solid rgba(234, 84, 85, 0.2); }
        .badge-warning-custom { background: rgba(255, 159, 67, 0.2); color: #ff9f43; border: 1px solid rgba(255, 159, 67, 0.2); }
        .badge-info-custom { background: rgba(0, 207, 232, 0.2); color: #00cfe8; border: 1px solid rgba(0, 207, 232, 0.2); }

        .btn-custom-outline { background: transparent; border: 1px solid; font-weight: 600; padding: 6px 12px; border-radius: 6px; transition: 0.2s; font-size: 0.8rem; text-decoration: none; display: inline-block; }
        .btn-outline-success { color: #28c76f; border-color: #28c76f; }
        .btn-outline-success:hover { background: #28c76f; color: #fff; }
        .btn-outline-warning { color: #ff9f43; border-color: #ff9f43; }
        .btn-outline-warning:hover { background: #ff9f43; color: #fff; }

        .overlay { display: none; position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; background: rgba(0,0,0,0.7); z-index: 1040; backdrop-filter: blur(3px); }
        .overlay.show { display: block; }

        @media (max-width: 992px) { 
            .sidebar { transform: translateX(-100%); box-shadow: none; z-index: 1050; } 
            .sidebar.show { transform: translateX(0); box-shadow: 5px 0 30px rgba(0,0,0,0.9); } 
            .main-content { margin-left: 0; width: 100%; }
            .content-wrapper { padding: 0 15px 30px 15px; }
            .top-header { padding: 15px 20px; }
            .mobile-toggle { display: block !important; }
            .ghost-spacer { display: block !important; }
            .header-title { font-size: 1.1rem; padding: 0 10px; } /* Fonte menor no celular para não quebrar */
        }
    </style>
</head>
<body>

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

<main class="main-content">
    <div class="top-header">
        <button class="mobile-toggle" onclick="toggleMenu()"><i class="fas fa-bars"></i></button>
        
        <div class="header-title">CONTROLE ANTI-FRAUDE</div>
        
        <div class="d-none d-lg-block">
            <?= $badgeTopo ?>
        </div>
        
        <!-- Elemento fantasma usado apenas no celular para equilibrar o botão do menu e manter o título centralizado -->
        <div class="ghost-spacer d-lg-none"></div>
    </div>

    <div class="content-wrapper">
        
        <?php if(!empty($msg_acao)): ?>
            <div class="alert alert-<?= $msg_tipo ?> border-0 text-white fw-bold mb-4" style="background: <?= $msg_tipo == 'success' ? 'rgba(40, 199, 111, 0.2)' : 'rgba(234, 84, 85, 0.2)' ?>; border-left: 4px solid <?= $msg_tipo == 'success' ? '#28c76f' : '#ea5455' ?> !important;">
                <i class="fas <?= $msg_tipo == 'success' ? 'fa-check-circle' : 'fa-exclamation-triangle' ?> me-2"></i> <?= $msg_acao ?>
            </div>
        <?php endif; ?>

        <div class="row">
            <!-- TABELA 1: IPs BANIDOS -->
            <div class="col-xl-6">
                <div class="section-card">
                    <div class="section-header">
                        <span><i class="fas fa-ban text-danger me-2"></i> Lista Negra de IPs</span>
                        <span class="status-badge badge-danger-custom"><?= count($ips_banidos) ?> Bloqueados</span>
                    </div>
                    <div class="section-body table-responsive">
                        <table class="table-custom">
                            <thead>
                                <tr>
                                    <th>Endereço IP</th>
                                    <th>Motivo</th>
                                    <th>Data</th>
                                    <th class="text-end">Ação</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if(empty($ips_banidos)): ?>
                                    <tr><td colspan="4" class="text-center text-muted py-4">Nenhum IP bloqueado no momento.</td></tr>
                                <?php else: foreach($ips_banidos as $b): ?>
                                    <tr>
                                        <td class="fw-bold" style="color: #00cfe8;"><?= htmlspecialchars($b['ip']) ?></td>
                                        <td class="small text-danger"><?= htmlspecialchars($b['motivo']) ?></td>
                                        <td><?= date('d/m/Y H:i', strtotime($b['data_bloqueio'])) ?></td>
                                        <td class="text-end">
                                            <a href="?acao=liberar_ip_banido&valor=<?= urlencode($b['ip']) ?>" class="btn-custom-outline btn-outline-success" onclick="return confirm('Tem certeza que deseja liberar este IP?')">
                                                <i class="fas fa-unlock me-1"></i> Liberar
                                            </a>
                                        </td>
                                    </tr>
                                <?php endforeach; endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- TABELA 2: WHATSAPP LIMITES -->
            <div class="col-xl-6">
                <div class="section-card">
                    <div class="section-header">
                        <span><i class="fab fa-whatsapp text-success me-2"></i> Limites de WhatsApp</span>
                    </div>
                    <div class="section-body table-responsive">
                        <table class="table-custom">
                            <thead>
                                <tr>
                                    <th>Número</th>
                                    <th>Consumo</th>
                                    <th>Último Teste</th>
                                    <th class="text-end">Ação</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if(empty($wpps_limite)): ?>
                                    <tr><td colspan="4" class="text-center text-muted py-4">Nenhum registro no momento.</td></tr>
                                <?php else: foreach($wpps_limite as $w): 
                                    $isLimit = $w['qtd_testes'] >= 3;
                                ?>
                                    <tr>
                                        <td class="fw-bold text-white"><?= htmlspecialchars($w['whatsapp']) ?></td>
                                        <td>
                                            <span class="status-badge <?= $isLimit ? 'badge-danger-custom' : 'badge-info-custom' ?>">
                                                <?= $w['qtd_testes'] ?> / 3 Usados
                                            </span>
                                        </td>
                                        <td><?= date('d/m/Y H:i', strtotime($w['ultimo_teste'])) ?></td>
                                        <td class="text-end">
                                            <a href="?acao=zerar_wpp&valor=<?= urlencode($w['whatsapp']) ?>" class="btn-custom-outline btn-outline-warning" onclick="return confirm('Zerar histórico deste número?')">
                                                <i class="fas fa-sync-alt me-1"></i> Zerar
                                            </a>
                                        </td>
                                    </tr>
                                <?php endforeach; endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

    </div>
</main>

<!-- Overlay para menu mobile -->
<div class="overlay" id="overlay" onclick="toggleMenu()"></div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    function toggleMenu() { 
        const sidebar = document.querySelector('.sidebar');
        const overlay = document.getElementById('overlay');
        if(sidebar && overlay) {
            sidebar.classList.toggle('show'); 
            overlay.classList.toggle('show'); 
        }
    }
</script>
</body>
</html>
