<?php
namespace App\Core;

class Auth
{
    public static function isLoggedIn(): bool
    {
        return !empty($_SESSION['user_id']);
    }

    public static function userId(): ?int
    {
        return $_SESSION['user_id'] ?? null;
    }

    public static function login(int $userId): void
    {
        session_regenerate_id(true);
        $_SESSION['user_id'] = $userId;
        $_SESSION['login_at'] = time();
    }

    public static function logout(): void
    {
        $_SESSION = [];
        if (ini_get('session.use_cookies')) {
            $p = session_get_cookie_params();
            setcookie(session_name(), '', time() - 42000, $p['path'], $p['domain'], $p['secure'], $p['httponly']);
        }
        session_destroy();
    }

    public static function requireAuth(): void
    {
        if (!self::isLoggedIn()) {
            http_response_code(401);
            header('Content-Type: application/json');
            echo json_encode(['error' => ['message' => 'Belum login', 'code' => 'UNAUTHORIZED']]);
            exit;
        }
    }

    /**
     * Rate limit sederhana: max 5 percobaan per 60 detik
     */
    public static function checkLoginRateLimit(): bool
    {
        $key = 'login_attempts';
        $window = 60;
        $maxAttempts = 5;

        if (!isset($_SESSION[$key])) {
            $_SESSION[$key] = [];
        }

        $now = time();
        // Bersihkan yang sudah lewat window
        $_SESSION[$key] = array_filter($_SESSION[$key], fn($t) => ($now - $t) < $window);

        if (count($_SESSION[$key]) >= $maxAttempts) {
            return false; // rate limited
        }

        $_SESSION[$key][] = $now;
        return true;
    }
}
