<?php

namespace App\Http\Livewire;


use Livewire\Component;
use Livewire\WithPagination;
use Spatie\Permission\Models\Role;
use App\Traits\OrderByTable;

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

    private $pagination = 10;
    /*
    public function paginationView()
    {
        return 'vendor.livewire.bootstrap';
    }
    */
    protected $paginationTheme = 'bootstrap';

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

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

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

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

        $messages = [
            'roleName.required' => 'El nombre del Rol es requerido',
            'roleName.unique' => 'El Rol ya existe',
            'roleName.min' => 'El nombre del Rol debe tener mínimo 2 cáracteres'
        ];

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

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

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

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

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

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

        $messages = [
            'roleName.required' => 'El nombre del Rol es requerido',
            'roleName.unique' => 'El Rol ya existe',
            'roleName.min' => 'El nombre del Rol debe tener mínimo 2 cáracteres'
        ];

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

        $role = Role::find($this->selected_id);
        $role->name = $this->roleName;
        $role->save();

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

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

    public function Destroy($id)
    {
        $useractions = UserAuthPermissionActions('Role_delete');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }
        $permissionsCount = Role::find($id)->permissions->count();
        if($permissionsCount > 0)
        {
            $this->emit('item-error', 'No se puede eliminar el Rol porque tiene permisos asociados');
            return;
        }

        Role::find($id)->delete();
        $this->emit('item-deleted', 'Se eliminó el Rol con éxito');
    }

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