<?php

namespace App\Http\Middleware;
use Illuminate\Support\Facades\Auth;
use Closure;
use DB;

class OwnerUser
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (Auth::check()) {
            $username = explode('/',request()->path());
            if(!empty($username[0])){
                if (DB::table('admins')->where('username',$username[0])->where('role','Owner')->exists()){
                    $owner = DB::table('admins')->where('username',$username[0])->where('role','Owner')->first();
                    if(Auth::user()->register_id == $owner->id){
                        return $next($request);
                    }
                    else{
                        return redirect()->back();
                    }
                }
                else{
                    return redirect()->back();
                }
            }
            return redirect()->back();
        }
    }

}