<?php

namespace App\Http\Livewire;

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

class AssignController extends Component
{
    use WithPagination;
    use OrderByTable;

    public $role, $componentName, $pageTitle, $permisosSelected=[], $old_permissions = [], $search, $count_reg;
    public $breadcrumb_show = true;

    private $pagination = 10;

    protected $paginationTheme = 'bootstrap';

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

    public function render()
    {
        $permissions = Permission::select('name', 'id', DB::raw("0 as checked"))
        ->where('name', 'like', '%' . $this->search. '%')
        ->orderBy($this->sortBy, $this->sortDirection)
        ->paginate($this->pagination);

        if($this->role != 'Seleccionar')
        {
            $list = Permission::join('role_has_permissions as rp','rp.permission_id','permissions.id')
            ->where('role_id', $this->role)->pluck('permissions.id')->toArray();

            $this->old_permissions = $list;
        }

        if($this->role != 'Seleccionar')
        {
            foreach ($permissions as $permission) {
                $role = Role::find($this->role);
                $hasPermission = $role->hasPermissionTo($permission->name);
                if ($hasPermission)
                {
                    $permission->checked = 1;
                }
            }
        }
        $this->count_reg = $permissions->total();
        return view('livewire.assign.component', [
            'roles' => Role::orderBy('name','asc')->get(),
            'permissions' => $permissions
        ])->extends('layouts.theme.admin.app')->section('content');
    }

    protected $listeners = ['revoke-all' => 'RemoveAll'];

    public function RemoveAll()
    {
        $useractions = UserAuthPermissionActions('Assign_revoke_all');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }
        if ($this->role == 'Seleccionar')
        {
            $this->emit('sync-error','Seleccionar un Rol valido');
            return;
        }

        $role = Role::find($this->role);
        $role->syncPermissions([0]);

        $this->emit('remove-all',"Se revocaron todos los permisos al rol $role->name");

    }

    public function SyncAll()
    {
        $useractions = UserAuthPermissionActions('Assign_sync_all');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }
        if ($this->role == 'Seleccionar')
        {
            $this->emit('sync-error','Seleccionar un Rol valido');
            return;
        }

        $role = Role::find($this->role);
        $permisos = Permission::pluck('id')->toArray();
        $role->syncPermissions($permisos);
        $this->emit('sync-all',"Se sincronizaron todos los permisos al rol $role->name");
    }

    public function SyncPermission($state, $permisoName)
    {
        $useractions = UserAuthPermissionActions('Assign_toggle_permission');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }
        debug("Estate: ",$state, "PermisoName: ",$permisoName);
        if ($this->role != 'Seleccionar')
        {
            $roleName = Role::find($this->role);

            if($state)
            {
                $roleName->givePermissionTo($permisoName);
                $this->emit('permi',"Permiso asignado correctamente");
            }
            else
            {
                $roleName->revokePermissionTo($permisoName);
                $this->emit('permi',"Permiso revocado correctamente");
            }
        }
        else
        {
            $this->emit('permi',"Seleccione un Rol");
        }
    }
}
