<?php

namespace App\Nova\Resources\Ecommerce\Product\Inventory;

use App\Models\Ecommerce\Product\Inventory\Inventory as InventoryModel;
use App\Models\System\Settings\Location\Province;
use App\Models\System\Settings\Location\Region;
use App\Nova\Permissions\NovaPermission;
use App\Nova\Resource;
use App\Nova\Resources\Ecommerce\Channel\Channel;
use App\Nova\Resources\Ecommerce\Product\Inventory\Product\ProductResource;
use Illuminate\Database\Eloquent\Builder;
use Laravel\Nova\Fields\BelongsTo;
use Laravel\Nova\Fields\BelongsToMany;
use Laravel\Nova\Fields\Boolean;
use Laravel\Nova\Fields\Currency;
use Laravel\Nova\Fields\HasMany;
use Laravel\Nova\Fields\Hidden;
use Laravel\Nova\Fields\ID;
use Laravel\Nova\Fields\Number;
use Laravel\Nova\Fields\Select;
use Laravel\Nova\Fields\Text;
use Laravel\Nova\Http\Requests\NovaRequest;

class Inventory extends Resource
{
    /**
     * The model the resource corresponds to.
     *
     * @var class-string<\App\Models\Shop\Inventory\Inventory>
     */
    public static $model = InventoryModel::class;

    /**
     * The relationships that should be eager loaded on index queries.
     *
     * @var array
     */
    public static $with = ['channel'];

    /**
     * The single value that should be used to represent the resource when being displayed.
     *
     * @var string
     */
    public static $title = 'name';

    /**
     * The columns that should be searched.
     *
     * @var array
     */
    public static $search = ['name', 'code', 'email', 'phone_number'];

    /**
     * Get the displayable label of the resource.
     */
    public static function label(): string
    {
        return __('Inventories');
    }

    /**
     * Get the displayable singular label of the resource.
     */
    public static function singularLabel(): string
    {
        return __('Inventory');
    }

    /**
     * Build an "index" query for the given resource.
     *
     * @param  Builder  $query
     * @return Builder
     */
    public static function indexQuery(NovaRequest $request, $query)
    {
        $user = $request->user();

        if ($user->hasRole('vendor')) {
            $query->where('channel_id', $user->channel()->id);
        }

        return $query;
    }

    /**
     * Get the fields displayed by the resource.
     */
    public function fields(NovaRequest $request): array
    {
        return [
            ID::make()->sortable(),

            BelongsTo::make(__('Channel'), 'channel', Channel::class)
                ->rules('required')
                ->canSeeWhen('systemUser', $this)
                ->sortable(),

            Hidden::make('channel_id')
                ->default(fn () => $request->isCreateOrAttachRequest() ? $request->user()->channel()?->id : null)
                ->canSee(NovaPermission::canSeeIfUserIsEntrepreneur()),

            Text::make(__('Name'), 'name')
                ->rules('required', 'string', 'max:255')
                ->sortable(),

            Text::make(__('Code'), 'code')->exceptOnForms()->sortable(),

            Select::make(__('Region'), 'region')
                ->displayUsingLabels()
                ->searchable()
                ->options(Region::values())
                ->default(Region::AG)
                ->rules('required')
                ->sortable(),

            Select::make(__('Province'), 'province_id')
                ->displayUsingLabels()
                ->searchable()
                ->dependsOn(['region'], function ($field, $request, $formData) {
                    if ($formData->region != 'ag') {
                        $field->rules('required');
                    }

                    $field->options(
                        Province::where('region', $formData->region)->pluck(
                            'name',
                            'id'
                        )
                    );
                })
                ->hideFromIndex()
                ->sortable(),

            Text::make(__('Address'), 'street_address')
                ->rules('nullable', 'string', 'max:255')
                ->hideFromIndex(),

            Text::make(__('Description'), 'description')->hideFromIndex(),

            Text::make(__('Email'), 'email')
                ->rules('nullable', 'string', 'max:255')
                ->hideFromIndex()
                ->sortable(),

            Currency::make(__('Phone'), 'phone_number')
                ->symbol('+993')
                ->displayUsing(fn ($value) => $value ? '+(993)-'.$value : '—')
                ->textAlign('left')
                ->rules('nullable', 'string', 'max:255')
                ->sortable(),

            Number::make(__('Zipcode'), 'zipcode')
                ->rules('nullable', 'integer')
                ->hideFromIndex()
                ->sortable(),

            Text::make(__('Longitude'), 'longitude')->hideFromIndex(),

            Text::make(__('Latitude'), 'latitude')->hideFromIndex(),

            Boolean::make(__('Sharable'), 'shareable')
                ->canSeeWhen('isAdmin', $this)
                ->sortable(),

            HasMany::make(__('Inventory entry'), 'history', InventoryHistoryResource::class),
            HasMany::make(__('Inventory exit'), 'historyRemoved', InventoryHistoryRemovedResource::class),

            BelongsToMany::make(__('Products'), 'products', ProductResource::class),
        ];
    }

    /**
     * Get the cards available for the request.
     *
     * @return array
     */
    public function cards(NovaRequest $request)
    {
        return [];
    }

    /**
     * Get the filters available for the resource.
     *
     * @return array
     */
    public function filters(NovaRequest $request)
    {
        return [];
    }

    /**
     * Get the lenses available for the resource.
     *
     * @return array
     */
    public function lenses(NovaRequest $request)
    {
        return [];
    }

    /**
     * Get the actions available for the resource.
     *
     * @return array
     */
    public function actions(NovaRequest $request)
    {
        return [];
    }
}
