<?php

namespace App\Http\Controllers;

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

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

  public function handleGoogleCallback()
{
    try {
        $user = Socialite::driver('google')->user();
        
        $finduser = User::where('google_id', $user->id)
                        ->orWhere('email', $user->email)
                        ->first();

        if($finduser){
            Auth::login($finduser);
        } else {
            // Saat membuat user baru, tentukan role defaultnya (misal: 'user')
            $finduser = User::create([
                'name' => $user->name,
                'email' => $user->email,
                'google_id'=> $user->id,
                'role' => 'user', // Sesuaikan dengan kolom role di database Anda
                'password' => encrypt('pustakanawasena123')
            ]);
            Auth::login($finduser);
        }

        // --- LOGIKA REDIRECT BERDASARKAN ROLE ---
        // Sesuaikan 'admin' atau '1' dengan cara Anda menentukan role
        if ($finduser->role == 'admin') {
            return redirect()->intended('/admin/dashboard'); 
        }

        return redirect()->intended('/home'); // Sesuai const HOME di Provider Anda

    } catch (Exception $e) {
        return redirect('login')->with('error', 'Gagal login!');
    }
}
}

