<?php

namespace App\Http\Livewire;

use App\Models\AnnexOther;
use Illuminate\Support\Facades\DB;
use Livewire\Component;
use Livewire\WithPagination;
use App\Traits\OrderByTable;

class AnnexOthersController extends Component
{
    use WithPagination;
    use OrderByTable;

    public $search, $selected_id, $pageTitle, $componentName, $count_reg;
    public $name, $description, $status, $content;
    public $breadcrumb_show = true;

    private $pagination = 9;

    protected $paginationTheme = 'bootstrap';

    public function mount()
    {
        UserAuthPermission('Annex_others_index');
        $this->pageTitle = 'Listado';
        $this->componentName = 'Anexos OtroSí';
    }

    public function render()
    {
        if (strlen($this->search) > 0)
            {
                $annex_others = AnnexOther::where('name', 'like', '%' . $this->search . '%')
                            ->where('description', 'like', '%' . $this->search . '%')
                            ->orderBy($this->sortBy, $this->sortDirection)
                            ->paginate($this->pagination);
            }
            else
            {
                $annex_others = AnnexOther::orderBy($this->sortBy, $this->sortDirection)
                                ->paginate($this->pagination);
            }

        $this->count_reg = $annex_others->total();

        return view('livewire.annex-others.component',compact('annex_others'))
        ->extends('layouts.theme.admin.app')
        ->section('content');
    }

    public function resetUI()
    {
        $this->search = '';
        $this->name = '';
        $this->description = '';
        $this->status = '';
        $this->content = '';
        $this->resetValidation();
        $this->resetPage();
    }

    public function openAdd()
    {
        $useractions = UserAuthPermissionActions('Annex_others_create');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }
        $this->selected_id = 0;
        $this->resetUI();
        $this->emit('show-modal','Abrir Modal');
    }

    public function Store()
    {
        $useractions = UserAuthPermissionActions('Annex_others_create');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }

        $rules = [
            'name' => 'required|string|max:99|unique:annex_others,name',
            'description' => 'required',
            'status' => 'required',
            'content' => 'required',
        ];

        $messages = [
            'name.required' => 'El nombre del anexo es requerido',
            'name.max' => 'El nombre del anexo no puede tener más de 99 caracteres',
            'name.unique' => 'El nombre del anexo ya existe',
            'description.required' => 'La descripción del anexo es requerida',
            'status.required' => 'El estado del anexo es requerido',
            'content.required' => 'El contenido del anexo es requerido',
        ];

        $this->validate($rules, $messages);

        AnnexOther::create([
            'name' => $this->name,
            'description' => $this->description,
            'status' => $this->status,
            'content' => $this->content,
        ]);

        $this->resetUI();
        $this->emit('item-added', 'Anexo OtroSí agregado correctamente');

    }

    public function Edit(AnnexOther $annex_other)
    {
        $useractions = UserAuthPermissionActions('Annex_others_update');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }

        $this->selected_id = $annex_other->id;
        $this->name = $annex_other->name;
        $this->description = $annex_other->description;
        $this->status = $annex_other->status;
        $this->content = $annex_other->content;

        $this->emit('show-modal', 'Abrir Modal Editar');
    }

    public function Update()
    {
        $useractions = UserAuthPermissionActions('Annex_others_update');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }

        $rules = [
            'name' => 'required|string|max:99|unique:annex_others,name,' . $this->selected_id,
            'description' => 'required',
            'status' => 'required',
            'content' => 'required',
        ];

        $messages = [
            'name.required' => 'El nombre del anexo es requerido',
            'name.max' => 'El nombre del anexo no puede tener más de 99 caracteres',
            'name.unique' => 'El nombre del anexo ya existe',
            'description.required' => 'La descripción del anexo es requerida',
            'status.required' => 'El estado del anexo es requerido',
            'content.required' => 'El contenido del anexo es requerido',
        ];

        $this->validate($rules, $messages);

        $annex_other = AnnexOther::find($this->selected_id);
        $annex_other->update([
            'name' => $this->name,
            'description' => $this->description,
            'status' => $this->status,
            'content' => $this->content,
        ]);

        $this->resetUI();
        $this->emit('item-updated', 'Anexo OtroSí actualizado correctamente');
    }

    protected $listeners = [
        'deleteRow' => 'Destroy',
        'resetUI' => 'resetUI'
    ];

    public function Destroy(AnnexOther $annex_other)
    {
        $useractions = UserAuthPermissionActions('Annex_others_delete');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }

        if ($annex_other)
        {
            $annex_other_contract_user = DB::table('annex_others_contract_users')->where('annex_other_id', $annex_other->id)->count();

            if ($annex_other_contract_user > 0) {
                $this->emit('item-deleted', 'No se puede eliminar el anexo OtroSí, ya que está asociado a un contrato');
                return;
            }

            $annex_other->delete();
            $this->resetUI();
            $this->emit('item-deleted', 'Anexo OtroSí eliminado correctamente');
        }
    }

}

