<?php
session_start();
ob_start();

// Verificar se já está logado
if (isset($_SESSION['admin_logged_in']) && $_SESSION['admin_logged_in'] === true) {
    header('Location: dashboard.php');
    exit();
}

// Arquivos de controle
define('ONLINE_USERS_FILE', 'online_users.txt');
define('USER_DATA_FILE', 'user_data.txt');
define('MAX_LOGIN_ATTEMPTS', 3);
define('BLOCK_TIME', 1800); // 30 minutos

// Função para registrar tentativa de login
function logLoginAttempt($success = false) {
    $ip = $_SERVER['REMOTE_ADDR'];
    $time = time();
    $user = isset($_POST['usuario']) ? htmlspecialchars($_POST['usuario']) : 'unknown';
    $status = $success ? 'success' : 'failed';
    $log = date('Y-m-d H:i:s') . " | IP: $ip | User: $user | Status: $status\n";
    file_put_contents(USER_DATA_FILE, $log, FILE_APPEND);
}

// Função para verificar tentativas de login
function checkLoginAttempts() {
    $ip = $_SERVER['REMOTE_ADDR'];
    $attempts = isset($_SESSION['login_attempts'][$ip]) ? $_SESSION['login_attempts'][$ip] : 0;
    
    if ($attempts >= MAX_LOGIN_ATTEMPTS) {
        $last_attempt = isset($_SESSION['last_attempt'][$ip]) ? $_SESSION['last_attempt'][$ip] : 0;
        if (time() - $last_attempt < BLOCK_TIME) {
            return false;
        }
        // Reset após o tempo de bloqueio
        unset($_SESSION['login_attempts'][$ip]);
        unset($_SESSION['last_attempt'][$ip]);
    }
    return true;
}

// Função para atualizar usuários online
function updateOnlineUsers($user) {
    $current = time();
    $online_users = [];
    
    if (file_exists(ONLINE_USERS_FILE)) {
        $content = file_get_contents(ONLINE_USERS_FILE);
        $online_users = json_decode($content, true) ?: [];
    }
    
    // Remover usuários inativos (+ de 5 minutos)
    foreach ($online_users as $u => $time) {
        if ($current - $time > 300) {
            unset($online_users[$u]);
        }
    }
    
    // Adicionar/atualizar usuário atual
    $online_users[$user] = $current;
    file_put_contents(ONLINE_USERS_FILE, json_encode($online_users));
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (!checkLoginAttempts()) {
        $erro = "Muitas tentativas. Aguarde 30 minutos.";
    } else {
        $usuario = filter_input(INPUT_POST, 'usuario', FILTER_SANITIZE_STRING);
        $senha = filter_input(INPUT_POST, 'senha', FILTER_SANITIZE_STRING);
        
        // Proteção contra XSS
        $usuario = htmlspecialchars($usuario, ENT_QUOTES, 'UTF-8');
        
        if ($usuario === "Bagalau7" && $senha === "Qwe84225054") {
            logLoginAttempt(true);
            updateOnlineUsers($usuario);
            
            $_SESSION['admin_logged_in'] = true;
            $_SESSION['user'] = $usuario;
            $_SESSION['last_activity'] = time();
            $_SESSION['token'] = bin2hex(random_bytes(32));
            
            header('Location: dashboard.php');
            exit();
        } else {
            logLoginAttempt(false);
            $ip = $_SERVER['REMOTE_ADDR'];
            $_SESSION['login_attempts'][$ip] = isset($_SESSION['login_attempts'][$ip]) ? $_SESSION['login_attempts'][$ip] + 1 : 1;
            $_SESSION['last_attempt'][$ip] = time();
            
            $erro = "Usuário ou senha incorretos";
        }
    }
}

// Limpar buffer antes de exibir a página
ob_end_clean();
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta http-equiv="Expires" content="0">
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
    <meta name="robots" content="noindex, nofollow">
    <meta name="referrer" content="strict-origin-when-cross-origin">
    <title>Login - Painel Administrativo</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            background-color: #1C2B3D;
            margin: 0;
            padding: 0;
            min-height: 100vh;
        }
        .page-wrapper {
            min-height: 100vh;
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 20px;
        }
        .logo-container {
            margin-bottom: 30px;
            text-align: center;
        }
        .logo-container img {
            max-width: 150px;
        }
        .login-container {
            background: white;
            padding: 30px;
            border-radius: 12px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            width: 100%;
            max-width: 400px;
        }
        .login-title {
            text-align: center;
            color: #333;
            margin-bottom: 30px;
            font-size: 24px;
        }
        .form-control:focus {
            border-color: #FF6C0E;
            box-shadow: 0 0 0 0.2rem rgba(255, 108, 14, 0.25);
        }
        .btn-login {
            background-color: #FF6C0E;
            border: none;
            width: 100%;
            padding: 12px;
            color: white;
            font-size: 16px;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        .btn-login:hover {
            background-color: #e65d00;
        }
        .error-message {
            color: #dc3545;
            text-align: center;
            margin-bottom: 15px;
        }
    </style>
</head>
<body>
    <div class="page-wrapper">
        <div class="logo-container">
            <img src="./img/dashboard/logo.png" alt="Bagalau Trampos">
        </div>
        <div class="login-container">
            <h2 class="login-title">Acesso Administrativo</h2>
            <?php if (isset($erro)): ?>
                <div class="error-message"><?php echo $erro; ?></div>
            <?php endif; ?>
            <form action="" method="POST">
                <div class="mb-3">
                    <input type="text" class="form-control" name="usuario" placeholder="Usuário" required>
                </div>
                <div class="mb-3">
                    <input type="password" class="form-control" name="senha" placeholder="Senha" required>
                </div>
                <button type="submit" class="btn-login">Entrar</button>
            </form>
        </div>
    </div>
    <script nonce="<?php echo $_SESSION['token'] ?? ''; ?>">
        // Desabilitar clique direito e atalhos de teclado
        document.addEventListener('contextmenu', e => e.preventDefault());
        document.addEventListener('keydown', e => {
            if (e.ctrlKey || e.keyCode === 123) e.preventDefault();
        });
    </script>
</body>
</html>
