<?php

namespace App\Http\Controllers;

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

class GoogleSocialiteController extends Controller
{
    /**
     * Redirect pengguna ke Google untuk autentikasi.
     */
    public function redirect()
    {
        // 🛠️ PERBAIKAN: Fallback diganti ke url('/') alias beranda utama agar tidak nyasar ke login admin
        $redirectTo = request()->query('redirect', url('/'));

        session(['google_login_redirect' => $redirectTo]);

        return Socialite::driver('google')
            ->with(['prompt' => 'select_account'])
            ->redirect();
    }

    /**
     * Terima callback dari Google.
     */
    public function callback()
    {
        try {
            $googleUser = Socialite::driver('google')->stateless()->user();

            // Cari user berdasarkan google_id atau email
            $user = User::where('google_id', $googleUser->id)
                ->orWhere('email', $googleUser->email)
                ->first();

            if (!$user) {
                // Buat user baru jika belum terdaftar
                $user = User::create([
                    'name' => $googleUser->name,
                    'email' => $googleUser->email,
                    'google_id' => $googleUser->id,
                    'avatar' => $googleUser->avatar,
                    'password' => Hash::make(Str::random(24)),
                    'role' => 'user', // Default role sebagai user biasa
                ]);
            } else {
                // Update google_id jika user sudah ada tapi belum terhubung ke Google
                if (!$user->google_id) {
                    $user->update([
                        'google_id' => $googleUser->id,
                        'avatar' => $googleUser->avatar ?: $user->avatar,
                    ]);
                }
            }

            // Login-kan user ke sistem Laravel
            Auth::login($user);

            // 🛠️ PERBAIKAN: Ambil tujuan dari session, kalau kosong otomatis lempar ke beranda utama url('/')
            $redirectTo = session('google_login_redirect', url('/'));
            session()->forget('google_login_redirect');

            return redirect($redirectTo)->with('success', 'Berhasil login via Google!');

        } catch (\Exception $e) {
            \Log::error('Google SSO Error: ' . $e->getMessage());
            
            // Jika gagal, kembalikan ke halaman login biasa dengan pesan error
            return redirect('/login')->with('error', 'Login Google gagal. Silakan coba lagi.');
        }
    }
}