<?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\Models\Filter;
use App\Models\FilterKey;
use App\Models\FilterValue;
use App\Notifications\ProductStatus;
use App\Services\Admin\Products\ProductService;
use Exception;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
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"),
            'productsStatistics' => $productService->getProductsStatistics(),
            '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(),
            'filterGroupList' => Filter::whereHas('keys')->get()->map(fn($filter) => [
                'id' => $filter->id,
                'title' => $filter->title,
                'keys' => $filter->keys->map(fn($key) => [
                    'id' => $key->id,
                    'title' => $key->title,
                    'value' => null,
                ]),
            ]),
        ]);
    }

    /**
     * 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->input('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);

        /** add sub categories */
        $subCategories = $request->input('sub_categories', []);
        $subCategories = array_filter($subCategories, fn($catId) => $catId != $product->category_id);
        $product->productCategories()->sync($subCategories);

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

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

        /** sync product filters */
        $productService->syncFilters($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 sub categories */
        $subCategories = $product->productCategories()->pluck('id')->toArray();
        $subCategories = array_filter($subCategories, fn($id) => $id != $product->category_id);
        $clonedProduct->productCategories()->sync($subCategories);

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

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

        /** copy product filters */
        $productService->cloneFilters($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')]);

        // sub categories
        $subCategories = $product->productCategories()->select('id', 'title')->get();

        // clear product filters cache
        Cache::forget('product_filters_' . $product->id);

        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,
                'get_filters' => $product->get_filters,
                '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,
                'sub_categories' => $subCategories,
            ],
            'categories' => $productService->getCategoriesBranchWithSpecification($product),
            'statusList' => $this->contentStatusList(),
            'videoTypeList' => $this->videoTypeList(),
            'filterGroupList' => Filter::whereHas('keys')->get()->map(fn($filter) => [
                'id' => $filter->id,
                'title' => $filter->title,
                'keys' => $filter->keys->map(fn($key) => [
                    'id' => $key->id,
                    'title' => $key->title,
                    'value' => null,
                    'suggestions' => null,
                ]),
            ]),
        ]);
    }

    /**
     * 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->input('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);
        }

        /** add sub categories */
        $subCategories = $request->input('sub_categories', []);
        $subCategories = array_filter($subCategories, fn($catId) => $catId != $product->category_id);
        $product->productCategories()->sync($subCategories);

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

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

        /** sync product filters */
        $productService->syncFilters($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')]);
    }

    /** refresh digikala cookie */
    private function refreshDigikalaCookie()
    {
        $url = "https://api.digikala.com/v2/search/";

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_NOBODY, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)",
        ]);

        $response = curl_exec($ch);

        $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
        $header = substr($response, 0, $header_size);

        curl_close($ch);

        preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $header, $matches);

        $cookie = null;

        foreach ($matches[1] as $match) {
            if (strpos($match, 'digicdn_cookie=') !== false) {
                $cookie = trim(str_replace('digicdn_cookie=', '', $match));
                break;
            }
        }

        if ($cookie) {
            file_put_contents(storage_path('app/digikala_cookie.txt'), $cookie);
        }

        return $cookie;
    }

    /** get digikala cookie */
    private function getDigikalaCookie()
    {
        $cookieFile = storage_path('app/digikala_cookie.txt');
        if (file_exists($cookieFile)) {
            $cookie = trim(file_get_contents($cookieFile));
            if (!empty($cookie)) {
                return $cookie;
            }
        }
        return $this->refreshDigikalaCookie();
    }

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

        /** @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')]);
        }

        /** digikala request with cookie retry */
        $maxAttempts = 3;
        $attempt = 0;
        $success = false;
        $response = null;

        do {
            $attempt++;

            // 1) get current cookie or generate new one
            $DKCookie = $this->getDigikalaCookie();

            try {
                $client = new Client([
                    'headers' => [
                        'Cookie' => 'digicdn_cookie=' . $DKCookie . ';',
                        'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
                        'Accept' => 'application/json',
                    ],
                    'timeout' => 10,
                ]);

                $raw = $client->get('https://api.digikala.com/v2/product/' . $productUUID . '/');
                $response = json_decode((string)$raw->getBody());

                // check if valid product received
                if ($response->status == 200 && isset($response->data->product->title_fa)) {
                    $success = true;
                    break;
                }

                // response invalid → refresh cookie & retry
                $this->refreshDigikalaCookie();
            } catch (\Exception $e) {
                // error during request → refresh cookie & retry
                $this->refreshDigikalaCookie();
            }
        } while ($attempt < $maxAttempts);

        if (!$success || !$response) {
            return redirect()->back()->withErrors([__('messages.product_not_found')]);
        }

        // extract digikala 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)) {
            foreach ($digikalaImages as $image) {
                if ($image) {
                    $fileData = $this->uploadFromUrl($image, $user);
                    if ($fileData && isset($fileData['id'])) {
                        $images[] = $fileData['id'];
                    }
                }
            }
        }

        // attributes
        $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));
            $seoDescription = implode("\n", array_slice($lines, 0, 2));
        }

        // tags
        $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;

        /** apply data to reuest */
        $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->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->title_en ?? null,
            'content' => $request->content,
            'warnings' => $request->warnings,
            'images' => $images ? serialize($images) : null,
            'attrs' => serialize($attrs),
            'seo_title' => $request->seo_title,
            'seo_description' => $request->seo_description,
            'seo_keywords' => $request->seo_keywords,
            'seo_canonical' => $request->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,
        ]);

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

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

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

    private function uploadFromUrl($url, $user)
    {
        try {
            $response = Http::timeout(8)->withHeaders([
                'User-Agent' => 'Mozilla/5.0',
            ])->get($url);

            if (!$response->successful()) {
                return null;
            }

            $tmpFile = tempnam(sys_get_temp_dir(), 'img');
            file_put_contents($tmpFile, $response->body());

            $finfo = finfo_open(FILEINFO_MIME_TYPE);
            $mime  = finfo_file($finfo, $tmpFile);

            $allowed = [
                'image/jpeg',
                'image/png',
                'image/webp',
                'image/gif',
                'image/avif',
            ];

            if (!in_array($mime, $allowed)) {
                return null;
            }

            $fileType = 'image';

            $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 = $user->id . '_' . time() . '_' . rand(10000, 99999) . '.' . $fileFormat;
            $fileSaveAddress = 'library/' . date('Y-m-d') . '/' . $user->id . '/' . $fileName;

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

            if (!$uploadResult) return null;

            return $user->files()->create([
                'name' => $fileName,
                'url' => '/media/' . $fileSaveAddress,
                'extension' => $fileFormat,
                'size' => strlen($finalImageTemp) / 1000,
                'resolution' => $imageResolution,
                'type' => $fileType,
            ])->toArray();
        } 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')]);
    }
}
