<?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.05); border-radius: 20px; width: 100%; max-width: 400px; padding: 50px 40px; box-shadow: 0 15px 35px rgba(0,0,0,0.6); }
        .logo-icon { font-size: 3.5rem; color: var(--primary); margin-bottom: 15px; text-shadow: 0 0 20px rgba(115, 103, 240, 0.4); }
        
        /* Estilo Material Underline */
        .form-floating-custom { position: relative; margin-bottom: 30px; }
        .form-floating-custom input { 
            width: 100%; 
            background: transparent; 
            border: none; 
            border-bottom: 2px solid #444; 
            color: #fff; 
            font-size: 1.1rem; 
            padding: 10px 40px 5px 35px; /* EspaÃ§o para o Ã­cone e pro olho */
            transition: all 0.3s ease; 
        }
        .form-floating-custom input:focus { outline: none; border-bottom: 2px solid var(--primary); }
        .form-floating-custom input::placeholder { color: transparent; }
        
        /* --- A VACINA CONTRA O FUNDO BRANCO DO CHROME --- */
        input:-webkit-autofill,
        input:-webkit-autofill:hover, 
        input:-webkit-autofill:focus, 
        input:-webkit-autofill:active {
            -webkit-box-shadow: 0 0 0 30px var(--bg-card) inset !important;
            -webkit-text-fill-color: #fff !important;
            transition: background-color 5000s ease-in-out 0s;
        }
        /* ------------------------------------------------ */

        .form-floating-custom label { 
            position: absolute; 
            top: 10px; 
            left: 35px; 
            color: #a6a6b7; 
            font-size: 1rem; 
            transition: all 0.3s ease; 
            pointer-events: none; 
        }
        
        /* A mÃ¡gica do texto subir quando digita ou foca */
        .form-floating-custom input:focus ~ label,
        .form-floating-custom input:not(:placeholder-shown) ~ label { 
            top: -15px; 
            font-size: 0.8rem; 
            color: var(--primary); 
            font-weight: 700; 
            letter-spacing: 1px;
        }

        .icon-left { position: absolute; left: 0; top: 12px; color: #a6a6b7; font-size: 1.2rem; transition: 0.3s; }
        .form-floating-custom input:focus ~ .icon-left { color: var(--primary); }
        
        .icon-right { position: absolute; right: 0; top: 12px; color: #a6a6b7; cursor: pointer; font-size: 1.2rem; transition: 0.3s; }
        .icon-right:hover { color: var(--primary); }

        .btn-login { background: linear-gradient(45deg, var(--primary) 0%, #827df6 100%); border: none; height: 55px; font-weight: 800; font-size: 1rem; border-radius: 30px; transition: 0.3s; color: #fff; text-transform: uppercase; letter-spacing: 1px; margin-top: 10px; box-shadow: 0 5px 15px rgba(115, 103, 240, 0.4); }
        .btn-login:hover { transform: translateY(-3px); box-shadow: 0 8px 20px rgba(115, 103, 240, 0.6); color: #fff; }
    </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" style="letter-spacing: 1px;"><?= htmlspecialchars($nomePainel) ?></h3>
    <p class="text-white-50 mb-5 small">Acesse o seu painel de controle</p>

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

    <form method="POST">
        <div class="form-floating-custom text-start">
            <input type="text" name="usuario" id="usuario" required placeholder=" ">
            <i class="fas fa-user icon-left"></i>
            <label for="usuario">Usuario</label>
        </div>

        <div class="form-floating-custom text-start">
            <input type="password" name="senha" id="inputSenha" required placeholder=" ">
            <i class="fas fa-lock icon-left"></i>
            <label for="inputSenha">Senha</label>
            <i class="fas fa-eye icon-right" id="iconEye" onclick="togglePassword()"></i>
        </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>
