<?php

namespace App\Http\Controllers\Auth;

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

class GoogleController extends Controller
{
    /**
     * Redirect the user to the Google authentication page.
     */
    public function redirectToGoogle()
    {
        // Prefer to hint Google to show accounts from the somaiya.edu domain.
        // This is only a UI hint — always validate the domain on the callback.
        return Socialite::driver('google')->with(['hd' => 'somaiya.edu'])->redirect();
    }

    /**
     * Obtain the user information from Google.
     */
    public function handleGoogleCallback()
    {
        try {
            $googleUser = Socialite::driver('google')->user();

            // Validate that the user belongs to the somaiya.edu domain.
            // Google may return a 'hd' (hosted domain) claim; fall back to parsing the email.
            $email = $googleUser->getEmail();
            $hostedDomain = data_get($googleUser->user, 'hd');
            $domain = $hostedDomain ?: (strpos($email, '@') !== false ? substr(strrchr($email, "@"), 1) : null);

            if ($domain !== 'somaiya.edu') {
                return redirect()->route('login')->withErrors(['error' => 'Please sign in using a somaiya.edu account.']);
            }

            $user = User::firstOrCreate(
                ['email' => $email],
                [
                    'name' => $googleUser->getName() ?: $email,
                    'password' => bcrypt(Str::random(16)), // Generate a random password
                ]
            );

            Auth::login($user);

            return redirect()->route('dashboard');
        } catch (\Exception $e) {
            return redirect()->route('login')->withErrors(['error' => 'Unable to login using Google. Please try again.']);
        }
    }
}
