<?php

namespace App\Http\Livewire;

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

class PublicHealthEntityController extends Component
{
    use WithPagination;
    use OrderByTable;
    public $name, $search, $selected_id, $pageTitle, $componentName,  $count_reg;
    public $breadcrumb_show = true;

    private $pagination = 10;

    protected $paginationTheme = 'bootstrap';

    public function mount()
    {
        UserAuthPermission('Eps_index');
        $this->pageTitle = 'Listado';
        $this->componentName = 'Eps';
    }

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

        $this->count_reg = $epss->total();
        return view('livewire.eps.component',compact('epss'))
        ->extends('layouts.theme.admin.app')
        ->section('content');
    }

    public function openAdd()
    {
        $useractions = UserAuthPermissionActions('Eps_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('Eps_create');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }
        $rules = [
            'name' => 'required|min:2|unique:public_health_entities,name|'
        ];

        $messages = [
            'name.required' => 'El nombre de la EPS es requerido',
            'name.unique' => 'La Eps ya existe',
            'name.min' => 'El nombre de la Eps debe tener mínimo 2 caracteres'
        ];

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

        PublicHealthEntity::create(['name' => $this->name]);

        $this->emit('item-added', 'Se registró la Eps con éxito');
        $this->resetUI();
    }

    public function Edit(PublicHealthEntity $eps)
    {
        $useractions = UserAuthPermissionActions('Eps_update');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }
        $this->selected_id = $eps->id;
        $this->name = $eps->name;

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

    public function Update()
    {
        $useractions = UserAuthPermissionActions('Eps_update');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }
        $rules = [
            'name' => "required|min:2|unique:public_health_entities,name, {$this->selected_id}|"
        ];

        $messages = [
            'name.required' => 'El nombre de la Eps es requerido',
            'name.unique' => 'La Eps ya existe',
            'name.min' => 'El nombre de la Eps debe tener mínimo 2 caracteres'
        ];

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

        $eps = PublicHealthEntity::find($this->selected_id);
        $eps->name = $this->name;
        $eps->save();

        $this->emit('item-updated', 'Se actualizó la Eps con éxito');
        $this->resetUI();
    }

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

    public function Destroy($id)
    {
        $useractions = UserAuthPermissionActions('Eps_delete');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }
        $epsUser = DB::table('company_user')->where('eps_id', $id)->count();
        if ($epsUser > 0) {
            $this->emit('item-deleted', 'No se puede eliminar la Eps porque tiene usuarios asociados');
            return;
        }
        $epsFamily = DB::table('family_users')->where('eps_id', $id)->count();
        if ($epsFamily > 0) {
            $this->emit('item-deleted', 'No se puede eliminar la Eps porque tiene familiares asociados');
            return;
        }

        PublicHealthEntity::find($id)->delete();
        $this->emit('item-deleted', 'Se eliminó la Eps con éxito');
    }

    public function resetUI()
    {
        $this->name = '';
        $this->search = '';
        $this->selected_id = 0;
        $this->resetErrorBag();
    }
}
