<?php

if (! function_exists('auth_user')) {
    function auth_user(): ?array
    {
        $apiUser = $GLOBALS['tibaleta_api_user'] ?? null;
        if (is_array($apiUser)) return $apiUser;
        $session = service('session');
        $user = $session->get('auth_user');
        return is_array($user) ? $user : null;
    }
}

if (! function_exists('auth_id')) {
    function auth_id(): ?int
    {
        return auth_user()['id'] ?? null;
    }
}

if (! function_exists('has_role')) {
    function has_role(string|array $roles): bool
    {
        $user = auth_user();
        if (! $user) return false;
        return in_array($user['role'] ?? '', (array) $roles, true);
    }
}

if (! function_exists('money')) {
    function money(float|int|string|null $amount, string $currency = 'KES'): string
    {
        return $currency . ' ' . number_format((float) ($amount ?? 0), 0);
    }
}

if (! function_exists('initials')) {
    function initials(?string $name): string
    {
        $name = trim((string) $name);
        if ($name === '') return 'TL';
        $parts = preg_split('/\\s+/', $name) ?: [];
        return strtoupper(substr($parts[0] ?? 'T', 0, 1) . substr($parts[1] ?? '', 0, 1));
    }
}

if (! function_exists('service_icon')) {
    function service_icon(string $slug): string
    {
        return match ($slug) {
            'doctor-home-visit' => 'stethoscope',
            'nursing-care' => 'heart-pulse',
            'physiotherapy' => 'activity',
            'lab-sample-collection' => 'flask-conical',
            'elderly-care' => 'heart-handshake',
            'teleconsultation' => 'video',
            'maternal-care' => 'baby',
            'chronic-care' => 'clipboard-heart',
            default => 'cross',
        };
    }
}
