<?php

namespace App\Http\Controllers;

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

class SocialLoginController extends Controller
{
    public function google()
    {
        return Socialite::driver('google')->redirect();
    }

    public function googleCallback()
    {
        $googleUser = Socialite::driver('google')->user();
        $user = User::where('email', $googleUser->getEmail())
            ->orWhere('google_id', $googleUser->getId())
            ->first();

        if (!$user) {
            $data = new User();
            $data->name = $googleUser->getName();
            $data->email = $googleUser->getEmail();
            $data->google_id = $googleUser->getId();
            $data->save();
            Auth::login($data);
        } else {
            Auth::login($user);
        }
        return redirect()->route('user.dashboard');
    }

    public function facebook()
    {
        return Socialite::driver('facebook')->redirect();
    }

    public function facebookCallback()
    {
        $facebookUser = Socialite::driver('facebook')->user();
        $user = User::where('email', $facebookUser->getEmail())
            ->orWhere('facebook_id', $facebookUser->getId())
            ->first();
        if (!$user) {
            $data = new User();
            $data->name = $facebookUser->getName();
            $data->email = $facebookUser->getEmail();
            $data->facebook_id = $facebookUser->getId();
            $data->save();
            Auth::login($data);
        } else {
            Auth::login($user);
        }
        return redirect()->route('user.dashboard');
    }
}
