<?php
// firewall.php - Painel de Controle Responsivo
session_start();
require_once 'includes/db.php';

// Apenas Admin pode acessar
if (!isset($_SESSION['user_id']) || ($_SESSION['role'] ?? '') !== 'admin' && $_SESSION['user_id'] != 1) { 
    header('Location: dashboard.php'); exit; 
}

// BLOQUEAR IP MANUALMENTE
if (isset($_POST['block_ip'])) {
    $ip = $_POST['ip'];
    $note = $_POST['note'];
    if(!empty($ip)){
        $pdo->prepare("INSERT INTO blocked_ips (ip, notes, date) VALUES (?, ?, ?)")->execute([$ip, $note, time()]);
        header("Location: firewall.php?msg=bloqueado"); exit;
    }
}

// DESBLOQUEAR IP
if (isset($_GET['unblock'])) {
    $id = $_GET['unblock'];
    $pdo->prepare("DELETE FROM blocked_ips WHERE id = ?")->execute([$id]);
    header("Location: firewall.php?msg=desbloqueado"); exit;
}

// ADICIONAR USER AGENT
if (isset($_POST['block_ua'])) {
    $ua = $_POST['ua'];
    $desc = $_POST['desc'];
    $pdo->prepare("INSERT INTO blocked_user_agents (user_agent, description) VALUES (?, ?)")->execute([$ua, $desc]);
    header("Location: firewall.php"); exit;
}
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Gerenciar Firewall</title>
    
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap" rel="stylesheet">

    <style>
        body { 
            background-color: #0f172a; 
            color: #f8fafc; 
            font-family: 'Inter', sans-serif;
            font-size: 0.95rem;
            overflow-x: hidden;
        }

        /* Cartões */
        .card { 
            background-color: #1e293b; 
            border: 1px solid #334155; 
            border-radius: 12px;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        .card-header {
            background-color: transparent;
            border-bottom: 1px solid #334155;
            font-weight: 600;
            text-transform: uppercase;
            font-size: 0.85rem;
            letter-spacing: 0.5px;
            padding: 15px 20px;
        }

        /* Formulários */
        .form-control { 
            background-color: #0f172a; 
            border: 1px solid #334155; 
            color: #fff; 
            border-radius: 8px;
            height: 45px;
        }
        .form-control:focus {
            background-color: #0f172a;
            border-color: #3b82f6;
            color: #fff;
            box-shadow: none;
        }
        label { font-size: 0.85rem; color: #94a3b8; margin-bottom: 5px; }

        /* Tabela */
        .table { margin-bottom: 0; }
        .table th { 
            border-top: none; 
            color: #94a3b8; 
            font-weight: 600; 
            font-size: 0.8rem;
        }
        .table td { 
            vertical-align: middle; 
            color: #cbd5e1; 
            border-top: 1px solid #334155;
        }
        .table-responsive {
            border-radius: 0 0 12px 12px;
        }

        /* Botões Customizados */
        .btn-custom-danger {
            background-color: rgba(239, 68, 68, 0.2);
            color: #ef4444;
            border: 1px solid rgba(239, 68, 68, 0.3);
            font-weight: 600;
        }
        .btn-custom-danger:hover {
            background-color: #ef4444;
            color: #fff;
        }
        
        .btn-custom-warning {
            background-color: rgba(234, 179, 8, 0.2);
            color: #eab308;
            border: 1px solid rgba(234, 179, 8, 0.3);
            font-weight: 600;
        }
        .btn-custom-warning:hover {
            background-color: #eab308;
            color: #000;
        }

        /* ============================================================
           LAYOUT RESPONSIVO (SIDEBAR + CONTEÚDO)
           ============================================================ */
        
        /* PC (Telas Grandes) */
        @media (min-width: 992px) {
            #sidebar { 
                display: block !important; 
                width: 240px; 
                position: fixed; top: 0; left: 0; height: 100vh; 
                z-index: 1000; overflow-y: auto; 
            }
            .right-column { 
                margin-left: 240px; 
                width: calc(100% - 240px); 
                padding: 0; /* Padding controlado internamente */
            }
            .navbar-top { display: none; } /* Oculta navbar extra se tiver */
            .btn-voltar-mobile { display: none; }
        }

        /* CELULAR (Telas Pequenas) */
        @media (max-width: 991px) {
            #sidebar { display: none !important; }
            .right-column { 
                margin-left: 0 !important; 
                width: 100% !important; 
                padding: 0;
            }
            .btn-voltar-mobile {
                display: inline-block;
                margin-right: 10px;
                color: #fff;
                font-size: 1.2rem;
            }
        }

        /* Cabeçalho da Página */
        .page-header {
            background-color: #1e293b;
            padding: 15px 20px;
            border-bottom: 1px solid #334155;
            margin-bottom: 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
    </style>
</head>
<body>

<div class="container-fluid p-0">
    <div class="row no-gutters">
        
        <?php include 'includes/sidebar.php'; ?>

        <div class="right-column">

            <div class="page-header sticky-top">
                <div class="d-flex align-items-center">
                    <a href="dashboard.php" class="btn-voltar-mobile"><i class="fa fa-arrow-left"></i></a>
                    <h4 class="mb-0"><i class="fa-solid fa-shield-virus text-danger mr-2"></i> Firewall</h4>
                </div>
                <a href="dashboard.php" class="btn btn-sm btn-outline-secondary px-3 d-none d-lg-inline-block">
                    <i class="fa fa-arrow-left"></i> Voltar
                </a>
            </div>

            <div class="container-fluid px-4 pb-5">
                <div class="row">
                    
                    <div class="col-12 col-lg-4 mb-4">
                        
                        <div class="card mb-4">
                            <div class="card-header text-danger">
                                <i class="fa-solid fa-ban mr-2"></i> Bloquear IP Manual
                            </div>
                            <div class="card-body">
                                <form method="post">
                                    <div class="form-group">
                                        <label>IP do Invasor</label>
                                        <input type="text" name="ip" class="form-control" placeholder="Ex: 189.23.10.2" required>
                                    </div>
                                    <div class="form-group">
                                        <label>Motivo</label>
                                        <input type="text" name="note" class="form-control" placeholder="Ex: Tentativa de invasão">
                                    </div>
                                    <button type="submit" name="block_ip" class="btn btn-custom-danger btn-block py-2">
                                        BLOQUEAR AGORA
                                    </button>
                                </form>
                            </div>
                        </div>

                        <div class="card">
                            <div class="card-header text-warning">
                                <i class="fa-solid fa-robot mr-2"></i> Bloquear App/Robô
                            </div>
                            <div class="card-body">
                                <form method="post">
                                    <div class="form-group">
                                        <label>Nome do Agente (User-Agent)</label>
                                        <input type="text" name="ua" class="form-control" placeholder="Ex: curl, python, vlc" required>
                                    </div>
                                    <div class="form-group">
                                        <label>Descrição (Opcional)</label>
                                        <input type="text" name="desc" class="form-control" placeholder="Identificação">
                                    </div>
                                    <button type="submit" name="block_ua" class="btn btn-custom-warning btn-block py-2">
                                        BLOQUEAR AGENTE
                                    </button>
                                </form>
                            </div>
                        </div>
                    </div>

                    <div class="col-12 col-lg-8">
                        <div class="card">
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <span><i class="fa-solid fa-list mr-2"></i> IPs Bloqueados</span>
                                <span class="badge badge-danger"><?php echo $pdo->query("SELECT count(*) FROM blocked_ips")->fetchColumn(); ?> Total</span>
                            </div>
                            
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead>
                                        <tr>
                                            <th width="35%">IP Alvo</th>
                                            <th width="40%">Motivo</th>
                                            <th width="25%" class="text-right">Ação</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php
                                        $stmt = $pdo->query("SELECT * FROM blocked_ips ORDER BY id DESC LIMIT 50");
                                        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
                                        
                                        if(count($rows) > 0) {
                                            foreach($rows as $row) {
                                                $data = date("d/m H:i", $row['date']);
                                                echo "<tr>
                                                    <td>
                                                        <span class='text-danger font-weight-bold'>{$row['ip']}</span>
                                                        <div class='small text-muted'>{$data}</div>
                                                    </td>
                                                    <td class='small'>{$row['notes']}</td>
                                                    <td class='text-right'>
                                                        <a href='?unblock={$row['id']}' class='btn btn-sm btn-outline-success' title='Desbloquear'>
                                                            <i class='fa fa-unlock'></i>
                                                        </a>
                                                    </td>
                                                </tr>";
                                            }
                                        } else {
                                            echo "<tr><td colspan='3' class='text-center py-4 text-muted'>Nenhum bloqueio registrado.</td></tr>";
                                        }
                                        ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>

                </div>
            </div>

        </div> </div>
</div>

</body>
</html>