<?php

namespace App\Http\Livewire;

use Livewire\Component;

class AllegatiGalleryType extends Component
{

    public $records, $name, $file_type, $dataId, $update = false, $add = false;

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

    protected $messages = [
        'name.required' => 'Il nome è obbligatorio'
    ];

    public function resetFields(){
        $this->name = '';
        $this->file_type = 0;
    }

    public function render()
    {
        $this->records = \App\Models\AllegatiGalleryType::get();
        return view('livewire.allegati-gallery-type');
    }

    public function add()
    {
        $this->resetFields();
        $this->add = true;
        $this->update = false;
    }

    public function store()
    {
        $this->validate();
        try {
            \App\Models\AllegatiGalleryType::create([
                'name' => $this->name,
                'file_type' => $this->file_type,
            ]);
            session()->flash('success','Record creato');
            $this->resetFields();
            $this->add = false;
        } catch (\Exception $ex) {
            session()->flash('error','Errore in fase di salvataggio');
        }
    }

    public function edit($id){
        try {
            $record = \App\Models\AllegatiGalleryType::findOrFail($id);
            if( !$record) {
                session()->flash('error','Record non trovato');
            } else {
                $this->name = $record->name;
                $this->file_type = $record->file_type;
                $this->dataId = $record->id;
                $this->update = true;
                $this->add = false;
            }
        } catch (\Exception $ex) {
            session()->flash('error','Errore');
        }
    }

    public function update()
    {
        $this->validate();
        try {
            \App\Models\AllegatiGalleryType::whereId($this->dataId)->update([
                'name' => $this->name,
                'file_type' => $this->file_type,
            ]);
            session()->flash('success','Record aggiornato');
            $this->resetFields();
            $this->update = false;
        } catch (\Exception $ex) {
            session()->flash('success','Errore');
        }
    }

    public function cancel()
    {
        $this->add = false;
        $this->update = false;
        $this->resetFields();
    }

    public function delete($id)
    {
        try{
            \App\Models\AllegatiGalleryType::find($id)->delete();
            session()->flash('success',"Record eliminato");
        }catch(\Exception $e){
            session()->flash('error',"Errore");
        }
    }
}
