<?php

namespace App\Http\Middleware;

use App\Exceptions\ServerStatus;
use App\Providers\RouteServiceProvider;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class Authenticate extends Middleware{


    /**
     * Get the path the user should be redirected to when they are not authenticated.
     *
     * @param  Request  $request
     * @return string|null
     */
    protected function redirectTo($request){
        if ($request->is("admin") or $request->is("admin/*")){
            return route('admin.auth.login');
        }
        return route('login');
    }

    /**
     * Handle an incoming request.
     *
     * @param $request
     * @param mixed $next
     * @param array $guards
     * @return mixed
     */
    public function handle($request,\Closure  $next, ...$guards){
        $guards = empty($guards) ? [null] : $guards;

        $guard = $guards[0] ?? "web";



//        dd( Auth::guard($guard)->check(),$guard,auth($guard)->user());
//        dd(auth()->guard($guard)->check(),$guard);

        $message = __("In order to proceed with your order, You will have to login if you are a returning customer or create an account by clicking the Create Account link below.");
        if ($request->is("admin") or $request->is("admin/*")){
            $message = __("Authentication required.");
        }

       //dd( auth($guard)->check(),$guard);
        if (!auth($guard)->check()) {
            return redirect()->guest($this->redirectTo($request))->with([
                'message' => $message,
                'alert-type' => "warning",
            ]);
        }

//       if (!$this->auth->guard()->check()){
//           $message = __("In order to proceed with your order, You will have to login if you are a returning customer or create an account by clicking the Create Account link below.");
//           if ($request->is("admin") or $request->is("admin/*")){
//              $message = __("Authentication required.");
//           }
//           return redirect()->guest($this->redirectTo($request))->with([
//               'message' => $message,
//               'alert-type' => "warning",
//           ]);
//       }
        return $next($request);
    }
}
