<?php

final class Auth
{
    public const COOKIE = 'hd_sid';

    private static ?array $user = null;
    private static ?array $session = null;

    /** Loads the session from the cookie, if any. */
    public static function boot(): void
    {
        $sid = $_COOKIE[self::COOKIE] ?? '';
        if ($sid === '' || !preg_match('/^[a-f0-9]{64}$/', $sid)) {
            return;
        }
        $row = DB::one(
            'SELECT s.*, u.id AS uid, u.full_name, u.email, u.is_active,
                    u.customer_id, u.twofa_enabled, u.twofa_confirmed_at, r.code AS role
             FROM user_sessions s
             JOIN users u ON u.id = s.user_id
             JOIN roles r ON r.id = u.role_id
             WHERE s.id = ? AND s.expires_at > NOW()',
            [$sid]
        );
        if (!$row || (int) $row['is_active'] !== 1) {
            return;
        }
        self::$session = $row;
        self::$user = [
            'id'          => (int) $row['uid'],
            'full_name'   => $row['full_name'],
            'email'       => $row['email'],
            'role'        => $row['role'],
            'customer_id' => $row['customer_id'] !== null ? (int) $row['customer_id'] : null,
            'twofa_enabled'   => (int) $row['twofa_enabled'] === 1,
            'twofa_confirmed' => $row['twofa_confirmed_at'] !== null,
        ];
        DB::run('UPDATE user_sessions SET last_seen_at = NOW() WHERE id = ?', [$sid]);
    }

    public static function startSession(int $userId, bool $twofaPassed): array
    {
        $sid  = bin2hex(random_bytes(32));
        $csrf = bin2hex(random_bytes(32));
        $mins = (int) Config::get('session_lifetime_min', 480);
        DB::run(
            'INSERT INTO user_sessions (id, user_id, csrf_token, ip_address, user_agent, twofa_passed, expires_at)
             VALUES (?,?,?,?,?,?, DATE_ADD(NOW(), INTERVAL ? MINUTE))',
            [
                $sid, $userId, $csrf,
                @inet_pton($_SERVER['REMOTE_ADDR'] ?? '') ?: null,
                substr($_SERVER['HTTP_USER_AGENT'] ?? '', 0, 255),
                $twofaPassed ? 1 : 0, $mins,
            ]
        );
        setcookie(self::COOKIE, $sid, [
            'expires'  => time() + $mins * 60,
            'path'     => (string) Config::get('cookie_path', '/'),
            'httponly' => true,
            'secure'   => (bool) Config::get('secure_cookies', true),
            'samesite' => 'Lax',
        ]);
        return ['sid' => $sid, 'csrf' => $csrf];
    }

    public static function promote(): void
    {
        if (self::$session) {
            DB::run('UPDATE user_sessions SET twofa_passed = 1 WHERE id = ?', [self::$session['id']]);
            self::$session['twofa_passed'] = 1;
        }
    }

    public static function destroy(): void
    {
        if (self::$session) {
            DB::run('DELETE FROM user_sessions WHERE id = ?', [self::$session['id']]);
        }
        setcookie(self::COOKIE, '', [
            'expires' => time() - 3600, 'path' => (string) Config::get('cookie_path', '/'), 'httponly' => true,
            'secure'  => (bool) Config::get('secure_cookies', true), 'samesite' => 'Lax',
        ]);
        self::$session = null;
        self::$user = null;
    }

    /** Signed in with the password, but the OTP step may still be pending. */
    public static function partial(): ?array
    {
        return self::$user;
    }

    public static function csrfToken(): ?string
    {
        return self::$session['csrf_token'] ?? null;
    }

    public static function twofaPassed(): bool
    {
        return self::$session !== null && (int) self::$session['twofa_passed'] === 1;
    }

    /** The fully authenticated user, or null. */
    public static function user(): ?array
    {
        return self::twofaPassed() ? self::$user : null;
    }

    public static function require(string ...$roles): array
    {
        $u = self::user();
        if (!$u) {
            throw new ApiError('נדרשת התחברות', 401);
        }
        if ($roles && !in_array($u['role'], $roles, true) && $u['role'] !== 'admin') {
            throw new ApiError('אין הרשאה לפעולה זו', 403);
        }
        return $u;
    }

    /** Any signed-in staff member. */
    public static function requireStaff(): array
    {
        return self::require('support', 'technician', 'instructor', 'admin');
    }

    public static function checkCsrf(): void
    {
        $method = $_SERVER['REQUEST_METHOD'];
        if (in_array($method, ['GET', 'HEAD', 'OPTIONS'], true)) {
            return;
        }
        // Nothing to protect before a session exists: the login request carries no
        // ambient authority. SameSite=Lax on the cookie covers login CSRF.
        if (self::$session === null) {
            return;
        }
        $sent = $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '';
        $have = self::csrfToken();
        if (!$have || !hash_equals($have, $sent)) {
            throw new ApiError('אסימון אבטחה שגוי, יש לרענן את הדף', 419);
        }
    }

    public static function logAttempt(string $email, bool $success, string $stage): void
    {
        DB::run(
            'INSERT INTO login_attempts (email, ip_address, success, stage) VALUES (?,?,?,?)',
            [$email, @inet_pton($_SERVER['REMOTE_ADDR'] ?? '') ?: null, $success ? 1 : 0, $stage]
        );
    }

    /** Simple throttle: 10 failures from one IP in 15 minutes. */
    public static function throttle(): void
    {
        $ip = @inet_pton($_SERVER['REMOTE_ADDR'] ?? '');
        if (!$ip) {
            return;
        }
        $n = (int) DB::value(
            'SELECT COUNT(*) FROM login_attempts
             WHERE ip_address = ? AND success = 0 AND created_at > DATE_SUB(NOW(), INTERVAL 15 MINUTE)',
            [$ip]
        );
        if ($n >= 10) {
            throw new ApiError('יותר מדי ניסיונות התחברות. נסו שוב בעוד 15 דקות.', 429);
        }
    }
}
