<?php

namespace App\Http\Controllers\Auth;

//use App\Helpers\Helper;
use App\Http\Controllers\Controller;
use App\Models\Role;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

//use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

//    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/login';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
//        $this->middleware('guest')->except(['logout', 'login']);
    }

    public function redirectTo()
    {
        return  '/login';
    }

    /**
     * Log the user out of the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Http\RedirectResponse|\Illuminate\Http\Response|\Illuminate\Routing\Redirector
     */
    public function logout(Request $request)
    {
        Auth::guard('admin')->logout();
        $request->session()->flush();
        $request->session()->regenerate();
        return redirect()->to('/login');
    }

    public function adminLogin()
    {
        if(Auth::guard('admin')->check()){
            redirect()->route('admin.dashboard');
        }
        if(redirect()->back()->getTargetUrl() == '' || redirect()->back()->getTargetUrl()  == route('login')){
            $redirectTo = route('admin.dashboard');
        }else{
            $redirectTo = redirect()->back()->getTargetUrl();
        }
//        $redirectTo = ($redirectTo == route('dashboard') || $redirectTo == route('admin.login')) ? route('admin.dashboard'):$redirectTo;
        return view('auth.login', ['postRoute'=> 'admin.doLogin', 'redirectTo' => $redirectTo]);
//        return view('backend.pages.auth.user-login', ['postRoute'=> 'backend.doLogin', 'redirectTo' => 'backend.dashboard', 'pageConfigs' => $pageConfigs, 'configData' => $configData]);
    }

    public function login(Request $request)
    {
//        $username = strtolower($request->username);
//        //check if user exist
//        $userExist = User::query()->where('username', $username)->;
//
//        if($userExist > 0){
//            return redirect()->back()->withErrors(__('Username already exist'))->withInput();
//        }
        if (Auth::guard('admin')->attempt(['username' => $request->username, 'password' => $request->password])) {
            $user = Auth::guard('admin')->user();
            if(!in_array($user->role_id, Role::BACKEND_ROLES)){
                Auth::guard('admin')->logout();
                $result = ["success" => false, "message" => __("You don't have permissions!")];
            }else{
                Auth::guard('admin')->login($user);
                $result = ["success" => true, "message" => __("Logged in successfully!")];
            }
            $request->session()->regenerate();
            return response()->json($result);
        } else {
            $result = ["success" => false, "message" => __("Invalid username or password")];
            return response()->json($result);
        }
    }
}
