<?php
session_start();
require_once 'conexao.php'; // Traz $connUser e $connGeral

// =======================================================================
// 1. SISTEMA DE SEGURANÃ‡A (FIREWALL IP)
// =======================================================================
$ip = $_SERVER['REMOTE_ADDR'];

// Cria a tabela de firewall se nÃ£o existir
try {
    $connUser->exec("CREATE TABLE IF NOT EXISTS firewall (
        id INT AUTO_INCREMENT PRIMARY KEY,
        ip VARCHAR(50),
        usuario VARCHAR(100),
        tentativas INT DEFAULT 0,
        bloqueado ENUM('sim','nao') DEFAULT 'nao',
        data_bloqueio TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    )");
} catch (Exception $e) {}

// Verifica se o IP jÃ¡ estÃ¡ bloqueado
$stmtBlock = $connUser->prepare("SELECT id FROM firewall WHERE ip = ? AND bloqueado = 'sim' LIMIT 1");
$stmtBlock->execute([$ip]);
if ($stmtBlock->rowCount() > 0) {
    die("
    <body style='background:#151521;color:white;font-family:sans-serif;text-align:center;display:flex;align-items:center;justify-content:center;height:100vh;flex-direction:column;'>
        <h1 style='color:#ea5455;font-size:3rem;'>ðŸš«</h1>
        <h2 style='text-transform:uppercase;'>IP BLOQUEADO</h2>
        <p>Muitas tentativas de acesso falhas.</p>
        <p style='color:#a6a6b7;'>IP: <strong>$ip</strong></p>
        <p>Contate o administrador para liberar.</p>
    </body>");
}
// =======================================================================

// --- 2. BUSCA CONFIGURAÃ‡Ã•ES DO SITE ---
$nomePainel = "IPTV PANEL"; 
$corPrimaria = "#7367f0"; 
try {
    $conf = $connGeral->query("SELECT NomePainel, TemaPainel FROM site_config WHERE id=1 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) { }

$erro = "";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $usuario = trim($_POST['usuario']);
    $senha = trim($_POST['senha']);
    $loginSucesso = false; 

    try {
        // TENTA ADMIN
        $stmt = $connUser->prepare("SELECT id, usuario, senha FROM admin WHERE usuario = ? LIMIT 1");
        $stmt->execute([$usuario]);
        $user = $stmt->fetch();

        if ($user && $senha === $user['senha']) {
            $_SESSION['logado'] = true;
            $_SESSION['usuario'] = $user['usuario'];
            $_SESSION['nivel'] = 'admin';
            $loginSucesso = true;
            $connUser->prepare("DELETE FROM firewall WHERE ip = ?")->execute([$ip]); // Limpa erros
            header("Location: index.php"); exit;
        }

        // TENTA REVENDA
        if (!$loginSucesso) {
            $stmt = $connUser->prepare("SELECT id, usuario, senha FROM rev WHERE usuario = ? LIMIT 1");
            $stmt->execute([$usuario]);
            $rev = $stmt->fetch();

            if ($rev && $senha === $rev['senha']) {
                $_SESSION['logado'] = true;
                $_SESSION['usuario'] = $rev['usuario'];
                $_SESSION['nivel'] = 'revenda';
                $loginSucesso = true;
                $connUser->prepare("DELETE FROM firewall WHERE ip = ?")->execute([$ip]); // Limpa erros
                header("Location: index.php"); exit;
            }
        }

        // --- LÃ“GICA DE FALHA COM AVISO DE CONTAGEM ---
        if (!$loginSucesso) {
            
            // Verifica quantas vezes esse IP jÃ¡ errou
            $chk = $connUser->prepare("SELECT id, tentativas FROM firewall WHERE ip = ?");
            $chk->execute([$ip]);
            $reg = $chk->fetch(PDO::FETCH_ASSOC);

            if ($reg) {
                $novas_tentativas = $reg['tentativas'] + 1;
                
                if ($novas_tentativas >= 5) {
                    // BLOQUEIA SE CHEGAR A 5
                    $connUser->prepare("UPDATE firewall SET tentativas = ?, bloqueado = 'sim', usuario = ? WHERE ip = ?")->execute([$novas_tentativas, $usuario, $ip]);
                    // ForÃ§a o refresh para cair na tela de bloqueio
                    header("Refresh:0"); exit;
                } else {
                    // AUMENTA CONTADOR E AVISA
                    $connUser->prepare("UPDATE firewall SET tentativas = ?, usuario = ? WHERE ip = ?")->execute([$novas_tentativas, $usuario, $ip]);
                    $restantes = 5 - $novas_tentativas;
                    $erro = "Senha incorreta! <br>Tentativa <b>$novas_tentativas de 5</b>. <br>Restam <b>$restantes</b> chances antes do bloqueio de IP.";
                }
            } else {
                // PRIMEIRO ERRO
                $connUser->prepare("INSERT INTO firewall (ip, usuario, tentativas, bloqueado) VALUES (?, ?, 1, 'nao')")->execute([$ip, $usuario]);
                $erro = "Senha incorreta! <br>Tentativa <b>1 de 5</b>.";
            }
        }

    } catch (PDOException $e) { $erro = "Erro no sistema."; }
}
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login | <?= 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; 
        }
        body { background-color: var(--bg-body); color: #fff; height: 100vh; display: flex; align-items: center; justify-content: center; font-family: 'Segoe UI', sans-serif; overflow: hidden; }
        
        .login-card { background: var(--bg-card); border: 1px solid rgba(255,255,255,0.1); border-radius: 15px; width: 100%; max-width: 400px; padding: 40px; box-shadow: 0 10px 30px rgba(0,0,0,0.5); }
        .form-label { color: #ffffff !important; font-weight: 700; text-transform: uppercase; font-size: 0.85rem; letter-spacing: 1px; margin-bottom: 8px; }
        .form-control { background: #2b2b40 !important; border: 1px solid #444 !important; color: #ffffff !important; height: 55px; font-size: 1rem; font-weight: 500; }
        .form-control::placeholder { color: rgba(255, 255, 255, 0.5) !important; font-weight: 400; }
        .input-group-text { background: #2b2b40 !important; border: 1px solid #444 !important; color: var(--primary) !important; cursor: pointer; padding: 0 15px; }
        .btn-login { background: var(--primary); border: none; height: 55px; font-weight: bold; font-size: 1.1rem; transition: 0.3s; color: #fff; text-transform: uppercase; }
        .btn-login:hover { filter: brightness(1.2); transform: translateY(-2px); color: #fff; }
        .logo-icon { font-size: 3.5rem; color: var(--primary); margin-bottom: 15px; text-shadow: 0 0 15px var(--primary); }
    </style>
</head>
<body>

<div class="login-card text-center">
    <i class="fas fa-tv logo-icon"></i>
    <h3 class="fw-bold mb-1 text-white"><?= htmlspecialchars($nomePainel) ?></h3>
    <p class="text-white-50 mb-4 small">Acesse seu painel de controle</p>

    <?php if($erro): ?>
        <div class="alert alert-danger border-0 small p-3 mb-3 text-start">
            <i class="fas fa-exclamation-triangle me-2"></i> <?= $erro ?>
        </div>
    <?php endif; ?>

    <form method="POST">
        <div class="mb-3 text-start">
            <label class="form-label">UsuÃ¡rio</label>
            <div class="input-group">
                <span class="input-group-text"><i class="fas fa-user"></i></span>
                <input type="text" name="usuario" class="form-control" required placeholder="Seu login aqui">
            </div>
        </div>

        <div class="mb-4 text-start">
            <label class="form-label">Senha</label>
            <div class="input-group">
                <span class="input-group-text"><i class="fas fa-lock"></i></span>
                <input type="password" name="senha" id="inputSenha" class="form-control" required placeholder="Sua senha aqui">
                <span class="input-group-text" onclick="togglePassword()">
                    <i class="fas fa-eye" id="iconEye"></i>
                </span>
            </div>
        </div>

        <button type="submit" class="btn btn-primary w-100 btn-login">ENTRAR NO PAINEL</button>
    </form>
</div>

<script>
    function togglePassword() {
        const input = document.getElementById('inputSenha');
        const icon = document.getElementById('iconEye');
        if (input.type === "password") { input.type = "text"; icon.classList.replace('fa-eye', 'fa-eye-slash'); } 
        else { input.type = "password"; icon.classList.replace('fa-eye-slash', 'fa-eye'); }
    }
</script>

</body>
</html>
