<?php
declare(strict_types=1);

namespace App\Services;

final class LoginGuard
{
    public static function isLocked(string $key = 'global'): bool
    {
        if (session_status() !== PHP_SESSION_ACTIVE) { @session_start(); }
        $until = (int)($_SESSION['lg_lock_until'][$key] ?? 0);
        return $until > time();
    }

    public static function secondsRemaining(string $key = 'global'): int
    {
        if (session_status() !== PHP_SESSION_ACTIVE) { @session_start(); }
        $until = (int)($_SESSION['lg_lock_until'][$key] ?? 0);
        return max(0, $until - time());
    }

    public static function registerFailedAttempt(string $key = 'global'): void
    {
        if (session_status() !== PHP_SESSION_ACTIVE) { @session_start(); }

        $count = (int)($_SESSION['lg_fail_count'][$key] ?? 0);
        $count++;
        $_SESSION['lg_fail_count'][$key] = $count;

        if ($count >= 6) {
            $_SESSION['lg_lock_until'][$key] = time() + 300; // 5 min
            $_SESSION['lg_fail_count'][$key] = 0;
        }
    }

    public static function clear(string $key = 'global'): void
    {
        if (session_status() !== PHP_SESSION_ACTIVE) { @session_start(); }
        unset($_SESSION['lg_fail_count'][$key], $_SESSION['lg_lock_until'][$key]);
    }

    /**
     * Compatibility: AuthController calls LoginGuard::record($key, $ok)
     * Some older code passes 'success'/'fail' strings.
     */
    public static function record(string $key = 'global', $ok = false): void
    {
        $boolOk = false;

        if (is_bool($ok)) {
            $boolOk = $ok;
        } elseif (is_int($ok)) {
            $boolOk = ($ok === 1);
        } elseif (is_string($ok)) {
            $v = strtolower(trim($ok));
            $boolOk = in_array($v, ['1','true','yes','ok','success','passed'], true);
        }

        if ($boolOk) self::clear($key);
        else self::registerFailedAttempt($key);
    }
}
