<?php

namespace App\Livewire\Admin\Suggestion;

use App\Models\Product;
use App\Models\Suggestion;
use App\Rules\ListIndexRule;
use Illuminate\Support\Facades\DB;
use Livewire\Component;

class Create extends Component
{
    public $product, $products, $isOpen = false, $list = [], $search;

    public function render()
    {
        return view('livewire.admin.suggestion.create');
    }

    public function mount()
    {
        
        $this->list = Suggestion::join('products','products.id','=','suggestions.suggestion_id')
        ->where('suggestions.product_id',$this->product->id)
        ->select('products.id','products.name')
        ->get()->toArray();
        // $this->data = Grade::all();
        // $this->educational_levels_schools = $this->educationalLevelsSchool();
        // $this->educational_levels_school_id = $this->educational_levels_schools->first()->id;
        $this->searchElement();
    }

    public function openModal()
    {
        $this->isOpen = true;
    }

    public function closeModal()
    {
        $this->isOpen = false;
    }

    public function selectProduct($id)
    {
        $product = Product::find($id);
        $exists = collect($this->list)->firstWhere('id', $product->id);
        if (is_null($exists)) {
            array_push($this->list, ['id' => $id, 'name' => $product->name]);
        }
        $this->searchElement();
    }

    public function deselectProduct($id)
    {
        $this->list = collect($this->list)->reject(function ($item) use ($id) {
            return $item['id'] == $id;
        })->values()->all();
        $this->searchElement();
    }

    public function searchElement()
    {
        $ids = collect($this->list)
            ->pluck('id')
            ->toArray();
        $this->products = Product::whereNotIn('id', $ids)
            ->where('id','!=',$this->product->id)
            ->where('status_id',4)
            ->where('name', 'like', '%' . $this->search . '%')
            ->get();
    }

    public function save()
    {
        $this->validate([
            'list'  => ['array','min:1',new ListIndexRule]
        ]);

        DB::beginTransaction();
        try {
            //
            foreach ($this->product->suggestions as $suggestion) $suggestion->delete();
            foreach ($this->list as $item) {
                Suggestion::create([
                    'product_id' => $this->product->id,
                    'suggestion_id' => $item['id']
                ]);
            }

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