<?php

namespace App\Http\Middleware;

use App\Modules\User\Models\Modules_user;
use Closure;
use Auth;
class CheckAuthUrl
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next,$checkurl)
    {
        $user = new Modules_user();
        if(!$user->permission_by_roles(Auth::id(),$checkurl)){
            abort(403, "No tienes autorización para ingresar.");
        }
        $perm = $request->user()->getPermissionsViaRoles();
        if ($this->url_permission($perm,'edit') == 'notauthorized') {
            abort(403, "No tienes autorización para ingresar.");
        }else if ($this->url_permission($perm,'create') == 'notauthorized') {
           abort(403, "No tienes autorización para ingresar.");
        }
        return $next($request);
    }
    public function rol_user_repeat($p){
        $myrol= array();
        foreach ($p as $y) {
            if (!in_array($y->name,$myrol)) {
                $myrol[]= $y->name;
            }
        }
        return $myrol;
    }
    public function url_permission($roles,$tipe){
        $first = strpos(url()->current(),$tipe);
        $data = 'authorized';
        if ($first !== false) {
            $data='notauthorized';
            $rol = $this->rol_user_repeat($roles);
            $obten = substr(url()->current(), $first,6);
            for ($i=0; $i <count($rol) ; $i++) { 
                if ($rol[$i] == $obten) {
                    $data='authorized';
                }
            }
        }
        return  $data;
    }
}
