<?php

namespace App\Http\Livewire;

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

class PermissionsController extends Component
{
    use WithPagination;
    use OrderByTable;

    public $permissionName, $search, $selected_id, $pageTitle, $componentName, $count_reg;
    public $breadcrumb_show = true;

    private $pagination = 10;

    protected $paginationTheme = 'bootstrap';

    public function mount()
    {
        UserAuthPermission('Permission_index');
        $this->pageTitle = 'Listado';
        $this->componentName = 'Permisos';
        $this->sortBy = 'id';
        $this->sortDirection = 'asc';
    }

    public function render()
    {
        if (strlen($this->search) > 0)
            $permissions = Permission::where('name', 'like', '%' . $this->search. '%')->orderBy($this->sortBy, $this->sortDirection)->paginate($this->pagination);
        else
            $permissions = Permission::orderBy($this->sortBy, $this->sortDirection)->paginate($this->pagination);
        $this->count_reg = $permissions->total();
        return view('livewire.permissions.component',[
            'permissions' => $permissions
        ])
        ->extends('layouts.theme.admin.app')
        ->section('content');
    }

    public function openAdd()
    {
        $useractions = UserAuthPermissionActions('Permission_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 CreatePermission()
    {
        $useractions = UserAuthPermissionActions('Permission_create');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }
        $rules = [
            'permissionName' => 'required|min:3|unique:permissions,name|'
        ];

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

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

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

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

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

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

    public function UpdatePermission()
    {
        $useractions = UserAuthPermissionActions('Permission_update');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }
        $rules = [
            'permissionName' => "required|min:3|unique:permissions,name, {$this->selected_id}|"
        ];

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

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

        $permiso = Permission::find($this->selected_id);
        $permiso->name = $this->permissionName;
        $permiso->save();

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

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

    public function Destroy($id)
    {
        $useractions = UserAuthPermissionActions('Permission_delete');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }
        $rolesCount = Permission::find($id)->getRoleNames()->count();
        if($rolesCount > 0)
        {
            $this->emit('item-error', 'No se puede eliminar el Permiso porque tiene Roles asociados');
            return;
        }

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

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