<?php

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

use App\Models\Ecommerce\Product\Order\Order as OrderModel;
use App\Models\Ecommerce\Product\Order\Status\OrderStatus;
use App\Nova\Filters\RegionFilter;
use App\Nova\Filters\StatusFilter;
use App\Nova\Resource;
use App\Nova\Resources\Ecommerce\Product\Order\Actions\ExportOrderInvoiceAction;
use App\Nova\Resources\Ecommerce\Product\Order\Actions\ExportOrderReportAction;
use App\Nova\Resources\Ecommerce\Product\Order\Concerns\OrderFieldsForCreate;
use App\Nova\Resources\Ecommerce\Product\Order\Concerns\OrderFieldsForDetail;
use App\Nova\Resources\Ecommerce\Product\Order\Concerns\OrderFieldsForIndex;
use App\Nova\Resources\Ecommerce\Product\Order\Concerns\OrderFieldsForUpdate;
use App\Repositories\CMS\Icon\IconRepository;
use DigitalCreative\ColumnToggler\ColumnTogglerTrait;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Laravel\Nova\Fields\HasMany;
use Laravel\Nova\Fields\ID;
use Laravel\Nova\Http\Requests\NovaRequest;

class Order extends Resource
{
    use ColumnTogglerTrait;

    /**
     * The model the resource corresponds to.
     *
     * @var string
     */
    public static $model = OrderModel::class;

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

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

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

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

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

    /**
     * Indicates whether the resource should automatically poll for new resources.
     *
     * @var bool
     */
    public static $polling = true;

    /**
     * The interval at which Nova should poll for new resources.
     *
     * @var int
     */
    public static $pollingInterval = 120;

    /**
     * Indicates whether to show the polling toggle button inside Nova.
     *
     * @var bool
     */
    public static $showPollingToggle = true;

    /**
     * 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')) {
            $order_ids = DB::table('order_items')->where('channel_id', $user->channel()->id)->distinct()->pluck('order_id');

            $query->whereIntegerInRaw('id', $order_ids);
        }

        return $query;
    }

    /**
     * After order was updated
     */
    public static function afterUpdate(NovaRequest $request, Model $model): void
    {
        if ($model->status === OrderStatus::CANCELLED) {
            $orderItems = $model->items()->with('product')->get(['id', 'product_id', 'order_id', 'quantity']);

            $orderItems->each(function ($item) {
                $item->product->update([
                    'stock' => intval($item->product->stock) + intval($item->quantity),
                ]);
            });
        }
    }

    /**
     * Get the fields for index.
     */
    public function fieldsForIndex(NovaRequest $request): array
    {
        return OrderFieldsForIndex::make($this, $request);
    }

    /**
     * Get the fields for create.
     */
    public function fieldsForCreate(NovaRequest $request): array
    {
        return OrderFieldsForCreate::make($this, $request);
    }

    /**
     * Get the fields displayed by the resource on detail page.
     */
    public function fieldsForDetail(NovaRequest $request): array
    {
        return OrderFieldsForDetail::make($this, $request);
    }

    /**
     * Get the fields displayed by the resource on detail page.
     */
    public function fieldsForUpdate(NovaRequest $request): array
    {
        return OrderFieldsForUpdate::make($this, $request);
    }

    /**
     * Get the fields displayed by the resource.
     */
    public function fields(NovaRequest $request): array
    {
        return [
            ID::make()->sortable(),
            HasMany::make(__('Products'), 'items', OrderItem::class),
        ];
    }

    /**
     * Get the actions available for the resource.
     */
    public function actions(NovaRequest $request): array
    {
        return [
            ExportOrderReportAction::make()
                ->standalone()
                ->canSeeWhen('isAdmin', $this)
                ->onlyOnIndex()
                ->icon(IconRepository::make()->documentReport()),

            ExportOrderInvoiceAction::make()
                ->confirmText(__('Are you sure you want to run this action?'))
                ->confirmButtonText(__('Yes'))
                ->cancelButtonText(__('No'))
                ->exceptOnIndex()
                ->icon(IconRepository::make()->documentDownload()),
        ];
    }

    /**
     * Get the filters available for the resource.
     */
    public function filters(NovaRequest $request): array
    {
        return [
            RegionFilter::make(),
            StatusFilter::make(),
        ];
    }

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

        ];
    }
}
