<?php

namespace App\Livewire\Admin\Product;

use App\Helpers\Utility;
use App\Models\Category;
// use App\Models\ClothingSize;
// use App\Models\ClothingSizesProduct;
use App\Models\MeasurementUnit;
use App\Models\ProductPrice;
use App\Models\Status;
use App\Models\Subcategory;
// use App\Rules\ExistClothingSizeRule;
// use App\Rules\IntegerClothingSizeRule;
// use App\Rules\RepeatClothingSizeRule;
use App\Rules\StatusRule;
use Illuminate\Support\Facades\DB;
use Livewire\Component;
use Livewire\Features\SupportFileUploads\WithFileUploads;

class Edit extends Component
{
    use WithFileUploads;
    
    public $product, $name, $categories, $category_id, $subcategories, $subcategory_id, $description, $quantity, $code, $price, $status_id, $status, $iva, $measurement_units, $measurement_unit_id;
    public $clothing_sizes_data, $clothing_sizes = [];
    public $contents, $introduction, $origin, $roasting, $image;

    public function render()
    {
        return view('livewire.admin.product.edit');
    }

    public function mount()
    {
        $this->price = $this->product->price->price;
        $this->name = $this->product->name;
        $this->description = $this->product->description;
        // $this->code = $this->product->code;
        $this->contents = $this->product->contents;
        $this->introduction = $this->product->introduction;
        $this->origin = $this->product->origin;
        $this->roasting = $this->product->roasting;
        $this->status_id = $this->product->status_id;
        // $this->iva = $this->product->iva;
        $this->status = Status::where('status_type_id', 2)->get();
        $this->measurement_units = MeasurementUnit::all();
        $this->measurement_unit_id = $this->product->measurement_unit_id;
        $this->categories = Category::all();
        $this->category_id = $this->product->category_id;
        // $this->subcategory_id = $this->product->subcategory_id;
        // $this->subcategories = Subcategory::where('category_id',$this->category_id)->get();
        // $this->clothing_sizes_data = ClothingSize::all();
        // $this->clothing_sizes = $this->product->clothingSizesProducts->where('status_id','=',8)->pluck('clothing_size_id');
    }

    public function selectCategory(){
        $this->subcategories = Subcategory::where('category_id',$this->category_id)->get();
        $this->subcategory_id = $this->subcategories->first()->id;
    }

    public function save()
    {
        $this->validate([
            'name'          => 'nullable|string|min:4|max:200',
            'description'   => 'nullable|string|max:200',
            'contents'      => 'required|numeric|min:0|max:99999999',
            'introduction'  => 'required|string|max:200',
            'origin'        => 'required|string|max:200',
            'roasting'      => 'required|string|max:200',
            // 'code'  => 'nullable|string|max:100',
            'price' => 'required|numeric|min:0|max:999999',
            'status_id' => ['required', 'integer', new StatusRule(2)],
            // 'iva'   => 'required|boolean',
            'measurement_unit_id' => 'required|integer|exists:measurement_units,id',
            // 'subcategory_id' => 'required|integer|exists:subcategories,id',
            'category_id'   => 'required|integer|exists:categories,id',
            'image'         => 'nullable|image|mimes:jpeg,png,jpg|max:2048',
            // 'clothing_sizes' => ['array','min:1','max:'.count($this->clothing_sizes_data), new RepeatClothingSizeRule, new IntegerClothingSizeRule, new ExistClothingSizeRule($this->clothing_sizes_data)],
        ]);
        DB::beginTransaction();
        try {
            //
            $this->product->update([
                'name'          => $this->name,
                'description'   => $this->description,
                'contents'      => $this->contents,
                'introduction'  => $this->introduction,
                'origin'        => $this->origin,
                'roasting'      => $this->roasting,
                // 'quantity'      => $this->quantity,
                // 'code'          => $this->code,
                'status_id'     => $this->status_id,
                'category_id'   => $this->category_id,
                // 'iva'           => $this->iva,
                'measurement_unit_id' => $this->measurement_unit_id,
            ]);

            if ($this->product->price->price != $this->price) {
                $prices = ProductPrice::where([
                    ['status_id','=',6],
                    ['product_id','=',$this->product->id]
                ])->get();
                foreach ($prices as $price) {
                    $price->update(['status_id' => 7]);
                }

                ProductPrice::create([
                    'price'     => $this->price,
                    'product_id'=> $this->product->id,
                    'status_id' => 6,
                ]);
            }

            if ($this->image) {
                $image = Utility::saveImage($this->image,'gallery');
                $oldImage = $this->product->images->first()->path;
                $this->product->images->first()->update([
                    'path'=> $image,
                ]);
                Utility::deleteImage($oldImage,'gallery');
            }



            // $sizes_product = ClothingSizesProduct::where('product_id','=',$this->product->id)->get();
            // foreach ($sizes_product as $size) {
            //     $size->update(['status_id' => 9]);
            // }

            // foreach ($this->clothing_sizes as $key) {
            //     $size = $sizes_product->where('clothing_size_id','=',$key)->first();
            //     if(!is_null($size)){
            //         $size->update(['status_id' => 8]);
            //     }else{
            //         ClothingSizesProduct::create([
            //             'product_id' => $this->product->id,
            //             'clothing_size_id' => $key,
            //             'status_id' => 8
            //         ]);
            //     }
            // }

            DB::commit();
            session()->flash('status', 'Los datos se guardaron correctamente.');
            return redirect()->route('products.index');
        } catch (\Throwable $th) {
            DB::rollBack();
            info($th->getMessage());
        }
    }
}
