<?php

namespace App\Repositories\Nova;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use Laravel\Nova\Events\ServingNova;

class NovaRepo
{
    /**
     * Serving nova application
     */
    public static function serving(ServingNova $event): void
    {
        static::setLocale($event);
    }

    /**
     * Nova breadcrumbs
     */
    public static function breadcrumbs(): Closure
    {
        return fn ($request) => static::enableBreadcrumbs($request);
    }

    /**
     * Enable breadcrumb for incoming request
     *
     * @param  \Laravel\Nova\Http\Requests\NovaRequest  $request
     */
    public static function enableBreadcrumbs($request): bool
    {
        $data = $request->segments();
        if (Route::currentRouteName() === 'nova.pages.detail' && count($data) === 4 && $data[2] === 'product-variants') {
            return false;
        }

        return true;
    }

    /**
     * Set locales
     */
    public static function setLocale(ServingNova $event): void
    {
        $user = $event->request->user();

        if ($user && array_key_exists($user->locale, config('app.locales'))) {
            app()->setLocale($user->locale);
        }
    }

    /**
     * Locale Switcher Save
     */
    public static function localeSwitcherSave(): Closure
    {
        return function (Request $request) {
            $locale = $request->post('locale');

            if (is_string($locale) && array_key_exists($locale, config('app.locales'))) {
                $request->user()->update([
                    'options' => json_encode([
                        'locale' => $locale,
                    ]),
                ]);
            }
        };
    }

    /**
     * Nova footer
     */
    public static function footer(): Closure
    {
        return fn ($request) => view('vendor.nova.layouts.footer')->render();
    }

    /**
     * Authorize user to view Nova
     */
    public static function canViewNova(): Closure
    {
        return fn ($user) => $user->canAccessNova();
    }

    /**
     * Nova raw image html
     */
    public static function rawImage(string $url): string
    {
        return sprintf('<img src="%s" class="rounded-full w-8 h-8" style="object-fit: cover;">', $url);
    }
}
