<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Laravel\Socialite\Facades\Socialite;

class TwitterSocialiteController extends Controller
{
    public function redirectToTwitter()
    {
        return Socialite::driver('twitter')->redirect();
    }

    public function handleCallback()
    {
        try {
            $user = Socialite::driver('twitter')->user();

            $finduser = User::where('social_id', $user->id)->first();

            if ($finduser)  
            {
                Auth::login($finduser);

                return redirect('/');
            }
            else
            {
                $maxId = User::max('id');
                $newUser = User::create([
                    'id' => $maxId,
                    'name' => $user->name,
                    'email' => $user->email,
                    'social_id' => $user->id,
                    'social_type' => 'Twitter',
                    'password' => bcrypt('password'),  
                    'role' => 'Member',
                ]);

                Auth::login($newUser);

                return redirect('/member/register');
            }

        }
        catch (Exception $e)
        {
            dd($e->getMessage());
        }
    }
}
