<?php
/*
 * package examples/crash_reporter/backend/src/Auth.php
 * Auth.php
 * Created at: Wed 20 May 2026 14:31:55 +0200
 * Updated at: Wed 20 May 2026 15:17:13 +0200 by Anton Afanasyeu <a.afanasieff@gmail.com>
 * Commit: 5d8e82d2e60a21fff3138d2a394ee4e8b4c6dcb8
 * Contributors:
 *    - Anton Afanasyeu <a.afanasieff@gmail.com> (2 commits, 56 lines)
 *    - Cursor Agent (project assistant)
 * Digest: SHA256	a6e49e8d07788ac2b4ea48f886f9a46ec6f5c1eab5b9723e1554e1fe53765efd
 */
declare(strict_types=1);

final class Auth {
    public static function user(): ?array {
        $u = $_SESSION['user'] ?? null;
        if (!$u || !empty($u['companies'])) {
            return $u;
        }
        $uid = (int) ($u['id'] ?? 0);
        if ($uid <= 0) {
            return $u;
        }
        $stmt = Database::pdo()->prepare('SELECT * FROM users WHERE id = ? LIMIT 1');
        $stmt->execute([$uid]);
        $row = $stmt->fetch();
        if (!$row) {
            return $u;
        }
        Database::ensureRbacSchema();
        Rbac::seedMembershipsForUser($uid, (string) ($row['role'] ?? 'viewer'));
        $_SESSION['user'] = Rbac::buildSessionUser($row);
        return $_SESSION['user'];
    }

    public static function check(): void {
        if (!self::user()) {
            header('Location: ' . self::basePath() . '/login');
            exit;
        }
    }

    public static function can(string $action): bool {
        return Rbac::can($action);
    }

    public static function canEditTags(?int $companyId = null): bool {
        return Rbac::can('edit_tags', $companyId);
    }

    /** Ticket owner or company admin+ (same gate as tag edit for alpha). */
    public static function canEditTicket(array $ticket, ?int $companyId = null): bool {
        if (self::canEditTags($companyId)) {
            return true;
        }
        $user = self::user();
        if (!$user) {
            return false;
        }
        $owner = trim((string) ($ticket['owner_username'] ?? ''));
        return $owner !== '' && strcasecmp($owner, (string) ($user['username'] ?? '')) === 0;
    }

    public static function login(string $username, string $password): bool {
        $pdo = Database::pdo();
        $stmt = $pdo->prepare('SELECT * FROM users WHERE username = ? LIMIT 1');
        $stmt->execute([$username]);
        $row = $stmt->fetch();
        if (!$row || !password_verify($password, $row['password_hash'])) {
            return false;
        }
        $_SESSION['user'] = Rbac::buildSessionUser($row);
        return true;
    }

    public static function logout(): void {
        unset($_SESSION['user']);
    }

    public static function basePath(): string {
        $bp = cfg('base_path', '');
        return rtrim($bp, '/');
    }
}
