<?php

namespace App\Nova\Actions\Ecommerce\Product;

use App\Imports\Ecommerce\Product\ProductImport;
use App\Repositories\Ecommerce\Channel\ChannelRepository;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Collection;
use Laravel\Nova\Actions\Action;
use Laravel\Nova\Fields\ActionFields;
use Laravel\Nova\Fields\File;
use Laravel\Nova\Fields\Select;
use Laravel\Nova\Http\Requests\NovaRequest;
use Maatwebsite\Excel\Facades\Excel;

class ProductImportAction extends Action
{
    use InteractsWithQueue, Queueable;

    /**
     * The displayable name of the action.
     *
     * @var string
     */
    public $name = 'Import product';

    /**
     * Perform the action on the given models.
     *
     * @return mixed
     */
    public function handle(ActionFields $fields, Collection $models)
    {
        $file = $fields->files->store(sprintf('public/product-exports/user/%s/%s/', auth()->user()->id, now()->format('H_i_d_m_Y')));

        Excel::import(new ProductImport($fields->channel_id), $file);
    }

    /**
     * Get the fields available on the action.
     *
     * @return array
     */
    public function fields(NovaRequest $request)
    {
        return [
            Select::make(__('Channel'), 'channel_id')
                ->fullWidth()
                ->displayUsingLabels()
                ->searchable()
                ->options(function () {
                    if (auth()->user()->isAdmin()) {
                        return ChannelRepository::values();
                    }

                    $channel = auth()->user()->channel();

                    return [$channel->id => $channel->name];
                })
                ->rules('required'),

            File::make(__('Products excel'), 'files')
                ->fullWidth()
                ->rules('required'),
        ];
    }
}
