<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\Customer;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Log;
use Laravel\Socialite\Facades\Socialite;
use App\Repositories\Member\Auth\MemberAuthRepository;

class GoogleController extends Controller
{
    protected $memberAuthRepository;

    public function __construct(MemberAuthRepository $memberAuthRepository)
    {
        $this->memberAuthRepository = $memberAuthRepository;
    }

    /**
     * Redirect the user to the Google authentication page.
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function redirectToGoogle()
    {
        return Socialite::driver('google')->redirect();
    }

    /**
     * Obtain the user information from Google.
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function handleGoogleCallback()
    {
        try{
            $googleUser = Socialite::driver('google')->stateless()->user();
            // Log::info($googleUser);

            $email = $googleUser->email;
            $name = $googleUser->name;
            $google_id = $googleUser->id;
            $avatar = $googleUser->avatar;

            // $user = User::updateOrCreate(
            //     ['email' => $googleUser->email],
            //     [
            //         'name' => $googleUser->name,
            //         'google_id' => $googleUser->id,
            //         'avatar' => $googleUser->avatar,
            //     ]
            // );

            $user = $this->memberAuthRepository->check(['email' => $email]);
                
                if (!$user) {
                    // auto register
                    $user = $this->memberAuthRepository->loginGoogle($name, $email, $avatar);
                }


            Auth::login($user, true);

            return redirect()->route('home')->with('info', __('signin.google_coming_soon'));
    
        } catch (\Exception $e) {
            Log::error('Google callback failed: '.$e->getMessage());
            Log::info($e);

            return redirect()->route('login')->with('error', __('signin.google_failed'));
        }
    }
}
