<?php

namespace App\Http\Middleware;

use App\Models\Role;
use App\Models\User;
use Closure;
use Illuminate\Http\Request;

class AdminAuthCheck
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $session_token = session()->token();

        $hashed = md5(md5($session_token));

        if (!session()->has('user_info.user_id_'.$hashed) && $request->path() != 'admin/auth/login') {

            return redirect()->route('admin.auth.login');
        }

        if (session()->has('user_info.user_id_'.$hashed)) {

            if ($request->path() == 'admin/auth/login') {

                return redirect()->back();
            }

            // get user role permissions

            //-- Check if user is admin
            $user_id = session('user_info.user_id_'.$hashed);

            $user_info = User::where(['id' => $user_id , 'is_admin' => 1 ] )->first();
            
            if ( $user_info ) {
                return $next($request);
            }

            // -- If not admin , get the role permissions
            $role_id = session('user_info.role_id_'.$hashed);

            $role = Role::findOrFail($role_id);

            $permissions = $role->permissions;

            // get requested action
            $actionName = class_basename($request->route()->getActionname());
            // check if requested action is in permissions list
            foreach ($permissions as $permission) {

                $_namespaces_chunks = explode('\\', $permission->controller);

                $controller = end($_namespaces_chunks);

                if ($actionName == $controller . '@' . $permission->method) {
                    // authorized request
                    return $next($request);
                }
            }

            // none authorized request
            //return response('Unauthorized Action', 403);

            $data['_page_title'] = __('admin/common.403.title');
            $data['message_title'] = __('admin/common.403.msg_title');
            $data['message_body'] = __('admin/common.403.msg_body');
            $data['back_link'] = url()->previous();
            
            $data['_breadcrumbs'] = '';
            $data['_page'] = 'admin.app.403';
            
            $data['_css'] = '';
            $data['_js'] = '';

            return response(view('admin.app.app',$data),403);
        }


        return $next($request);
    }
}
