<?php

namespace App\Http\Livewire;

use Livewire\Component;
use App\Models\Unit;

class Units extends Component
{
    public $search = '', $data, $units, $unit_id;
    public $name, $description;
    public $updateMode = false;
    public $imputActive = false;

    protected $rules = ['name' => "required"];

    public function render()
    {
        $this->units = Unit::All();
        $this->data = ($this->search)
        ? Unit::where('id', 'like', '%'.$this->search.'%')
            ->orWhere('name', 'like', '%'.$this->search.'%')
            ->orWhere('description', 'like', '%'.$this->search.'%')
            ->get()
        : Unit::orderBy('id', 'DESC')->get();
        return view('livewire.units');
    }

    public function resetInput()
    {
        $this->name         = null;
        $this->description = null;
        $this->updateMode = false;
        // $this->emitUpdates();
    }

    public function save()
    {
        if ($this->updateMode)
            return $this->update();

        return $this->store();
    }

    public function store()
    {
        $this->validate([
            'name'   => 'required',

        ]);
        Unit::create([
            'name'          => $this->name,
            'description'   => $this->description
        ]);
        $this->emit('notify:toast', ['type'  => 'success', 'name' => 'Registro creado...']);
        $this->resetInput();
    }

    public function edit($id)
    {
        $record             = Unit::findOrFail($id);
        $this->unit_id    =  $id;
        $this->name         = $record->name;
        $this->description         = $record->description;

        // $this->emitUpdates();

        $this->updateMode = true;

        $this->emit('notify:toast', ['type'  => 'success', 'name' => 'Registro cargado...']);
    }

    public function update()
    {


        if ($this->unit_id) {
            $record = Unit::find($this->unit_id);
            $record->update([
                'name' => $this->name,
                'description' => $this->description
            ]);

            return redirect()->back()->with('message', 'Registro actualizado...');
            $this->resetInput();
            $this->updateMode = false;
        }
    }

    public function destroy($id)
    {
        if ($id) {
            $record = Unit::find($id);
            $record->delete();

            $this->emit('notify:toast', ['type'  => 'success', 'name' => 'Registro eliminado...']);
            //$this->resetInput();
        }
    }
}

