<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use App\Models\UserManagement\Admin;
use App\Models\UserManagement\Customer;
use App\Models\UserManagement\User;
use App\Models\UserManagement\UserType;
use App\Providers\RouteServiceProvider;
use Carbon\Carbon;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Laravel\Socialite\Facades\Socialite;

class AuthController 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 {
        logout as protected originalLogout;
        login as protected originalLogin;
    }


    const GUARD = "admin";
    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = "/".self::GUARD;

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

    /**
     * Get the login username to be used by the controller.
     *
     * @return string
     */
    public function username(){
        return 'username';
    }


    public function login(Request $request){

        $request->session()->invalidate();

        $request->session()->regenerateToken();

        $credentials = $request->only(['loginId',"password",'remember']);
        $remember = $request->remember ?? true;

        $loginId = $credentials['loginId'];

        $user = Admin::where('email',$loginId)
                    ->orWhere('username',$loginId)
                    ->orWhere('phone',$loginId)
                    ->first();

//        dd($guard,$user);

        //si l'user n'exite pas
        if (!$user) {
            throw ValidationException::withMessages([
                'loginId' => [__("Incorrect email, username or phone")],
            ]);
        }
        if (!Hash::check($credentials['password'], $user->password)){
            throw ValidationException::withMessages([
                'password' => [__("Incorrect password")],
            ]);
        }

        // If the class is using the ThrottlesLogins trait, we can automatically throttle
        // the login attempts for this application. We'll key this by the username and
        // the IP address of the client making these requests into this application.
        if (method_exists($this, 'hasTooManyLoginAttempts') &&
            $this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);
            return $this->sendLockoutResponse($request);
        }

        Auth::guard(self::GUARD)->login($user,$remember);

        if ($request->hasSession()) {
            $request->session()->put('auth.password_confirmed_at', time());
        }
        return $this->sendLoginResponse($request);
    }

    public function redirectTo(){
        return $this->redirectTo =  route("admin.index");
    }

    public function logout(Request $request){
        $cart = collect($request->session()->get('cart'));
        $user = auth(activeGuard())->user();
        $redirect = ($user->isCustomer())
                    ? route("shop.index")
                    : route("admin.login");

        /* Call Original Logout Method */
        $response = $this->originalLogout($request);

        /* Repopulate Session With Cart */
        if (!config('cart.destroy_on_logout')) {
            $cart->each(function ($rows, $identifier) use ($request) {
                $request->session()->put('cart.' . $identifier, $rows);
            });
        }

        if ($request->ajax()){
            return response()->json([
                "success" => true,
                "redirect" => $redirect,
                "message" => __("You are now logged-out"),
            ]);
        }
        return redirect($redirect)->with([
            "message" => __("You are now logged-out"),
            "alert-type" => "success",
        ]);

        /* Repopulate Original Response  */
       // return $response;
    }

    /* Actions After Logged Out  */
    protected function loggedOut(){
        Cache::forget('admin_side_menu');
        Cache::forget('shop_categories_menu');
        Cache::forget('shop_tags_menu');
    }
}
