<?php

namespace App\Livewire\Admin\ImageGallery;

use App\Helpers\Utility;
use App\Models\ProductImage;
use Illuminate\Support\Facades\DB;
use Livewire\Component;
use Livewire\WithFileUploads;

class Edit extends Component
{
    use WithFileUploads;

    public $product, $images = [], $image, $product_image, $image_id, $type = 0;

    public function render()
    {
        return view('livewire.admin.image-gallery.edit');
    }

    public function mount()
    {
        $this->getImages();
    }

    public function create()
    {
        if (count($this->product->images) >= 10) {
            $this->addError('max', 'Maximo 10 imagenes por producto.');
            return;
        }
        $this->type = 1;
    }

    public function edit($id)
    {
        $this->product_image = ProductImage::where([
            ['id','=',$id],
            ['product_id','=',$this->product->id]
        ])->first();
        $this->type = 2;
        // info($this->type);
    }

    public function delete($id)
    {
        try {
            $image = ProductImage::find($id);
            Utility::deleteImage($image->path,'gallery');
            $image->delete();
        } catch (\Throwable $th) {
            //throw $th;
            info($th->getMessage());
        }
        $this->getImages();
    }

    public function cancel()
    {
        $this->type = 0;
    }

    public function slider($id)
    {
        $image = ProductImage::find($id);
        $image->update(['slider'=> $image->slider == 0 ? 1 : 0]);
        $this->getImages();
    }

    public function getImages()
    {
        $this->images = $this->product->images;
        $this->image = null;
    }

    public function save()
    {
        $this->validate([
            'image'     => 'required|image|mimes:jpeg,png,jpg|max:2048',
        ]);

        DB::beginTransaction();
        try {
            //
            $image = Utility::saveImage($this->image,'gallery');
            if ($this->type == 1) {
                ProductImage::create([
                    'path'=> $image,
                    'product_id' => $this->product->id
                ]);
            }else{
                $oldImage = $this->product_image->path;
                $this->product_image->update([
                    'path'=> $image,
                ]);
                Utility::deleteImage($oldImage,'gallery');
            }
            $this->getImages();
            $this->type = 0;
            DB::commit();
            // session()->flash('status', 'Los datos se guardaron correctamente.');
            // return redirect()->route('schools.index');
        } catch (\Throwable $th) {
            DB::rollBack();
            info($th->getMessage());
        }
    }
}
