<?php

namespace App\Http\Controllers;

use App\Models\IstatistikModel;
use App\Models\Uyeler;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Auth;
use Laravel\Socialite\Facades\Socialite;

class GoogleAuthController extends Controller
{
    public function redirect(){
        return Socialite::driver('google')->redirect();
    }
    public function callbackGoogle(){
        try {
            $google_user=Socialite::driver('google')->user();



                $user= Uyeler::where('google_id',$google_user->getId())->first();
                if (!$user){
                    $new_user=Uyeler::create([
                        'name'=>$google_user->getName(),
                        'email'=>$google_user->getEmail(),
                        'google_id'=>$google_user->getId(),
                        'profile_image'=>$google_user->getAvatar(),
                    ]);


                    $toplammusteri=IstatistikModel::find(1);


                    IstatistikModel::find(1)->update([
                        'toplammusteri' => $toplammusteri->toplammusteri+1,
                        'updated_at' => Carbon::now(),
                    ]);

                    Auth::guard('uye')->login($new_user);

                    return redirect()->intended('uye/account');
                }else{
                    Auth::guard('uye')->login($user);

                    return redirect()->intended('uye/account');

                }




        }catch (\Throwable $th){
            return redirect()->back()->with('danger','Bu mail ile daha önce kayıt yapılmış');


        }
    }


    public function redirectface(){
        return Socialite::driver('facebook')->redirect();
    }
    public function callbackFacebook(){
        try {
            $facebook_user=Socialite::driver('facebook')->user();



            $user= Uyeler::where('facebook_id',$facebook_user->getId())->first();
            if (!$user){
                $new_user=Uyeler::create([
                    'name'=>$facebook_user->getName(),
                    'email'=>$facebook_user->getEmail(),
                    'facebook_id'=>$facebook_user->getId(),
                    'profile_image'=>$facebook_user->getAvatar(),
                ]);

                Auth::guard('uye')->login($new_user);

                return redirect()->intended('uye/account');
            }else{
                Auth::guard('uye')->login($user);

                return redirect()->intended('uye/account');

            }




        }catch (\Throwable $th){
            dd('Hata Var'.$th->getMessage());

        }
    }
}
