<?php

namespace App\Http\Controllers\Auth;

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

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

    public function handleGoogleCallback()
    {
        try {
            $googleUser = Socialite::driver('google')->stateless()->user();

            // Cek user berdasarkan email
            $user = User::where('email', $googleUser->getEmail())->first();

            if ($user) {
                if ($user->role !== 'customer') {
                    return redirect()->route('login')->with('error', 'Akun Anda bukan customer.');
                }

                Auth::login($user);
                return redirect()->route('dashboard');
            } else {
                // Simpan data Google ke session
                Session::put('google_user', [
                    'name' => $googleUser->getName(),
                    'email' => $googleUser->getEmail(),
                ]);

                return redirect()->route('google.register.form');
            }

        } catch (\Exception $e) {
            return redirect()->route('login')->with('error', 'Gagal login dengan Google.');
        }
    }

    public function showPasswordForm()
    {
        $googleUser = Session::get('google_user');

        if (!$googleUser) {
            return redirect()->route('login')->with('error', 'Session Google tidak ditemukan.');
        }

        return view('auth.google-register', ['googleUser' => $googleUser]);
    }

    public function registerWithPassword(Request $request)
    {
        $request->validate([
            'password' => 'required|min:6|confirmed',
        ]);

        $googleUser = Session::get('google_user');

        if (!$googleUser) {
            return redirect()->route('login')->with('error', 'Session Google tidak ditemukan.');
        }

        // Buat user baru
        $user = User::create([
            'name' => $googleUser['name'],
            'email' => $googleUser['email'],
            'password' => Hash::make($request->password),
            'role' => 'customer',
        ]);

        Auth::login($user);
        Session::forget('google_user');

        return redirect()->route('dashboard');
    }
}
