<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Str;
use Laravel\Socialite\Facades\Socialite;
use Auth;

class FacebookLoginController extends Controller
{
    /**
     * @return RedirectResponse
     */
    public function redirectToFacebook(): RedirectResponse
    {
        return Socialite::driver('facebook')->redirect();
    }

    /**
     * @return RedirectResponse
     */
    public function handleFacebookCallback(): RedirectResponse
    {
        $user = Socialite::driver('facebook')->user();

        $existingUser = User::where('facebook_id', $user->id)->first();

        if ($existingUser) {
            // Log in the existing user.
            Auth::login($existingUser);
        } else {
            // Create a new user.
            $checkuser = User::where('email', $user->email)->first();
            if ($checkuser) {
                $checkuser->gauth_id = $user->id;
                $checkuser->gauth_type = 'google';
                $checkuser->update();
                Auth::login($checkuser);
            } else {
                $newUser = new User();
                $newUser->name = $user->name;
                $newUser->email = $user->email;
                $newUser->facebook_id = $user->id;
                $newUser->password = bcrypt(request(Str::random())); // Set some random password
                $newUser->save();
                Auth::login($newUser);

            }


            // Log in the new user.
        }

        // Redirect to url as requested by user, if empty use /dashboard page as generated by Jetstream
        return redirect()->intended('/');
    }
}