<?php

namespace App\Http\Controllers\Admin\Products;

use App\Exports\ProductsExport;
use App\Helpers\DropdownListHelper;
use App\Helpers\UUIDHelper;
use App\Models\Product;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\ProductStoreRequest;
use App\Http\Requests\Admin\ProductUpdateRequest;
use App\Imports\ProductsImport;
use App\Models\Brand;
use App\Notifications\ProductStatus;
use App\Services\Admin\Products\ProductService;
use Exception;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Inertia\Inertia;
use Intervention\Image\Drivers\Gd\Driver;
use Intervention\Image\Encoders\WebpEncoder;
use Intervention\Image\ImageManager;
use Maatwebsite\Excel\Facades\Excel;

class ProductsController extends Controller
{
    use DropdownListHelper, UUIDHelper;

    /**
     * Display a listing of the resource.
     */
    public function index(Request $request, ProductService $productService)
    {
        return Inertia::render('Admin/Products/Products/List', [
            'products' => $productService->getProducts($request, "all"),
            'categories' => $productService->getCategoriesBranch(),
            'brands' => Brand::where('status', 'publish')->get()->map(fn($brand) => [
                'id' => $brand->id,
                'title' => $brand->title,
            ]),
            'statusList' => $this->contentStatusList(),
        ]);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create(ProductService $productService)
    {
        return Inertia::render('Admin/Products/Products/Create', [
            'categories' => $productService->getCategoriesBranch(),
            'statusList' => $this->contentStatusList(),
            'videoTypeList' => $this->videoTypeList(),
        ]);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(ProductStoreRequest $request, ProductService $productService)
    {
        /** current user
         * @var \App\Models\User $user
         */
        $user = auth()->user();

        /** validate duplicated slug */
        if ($request->exists('slug') && $request->slug != null) {
            $productWithSlug = Product::where('slug', $request->slug)->first();
            if ($productWithSlug != null) {
                return redirect()->back()->withErrors([__('messages.slug_is_exist')]);
            }
        }

        /** validate duplicated uuid */
        if ($request->exists('uuid') && $request->uuid != null) {
            $productWithSlug = Product::where('uuid', $request->uuid)->first();
            if ($productWithSlug != null) {
                return redirect()->back()->withErrors([__('messages.product_with_this_uuid_is_exist')]);
            }
        }

        /** validate in stock status when is false */
        if (!$request->in_stock_status) {
            if ($request->inquiry_options['landline_phone'] == null || $request->inquiry_options['cellular_phone'] == null) {
                return redirect()->back()->withErrors([__('messages.landline_phone_or_cellular_phone_is_null')]);
            }
        }

        /** validate seller commission */
        $commission = 0;
        if ($request->exists('commission') && $request->commission != null) {
            if ($request->commission > 100 || $request->commission < 0) {
                return redirect()->back()->withErrors([__('messages.seller_commission_incorrect')]);
            }
            $commission = $request->commission;
        }

        $product = $user->products()->create([
            'edited_by' => $user->id,
            'brand_id' => $productService->initBrand($user, $request),
            'category_id' => $request->category['id'],
            'uuid' => $request->exists('uuid') && $request->uuid != null && $request->uuid != '' ? $request->uuid : $this->generateUniqueRandomNumber(8, \App\Models\Product::class, 'uuid', 'p-'),
            'title' => $request->title,
            'title_en' => $request->exists('title_en') ? $request->title_en : null,
            'slug' => $request->exists('slug') && $request->slug != null ? str_replace('/', '-', str_replace('\\', '-', str_replace('%', '', $request->slug))) : null,
            'content' => $request->exists('content') ? $request->content : null,
            'warnings' => $request->exists('warnings') ? $request->warnings : null,
            'guide' => $request->exists('guide') ? $request->guide : null,
            'tabs' => $request->exists('tabs') ? serialize($request->tabs) : null,

            'images' => $request->exists('images') ? serialize($request->images) : null,
            'videos' => $request->exists('videos') ? serialize($request->videos) : null,
            'model_3d' => $request->exists('model_3d') ? $request->model_3d : null,

            'attrs' => $request->exists('attrs') ? serialize($request->attrs) : null,

            'seo_title' => $request->exists('seo_title') ? $request->seo_title : null,
            'seo_description' => $request->exists('seo_description') ? $request->seo_description : null,
            'seo_keywords' => $request->exists('seo_keywords') ? $request->seo_keywords : null,
            'seo_canonical' => $request->exists('seo_canonical') ? urldecode($request->seo_canonical) : null,

            'in_stock_status' => $request->in_stock_status,
            'inquiry_options' => serialize($request->inquiry_options),

            'commission' => $commission,

            'is_vip' => $request->is_vip,
            'comment_status' => $request->comment_status,
            'question_status' => $request->question_status,

            'reason' => 'create',
            'status' => $request->status,
        ]);

        /** add price model */
        $productService->addPriceModel($product, $request);

        try {
            /** add specifications */
            $productService->addSpecifications($product, $request);
        } catch (Exception $e) {
        }

        /** create and sync tags */
        $productService->syncTags($product, $request);

        /** Report Action */
        $this->report(__("messages.report_product_created"), 'product', $product);

        return redirect()->route('admin.products.index')->with('message', [__('messages.product_created')]);
    }

    /**
     * Clone an existing product
     */
    public function clone(Product $product, ProductService $productService)
    {
        /** current user */
        $user = auth()->user();

        /** create cloned product */
        $clonedProduct = $user->products()->create([
            'edited_by'       => $user->id,
            'brand_id'        => $product->brand_id,
            'category_id'     => $product->category_id,
            'uuid'            => $this->generateUniqueRandomNumber(8, \App\Models\Product::class, 'uuid', 'p-'),
            'title'           => $product->title,
            'title_en'        => $product->title_en,
            'content'         => $product->content,
            'warnings'        => $product->warnings,
            'guide'           => $product->guide,
            'tabs'            => $product->tabs,
            'images'          => $product->images,
            'videos'          => $product->videos,
            'model_3d'          => $product->model_3d,
            'attrs'           => $product->attrs,
            'seo_title'       => $product->seo_title,
            'seo_description' => $product->seo_description,
            'seo_keywords'    => $product->seo_keywords,
            'seo_canonical'   => $product->seo_canonical,
            'in_stock_status' => $product->in_stock_status,
            'inquiry_options' => $product->inquiry_options,
            'commission'      => $product->commission,
            'is_vip'          => $product->is_vip,
            'comment_status'  => $product->comment_status,
            'question_status' => $product->question_status,
            'reason'          => 'clone',
            'status'          => 'draft',
        ]);

        /** copy price models */
        $productService->clonePriceModel($product, $clonedProduct);

        /** copy specifications */
        $productService->cloneSpecifications($product, $clonedProduct);

        /** copy tags */
        $productService->cloneTags($product, $clonedProduct);

        /** Report Action */
        $this->report(__("messages.report_product_created"), 'product', $clonedProduct);

        return redirect()->route('admin.products.index')->with('message', [__('messages.product_cloned')]);
    }


    /**
     * Display the specified resource.
     */
    public function show(Product $product)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Product $product, ProductService $productService)
    {
        if ($product->status == 'rejected')
            return redirect()->route('admin.products.index')->withErrors([__('messages.unauthorized')]);

        return Inertia::render('Admin/Products/Products/Edit', [
            'product' => [
                'id' => $product->id,
                'uuid' => $product->uuid,
                'title' => $product->title,
                'title_en' => $product->title_en,
                'slug' => $product->slug,
                'content' => $product->content,
                'warnings' => $product->warnings,
                'guide' => $product->guide,
                'get_tabs' => $product->get_tabs,
                'get_videos' => $product->get_videos,
                'model_3d' => $product->model_3d,
                'seo_title' => $product->seo_title,
                'seo_description' => $product->seo_description,
                'seo_keywords' => $product->seo_keywords,
                'seo_canonical' => $product->seo_canonical,
                'in_stock_status' => $product->in_stock_status,
                'get_inquiry_options' => $product->get_inquiry_options,
                'commission' => $product->commission,
                'question_status' => $product->question_status,
                'comment_status' => $product->comment_status,
                'get_tags_string' => $product->get_tags_string,
                'get_images_id' => $product->get_images_id,
                'get_images_link' => $product->get_images_link,
                'get_attrs' => $product->get_attrs,
                'price_model' => $product->price_model,
                'raw_price_model' => $product->raw_price_model,
                'is_vip' => $product->is_vip,
                'reason' => $product->reason,
                'status' => $product->status,
                'inventory' => $product->inventory,

                'brand' => $product->brand != null ? [
                    'id' => $product->brand->id,
                    'title' => $product->brand->title,
                ] : null,
                'category' => $product->productCategory != null ? [
                    'id' => $product->productCategory->id,
                ] : null,
            ],
            'categories' => $productService->getCategoriesBranchWithSpecification($product),
            'statusList' => $this->contentStatusList(),
            'videoTypeList' => $this->videoTypeList(),
        ]);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(ProductUpdateRequest $request, Product $product, ProductService $productService)
    {
        /** current user
         * @var \App\Models\User $user
         */
        $user = auth()->user();

        /** product initial status */
        $productStatus = $product->status;

        /** validate duplicated slug */
        if ($request->exists('slug') && $request->slug != null && $request->slug != $product->slug) {
            $productWithSlug = Product::where('slug', $request->slug)->first();
            if ($productWithSlug != null) {
                return redirect()->back()->withErrors([__('messages.slug_is_exist')]);
            }
        }

        /** validate duplicated uuid */
        if ($request->exists('uuid') && $request->uuid != null && $request->uuid != $product->uuid) {
            $productWithSlug = Product::where('uuid', $request->uuid)->first();
            if ($productWithSlug != null) {
                return redirect()->back()->withErrors([__('messages.product_with_this_uuid_is_exist')]);
            }
        }

        /** validate in stock status when is false */
        if (!$request->in_stock_status) {
            if ($request->inquiry_options['landline_phone'] == null || $request->inquiry_options['cellular_phone'] == null) {
                return redirect()->back()->withErrors([__('messages.landline_phone_or_cellular_phone_is_null')]);
            }
        }

        /** validate seller commission */
        $commission = $product->commission;
        if ($request->exists('commission') && $request->commission != null) {
            if ($request->commission > 100 || $request->commission < 0) {
                return redirect()->back()->withErrors([__('messages.seller_commission_incorrect')]);
            }
            $commission = $request->commission;
        }

        $product->update([
            'uuid' => $request->exists('uuid') && $request->uuid != null && $request->uuid != '' && $product->status == 'awaiting' ? $request->uuid : $product->uuid,
            'edited_by' => $user->id,
            'brand_id' => $productService->initBrand($user, $request),
            'category_id' => $request->category['id'],
            'title' => $request->title,
            'title_en' => $request->exists('title_en') ? $request->title_en : $product->title_en,
            'slug' => $request->exists('slug') ? str_replace('/', '-', str_replace('\\', '-', str_replace('%', '', $request->slug))) : $product->slug,
            'content' => $request->content,
            'warnings' => $request->exists('warnings') ? $request->warnings : $product->warnings,
            'guide' => $request->exists('guide') ? $request->guide : $product->guide,
            'tabs' => $request->exists('tabs') ? serialize($request->tabs) : $product->tabs,

            'images' => $request->exists('images') ? serialize($request->images) : $product->images,
            'videos' => $request->exists('videos') ? serialize($request->videos) : $product->videos,
            'model_3d' => $request->exists('model_3d') ? $request->model_3d : $product->model_3d,

            'attrs' => $request->exists('attrs') ? serialize($request->attrs) : null,

            'seo_title' => $request->exists('seo_title') ? $request->seo_title : $product->seo_title,
            'seo_description' => $request->exists('seo_description') ? $request->seo_description : $product->seo_description,
            'seo_keywords' => $request->exists('seo_keywords') ? $request->seo_keywords : $product->seo_keywords,
            'seo_canonical' => $request->exists('seo_canonical') ? urldecode($request->seo_canonical) : $product->seo_canonical,

            'in_stock_status' => $request->in_stock_status,
            'inquiry_options' => serialize($request->inquiry_options),

            'commission' => $commission,

            'is_vip' => $request->is_vip,
            'question_status' => $request->question_status,
            'comment_status' => $request->comment_status,

            'reason' => 'update',
            'status' => $request->status,
        ]);

        if ($product->inventories()->count() == 0) {
            /** add price model */
            $productService->addPriceModel($product, $request);
        }

        try {
            /** update specifications */
            $productService->updateSpecifications($product, $request);
        } catch (Exception $e) {
        }

        /** update and sync tags */
        $productService->updateAndSyncTags($product, $request);

        if ($productStatus == 'awaiting') {
            /** Report Action */
            $this->report(__("messages.report_product_accepted"), 'product', $product);

            // notification
            $product->user->notify(new ProductStatus($product, 'accept'), true);
        } else {
            /** Report Action */
            $this->report(__("messages.report_product_updated"), 'product', $product);
        }

        return redirect()->route('admin.products.edit', $product->slug)->with('message', [__('messages.product_updated')]);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Request $request, Product $product)
    {
        if ($product->status == 'deleted' && $request->status == 'deep_deleted') {
            // delete product from users cart
            $product->consignmentItems()->whereHas('consignment', function ($query) {
                $query->whereHas('order', function ($query) {
                    $query->whereDoesntHave('orderGroup');
                });
            })->delete();

            if ($product->consignmentItems()->count() > 0) {
                $product->update([
                    'status' => 'deep_deleted'
                ]);
            } else {
                $product->delete();
            }

            /** Report Action */
            $this->report(__("messages.report_product_deleted"), 'product', $product);

            return redirect()->back()->with('message', [__('messages.product_deleted')]);
        } else if ($product->status != 'deleted' && $request->status == 'deleted') {
            // delete product from users cart
            $product->consignmentItems()->whereHas('consignment', function ($query) {
                $query->whereHas('order', function ($query) {
                    $query->where('status', '!=', 'prefactor')->whereDoesntHave('orderGroup');
                });
            })->delete();

            $product->update([
                'status' => 'deleted'
            ]);

            /** Report Action */
            $this->report(__("messages.report_product_to_trash"), 'product', $product);

            return redirect()->back()->with('message', [__('messages.product_to_trash')]);
        } else if ($product->status != 'deleted' && $request->status == 'draft') {
            // delete product from users cart
            $product->consignmentItems()->whereHas('consignment', function ($query) {
                $query->whereHas('order', function ($query) {
                    $query->where('status', '!=', 'prefactor')->whereDoesntHave('orderGroup');
                });
            })->delete();

            $product->update([
                'status' => 'draft'
            ]);

            /** Report Action */
            $this->report(__("messages.report_product_draft"), 'product', $product);

            return redirect()->back()->with('message', [__('messages.product_draft')]);
        } else if ($request->status == 'publish') {
            $product->update([
                'status' => 'publish'
            ]);

            /** Report Action */
            $this->report(__("messages.report_product_publish"), 'product', $product);

            return redirect()->back()->with('message', [__('messages.product_publish')]);
        }

        return redirect()->route('admin.products.index')->withErrors([__('messages.unknown_error')]);
    }

    /**
     * products trash list
     */
    public function trash(Request $request, ProductService $productService)
    {
        return Inertia::render('Admin/Products/Products/Trash', [
            'products' => $productService->getTrashList($request)
        ]);
    }

    /**
     * accept or reject awaiting products
     */
    public function check(Request $request, Product $product)
    {
        if ($product->status != 'awaiting')
            return redirect()->route('admin.products.index')->withErrors([__('messages.unauthorized')]);

        $request->validate([
            'action' => 'required'
        ]);

        if ($request->action == 'accept') {
            $product->update([
                'status' => 'publish'
            ]);

            /** Report Action */
            $this->report(__("messages.report_product_accepted"), 'product', $product);

            // notification
            $product->user->notify(new ProductStatus($product, 'accept'), true);

            return redirect()->route('admin.products.index')->with('message', [__('messages.product_accepted')]);
        } else if ($request->action == 'reject') {
            $request->validate([
                'reason' => 'required'
            ]);

            $product->update([
                'reason' => $request->reason,
                'status' => 'rejected'
            ]);

            /** Report Action */
            $this->report(__("messages.report_product_rejected"), 'product', $product);

            // notification
            $product->user->notify(new ProductStatus($product, 'reject'), true);

            return redirect()->route('admin.products.index')->with('message', [__('messages.product_rejected')]);
        }

        return redirect()->route('admin.products.index')->withErrors([__('messages.unknown_error')]);
    }

    /**
     * import product from digikala
     */
    public function import_digikala(Request $request, ProductService $productService)
    {
        $request->validate([
            'uuid' => 'required',
            'category' => 'required',
            'commission' => 'required',
            'status' => 'required',
        ]);

        /** current user
         * @var \App\Models\User $user
         */
        $user = auth()->user();

        // check for existing product
        $productUUID = str_replace(['dkp-', 'DKP-'], '', trim($request->uuid));
        if (Product::where('uuid', 'p-' . $productUUID)->first() != null) {
            return redirect()->back()->withErrors([__('messages.product_with_this_uuid_is_exist')]);
        }

        // fetch product information
        try {
            $client = new Client();
            $response = $client->get('https://api.digikala.com/v2/product/' . $productUUID . '/');
            $response = (string)$response->getBody();
            $response = json_decode($response);
        } catch (Exception $e) {
            return redirect()->back()->withErrors([$e->getMessage()]);
        }

        // handle rewuest status
        if ($response->status != 200 || !isset($response->data->product->title_fa)) {
            return redirect()->back()->withErrors([__('messages.product_not_found')]);
        }

        // extract digikala product images
        $digikalaImages = [];
        if (!empty($response->data->product->images->main?->url[0] ?? null)) {
            $digikalaImages[] = $response->data->product->images->main->url[0];
        }
        if (!empty($response->data->product->images->list) && is_array($response->data->product->images->list)) {
            $count = min(4, count($response->data->product->images->list));
            for ($i = 0; $i < $count; $i++) {
                if (!empty($response->data->product->images->list[$i]->url[0])) {
                    $digikalaImages[] = $response->data->product->images->list[$i]->url[0];
                }
            }
        }

        // upload images
        $images = null;
        if (!empty($digikalaImages) && is_array($digikalaImages) && count($digikalaImages) > 0) {
            foreach ($digikalaImages as $image) {
                if ($image) {
                    $fileData = $this->uploadFromUrl($image, $user);
                    if ($fileData && isset($fileData['id'])) {
                        $images[] = $fileData['id'];
                    }
                }
            }
        }

        // get attrs
        $attrs = [];
        $attributes = $response->data->product->review->attributes ?? [];
        if (is_array($attributes)) {
            foreach ($attributes as $attr) {
                if (!empty($attr->title) && !empty($attr->values[0])) {
                    $attrs[] = [
                        'key'   => $attr->title,
                        'value' => $attr->values[0],
                    ];
                }
            }
        }

        // seo description
        $seoDescription = $response->data->product->review?->description ?? null;
        if ($seoDescription !== null) {
            $lines = preg_split('/\r\n|\r|\n/', trim($seoDescription));
            $firstThree = array_slice($lines, 0, 2);
            $seoDescription = implode("\n", $firstThree);
        }

        // tags and seo keywords
        $tags = [];
        if (is_array($response->data->product->tags ?? [])) {
            foreach ($response->data->product->tags ?? [] as $tag) {
                if (!empty($tag->name)) {
                    $tags[] = [
                        'value' => $tag->name
                    ];
                }
            }
            if (count($tags) > 0)
                $tags = json_encode($tags, JSON_UNESCAPED_UNICODE);
        }
        $tags = is_array($tags) && count($tags) == 0 ? null : $tags;

        // add data to request
        $request->merge([
            'brand' => $response->data->product->brand?->title_fa ?? null,
            'title' => $response->data->product->title_fa,
            'title_en' => $response->data->product->title_en ?? null,
            'content' => $response->data->product->review?->description ?? '<p></p>',
            'warnings' => $response->data->product->category?->return_reason_alert ?? null,
            'images' => $images,
            'attrs' => $attrs,
            'seo_title' => $response->data->product->title_fa,
            'seo_description' => $seoDescription,
            'seo_keywords' => $tags,
            'tags' => $tags,
        ]);

        // create product
        $commission = 0;
        if ($request->exists('commission') && $request->commission != null) {
            if ($request->commission > 100 || $request->commission < 0) {
                return redirect()->back()->withErrors([__('messages.seller_commission_incorrect')]);
            }
            $commission = $request->commission;
        }

        $product = $user->products()->create([
            'edited_by' => $user->id,
            'brand_id' => $productService->initBrand($user, $request),
            'category_id' => $request->category['id'],
            'uuid' => 'p-' . $productUUID,
            'title' => $request->title,
            'title_en' => $request->exists('title_en') ? $request->title_en : null,
            //'slug' => $request->exists('slug') && $request->slug != null ? $request->slug : null,
            'content' => $request->exists('content') ? $request->content : null,
            'warnings' => $request->exists('warnings') ? $request->warnings : null,

            'images' => $request->exists('images') && $request->images != null && count($request->images) > 0 ? serialize($request->images) : null,
            //'videos' => $request->exists('videos') ? serialize($request->videos) : null,

            'attrs' => $request->exists('attrs') ? serialize($request->attrs) : null,

            'seo_title' => $request->exists('seo_title') ? $request->seo_title : null,
            'seo_description' => $request->exists('seo_description') ? $request->seo_description : null,
            'seo_keywords' => $request->exists('seo_keywords') ? $request->seo_keywords : null,
            'seo_canonical' => $request->exists('seo_canonical') ? urldecode($request->seo_canonical) : null,

            'in_stock_status' => true,
            'inquiry_options' => serialize([
                "landline_phone" => null,
                "cellular_phone" => null
            ]),

            'commission' => $commission,

            'is_vip' => false,
            'comment_status' => true,
            'question_status' => true,

            'reason' => 'create',
            'status' => $request->status,
        ]);

        /** add price model */
        //$productService->addPriceModel($product, $request);

        /** create and sync tags */
        $productService->syncTags($product, $request);

        /** Report Action */
        $this->report(__("messages.report_product_created"), 'product', $product);

        return redirect()->back()->with('message', [__('messages.product_created')]);
    }

    private function uploadFromUrl($url, $user)
    {
        try {
            $tmpFile = tempnam(sys_get_temp_dir(), 'img');
            file_put_contents($tmpFile, file_get_contents($url));

            $fileInfo = pathinfo(parse_url($url, PHP_URL_PATH));
            $originalExtension = strtolower($fileInfo['extension'] ?? 'jpg');
            $fileType = match ($originalExtension) {
                'jpeg', 'jpg', 'png', 'webp', 'gif', 'svg', 'avif' => 'image',
                default => null,
            };

            if ($fileType !== 'image') return null;

            $manager = ImageManager::withDriver(new Driver());
            $imageTemp = $manager->read($tmpFile);
            $imageResolution = $imageTemp->width() . '×' . $imageTemp->height();

            $optimizationPercent = 30;
            $finalImageTemp = $imageTemp->encode(new WebpEncoder($optimizationPercent))->__toString();
            $fileFormat = 'webp';

            $fileName = 'file.' . time() . '.' . rand(10000, 99999) . '.' . $fileFormat;
            $fileSaveAddressNoName = 'library/' . date('Y-m-d') . '/' . $user->id;
            $fileSaveAddressImage = $fileSaveAddressNoName . '/' . $fileName;

            $uploadResult = Storage::disk('media')->put($fileSaveAddressImage, $finalImageTemp, 'public');

            if ($uploadResult) {
                return $user->files()->create([
                    'name' => $fileName,
                    'url' => '/media/' . $fileSaveAddressImage,
                    'extension' => $fileFormat,
                    'size' => strlen($finalImageTemp) / 1000,
                    'resolution' => $imageResolution,
                    'type' => $fileType,
                ])->toArray();
            }

            return null;
        } catch (\Exception $e) {
            report($e);
            return null;
        }
    }

    /**
     * export storage
     */
    public function export(Storage $storage, Request $request)
    {
        $request->validate([
            'type' => 'required',
            'category' => 'required',
            'brand' => 'required',
        ]);

        /** Report Action */
        $this->report(__("messages.report_products_exported"));

        return Excel::download(new ProductsExport($request->type, $request->category, $request->brand), 'خروجی محصولات.xlsx');
    }

    /**
     * import storage
     */
    public function import(Storage $storage, Request $request)
    {
        $request->validate([
            'file' => 'required',
        ]);

        /** Report Action */
        $this->report(__("messages.report_products_imported"));

        Excel::import(new ProductsImport(), $request->file('file'));

        return redirect()->back()->with('message', [__('messages.excel_imported_to_products_list')]);
    }
}
