<?php

declare(strict_types=1);

namespace App\Core;

use PDO;
use App\Shared\Schema\FinanceSchemaSupport;

final class Auth
{
    private const INTENDED_URL_KEY = '_intended_url';

    public static function check(): bool
    {
        return !empty(Session::get('user'));
    }

    public static function login(array $user): void
    {
        Session::regenerate(true);
        rbac_flush_cache();

        Session::put('user', [
            'id' => (int) ($user['id'] ?? 0),
            'username' => (string) ($user['username'] ?? ''),
            'full_name' => (string) (($user['full_name'] ?? '') ?: ($user['username'] ?? '')),
            'cashbox_id' => isset($user['cashbox_id']) ? (int) $user['cashbox_id'] : null,
        ]);
    }

    public static function user(): ?array
    {
        $user = Session::get('user');
        return is_array($user) ? $user : null;
    }

    public static function id(): ?int
    {
        $user = self::user();
        return isset($user['id']) ? (int) $user['id'] : null;
    }

    public static function name(): string
    {
        $user = self::user() ?? [];
        $name = trim((string) ($user['full_name'] ?? ''));
        if ($name !== '') {
            return $name;
        }

        $name = trim((string) ($user['username'] ?? ''));
        return $name !== '' ? $name : '-';
    }

    public static function cashboxId(PDO $pdo): int
    {
        $sessionCashboxId = (int) (Session::get('user')['cashbox_id'] ?? 0);
        if ($sessionCashboxId > 0) {
            return $sessionCashboxId;
        }

        $uid = self::id() ?? 0;
        if ($uid <= 0) {
            return 0;
        }

        try {
            FinanceSchemaSupport::ensureUsersCashboxSchema($pdo);
            $st = $pdo->prepare("SELECT cashbox_id FROM users WHERE id=? LIMIT 1");
            $st->execute([$uid]);
            $cashboxId = (int) ($st->fetchColumn() ?: 0);
            if ($cashboxId > 0) {
                $user = self::user() ?? [];
                $user['cashbox_id'] = $cashboxId;
                Session::put('user', $user);
            }
            return $cashboxId;
        } catch (\Throwable $e) {
            return 0;
        }
    }

    public static function requireLogin(): void
    {
        if (!self::check()) {
            self::rememberIntendedUrl();
            Redirect::to('/login');
        }
    }

    public static function rememberIntendedUrl(?string $uri = null): void
    {
        $uri ??= (string) ($_SERVER['REQUEST_URI'] ?? '/');
        if ($uri === '' || str_contains($uri, '/login')) {
            return;
        }

        Session::put(self::INTENDED_URL_KEY, $uri);
    }

    public static function pullIntendedUrl(string $fallback = '/admin/dashboard'): string
    {
        $value = Session::pull(self::INTENDED_URL_KEY, $fallback);
        return is_string($value) && $value !== '' ? $value : $fallback;
    }

    public static function logout(): void
    {
        $userId = current_user_id();
        audit_log('LOGOUT', 'users', $userId, []);

        Session::invalidate();
        Flash::set('success', 'تم تسجيل الخروج');
    }
}
