<?php

namespace App\Http\Controllers\Auth;

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

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

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

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


    public function login(Request $request){
        //$this->validateLogin($request);

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

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

//        $model = ($guard == "admin") ? Admin::class : Customer::class;

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

        $loginId = $credentials['loginId'];

        $user = Customer::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")],
            ]);
        }

        $guard = $user->guardName();

        // 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($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("shop.index");
    }

    public function logout(Request $request){
        $cart = collect($request->session()->get('cart'));
        $user = auth(activeGuard())->user();
        $redirect = ($user->isCustomer())
                    ? route("shop.index")
                    : route("admin.auth.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');
    }

    // Oauth Login [ Facebook - Twitter - Google ]
    public function redirectToProvider($provider){
        return Socialite::driver($provider)->redirect();
    }

    // callback [ Facebook - Twitter - Google ]
    public function handleProviderCallback($provider){
        $socialUser = Socialite::driver($provider)->user();

        $id = $socialUser->getId();
        $token = $socialUser->token;
        $name = $socialUser->getName();
        $nickName = $socialUser->getNickname() == '' ? trim(Str::lower(Str::replaceArray(' ', ['_'], $name))) : $socialUser->getNickname();
        $email = $socialUser->getEmail() == '' ? trim(Str::lower(Str::replaceArray(' ', ['_'], $name))) . '@' . $provider . '.com' : $socialUser->getEmail();
        $user_image = $socialUser->getAvatar();

        $user = Customer::firstOrCreate(
            ['email' => $email],
            [
                'first_name' => $name,
                'last_name' => $name,
                'username' => $nickName,
                'email' => $email,
                'email_verified_at' => Carbon::now(),
                'phone' => null,
                'active' => 1,
                'receive_email' => 1,
                'remember_token' => $token,
                'password' => Hash::make($email),
                //UserType::FK_ID => UserType::CUSTOMER,
            ]
        );

        //$user->assignRole('user');

        Auth::guard("customer")->login($user, true);

        return redirect()->route('user.orders')
                           ->with([
                                'message' => __('Your logged in successfully'),
                                'alert-type' => 'success',
                            ]);
    }
}
