<?php

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

use App\Models\Ecommerce\Product\Inventory\InventoryHistoryRemoved;
use App\Models\Ecommerce\Product\Product\Product;
use App\Nova\Repeater\InventoryHistoryItemRepeater;
use App\Nova\Resource;
use App\Nova\Resources\Ecommerce\Channel\Channel;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Laravel\Nova\Fields\BelongsTo;
use Laravel\Nova\Fields\Date;
use Laravel\Nova\Fields\HasMany;
use Laravel\Nova\Fields\ID;
use Laravel\Nova\Fields\Repeater;
use Laravel\Nova\Fields\Text;
use Laravel\Nova\Http\Requests\NovaRequest;

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

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

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

    /**
     * The columns that should be searched.
     *
     * @var array
     */
    public static $search = [];

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

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

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

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

        return $query;
    }

    /**
     * Return the location to redirect the user after creation.
     *
     * @param  \Laravel\Nova\Resource  $resource
     * @return \Laravel\Nova\URL|string
     */
    public static function redirectAfterCreate(NovaRequest $request, $resource): string
    {
        return 'resources/inventories/'.$resource->inventory_id;
    }

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

            Date::make(__('Date'), 'date')
                ->rules('required')
                ->displayUsing(fn ($value) => $value->format('d.m.Y'))
                ->readonly(fn ($request) => $request->isUpdateOrUpdateAttachedRequest())
                ->default(now()->toDate())
                ->sortable(),

            Text::make(__('R. Number'), 'number')
                ->rules('required')
                ->readonly(fn ($request) => $request->isUpdateOrUpdateAttachedRequest())
                ->sortable(),

            BelongsTo::make(__('Inventory'), 'inventory', Inventory::class),
            BelongsTo::make(__('Channel'), 'channel', Channel::class),

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

            Text::make(__('Total'), fn () => $this->total),

            Text::make(__('Total'), 'readonly_total')
                ->onlyOnForms()
                ->readonly(),

            Repeater::make('Options', 'options')
                ->repeatables([
                    InventoryHistoryItemRepeater::make(),
                ])
                ->asJson()
                ->fullWidth()
                ->hideWhenUpdating(),

            HasMany::make(__('Items'), 'items', InventoryHistoryRemovedItemResource::class),
        ];
    }

    /**
     * Register a callback to be called after the resource is created.
     */
    public static function afterCreate(NovaRequest $request, Model $model): void
    {
        $total = 0;
        $request->collect('options')->each(function ($item) use ($model, &$total) {
            $total = floatval($total) + floatval($item['fields']['total']);

            $model->items()->create([
                'product_id' => $item['fields']['product_id'],
                'quantity' => $item['fields']['quantity'],
                'total' => floatval($item['fields']['total']),
                'cost_amount' => $item['fields']['cost_amount'],
            ]);

            $product = Product::find($item['fields']['product_id']);

            $inventoryRecordQuery = DB::table('inventory_product')
                ->where('product_id', $product->id)
                ->where('inventory_id', $model->inventory_id);

            $inventoryRecord = $inventoryRecordQuery->first();

            $inventoryRecord
            ? $inventoryRecordQuery->update([
                'stock' => intval($inventoryRecord->stock) - intval($item['fields']['quantity']),
            ]) : DB::table('inventory_product')->insert([
                'product_id' => $product->id,
                'inventory_id' => $model->inventory_id,
                'stock' => -intval($item['fields']['quantity']),
            ]);

            $product->updateQuietly([
                'stock' => $product->inventories()->sum('inventory_product.stock'),
            ]);
        });

        $model->updateQuietly(['total' => $total]);
    }

    /**
     * Determine if the current user can update the given resource.
     */
    public function authorizedToUpdate(Request $request): bool
    {
        return false;
    }

    /**
     * Determine if the current user can delete the given resource.
     */
    public function authorizedToDelete(Request $request): bool
    {
        if (auth()->user()->isMe()) {
            return true;
        }

        return false;
    }
}
