<?php

namespace App\Http\Controllers;

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

class GoogleAuthController extends Controller
{
    // Redirect user to Google OAuth page
    public function redirectToGoogle()
    {
        return Socialite::driver('google')->stateless()->redirect();
    }

    // Handle Google OAuth callback
    public function handleGoogleCallback(Request $request)
    {
        try {
            $socialiteUser = Socialite::driver('google')->stateless()->user();

            // Find user by email or create new
            $user = User::firstOrCreate(
                ['email' => $socialiteUser->getEmail()],
                [
                    'name' => $socialiteUser->getName(),
                    'google_id' => $socialiteUser->getId(),
                    'email_verified_at' => now(),
                    'password' => bcrypt(Str::random(16)), // not used for login
                    'last_name' => null,
                    'phne' => null,
                    'country' => null,
                ]
            );

            // Log the user in
            Auth::login($user);

            // Generate JWT token
            $token = JWTAuth::fromUser($user);

            // Redirect to frontend with token and user data
            $frontendUrl = 'http://localhost:5173/login/success'; // Change if needed

            return redirect()->to($frontendUrl .
                '?token=' . urlencode($token) .
                '&name=' . urlencode($user->name) .
                '&email=' . urlencode($user->email)
            );

        } catch (\Exception $e) {
            return response()->json([
                'error' => 'Authentication failed: ' . $e->getMessage()
            ], 500);
        }
    }

    public function getGoogleUser(Request $request)
        {
            try {
                $user = JWTAuth::parseToken()->authenticate();

                return response()->json([
                    'success' => true,
                    'user' => [
                        'name' => $user->name,
                        'email' => $user->email
                    ]
                ]);
            } catch (\Exception $e) {
                return response()->json([
                    'success' => false,
                    'message' => 'Token invalid or expired',
                    'error' => $e->getMessage()
                ], 401);
            }
        }

        public function logout(Request $request)
{
    try {
        JWTAuth::invalidate(JWTAuth::parseToken());

        return response()->json([
            'success' => true,
            'message' => 'User successfully logged out.'
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'message' => 'Failed to logout. Token may be invalid or expired.',
            'error' => $e->getMessage()
        ], 500);
    }
}


}
