<?php

namespace App\Nova\Resources\Ecommerce\Product\Order\OrderItem;

use App\Models\Ecommerce\Product\Product\Product as ProductModel;
use App\Nova\Resources\Ecommerce\Product\Order\Order;
use App\Nova\Resources\Ecommerce\Product\Product\Product;
use Illuminate\Support\Facades\DB;
use Laravel\Nova\Fields\Hidden;
use Laravel\Nova\Fields\ID;
use Laravel\Nova\Fields\Number;
use Laravel\Nova\Fields\Text;
use Outl1ne\MultiselectField\Multiselect;

class OrderItemFieldsForCreate
{
    /**
     * Order item fields for create
     */
    public static function make($resource, $request): array
    {
        return [
            ID::make(),

            Hidden::make('order_id')
                ->default($request->viaResource()),

            Multiselect::make(__('Product'), 'product_id')
                ->asyncResource(Product::class)
                ->placeholder(__('Search by id, name, sku, barcode...'))
                ->singleSelect()
                ->rules('required'),

            Number::make(__('Quantity'), 'quantity')
                ->rules('required', 'min:1')
                ->default(1),

            Text::make(__('Price'), 'unit_price_amount')
                ->rules('required')
                ->dependsOn('product_id', function ($field, $request, $formData) {
                    if (! $formData->product_id || ! is_int($formData->product_id)) {
                        return;
                    }

                    $product = DB::table('products')->where('id', $formData->product_id)->first();

                    $field->setValue($product->price_amount);
                })->fillUsing(function ($request, $model, $attribute, $requestAttribute) {
                    $product = ProductModel::find($request->product_id);

                    $model->unit_price_amount = $request->unit_price_amount;
                    $model->unit_cost_amount = $product->cost_amount;
                    $model->product_name = $product->name;
                    $model->channel_id = $product->channels()->first()?->id ?? tmpostChannel()->id;
                }),

            Number::make(__('Total'), 'total')
                ->dependsOn(['quantity', 'unit_price_amount'], function ($field, $request, $formData) {
                    if (! $formData->unit_price_amount || ! $formData->quantity) {
                        return;
                    }

                    $field->setValue($formData->unit_price_amount * $formData->quantity);
                })->readonly(),
        ];
    }
}
