<?php

namespace App\Http\Controllers;

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

class AuthController extends Controller
{
    /**
     * Handle form-based email/password login
     */
public function loginWithEmail(Request $request)
{
    $request->validate([
        'email' => 'required|email',
        'password' => 'required|string',
    ]);

    $user = User::where('email', $request->email)->first();

    if (!$user || !Hash::check($request->password, $user->password)) {
        return response()->json(['message' => 'Invalid email or password'], 401);
    }

    $token = JWTAuth::fromUser($user);

    $redirectUrl = 'http://localhost:5173/login/success?' .
        'token=' . urlencode($token) .
        '&name=' . urlencode($user->name) .
        '&email=' . urlencode($user->email);

    return response()->json([
        'token' => $token,
        'user' => [
            'name' => $user->name,
            'email' => $user->email,
            'userType' => $user->userType ?? 'form',
        ],
        'redirect_url' => $redirectUrl
    ]);
}

    /**
     * Redirect to Google for OAuth
     */
    public function redirectToGoogle()
    {
        return Socialite::driver('google')->stateless()->redirect();
    }

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

            $user = User::firstOrCreate(
                ['email' => $socialiteUser->getEmail()],
                [
                    'name' => $socialiteUser->getName(),
                    'google_id' => $socialiteUser->getId(),
                    'email_verified_at' => now(),
                    'password' => bcrypt(Str::random(16)), // random dummy password
                    'last_name' => null,
                    'phne' => null,
                    'country' => null,
                ]
            );

            Auth::login($user);
            $token = JWTAuth::fromUser($user);

            $frontendUrl = 'http://localhost:5173/login/success';

            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);
        }
    }

    /**
     * Get the authenticated user from token
     */
    public function getAuthenticatedUser(Request $request)
    {
        try {
            $user = JWTAuth::parseToken()->authenticate();

            return response()->json([
                'success' => true,
                'user' => [
                    'id' => $user->id,
                    'name' => $user->name,
                    'email' => $user->email,
                    'google_id' => $user->google_id,
                    'userType' => $user->userType ?? 'form',
                    'phne' => $user->phne, // Add this (note the spelling matches your DB)
                    'country' => $user->country, // Add this
                    'last_name' => $user->last_name,
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Token invalid or expired',
                'error' => $e->getMessage()
            ], 401);
        }
    }


        public function updateUser(Request $request)
    {
        try {
            $user = JWTAuth::parseToken()->authenticate();
            
            $validator = Validator::make($request->all(), [
                'name' => 'sometimes|string|max:255',
                'last_name' => 'nullable|string|max:255',
                'phne' => 'nullable|string|max:20',
                'country' => 'nullable|string|max:100',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'errors' => $validator->errors()
                ], 422);
            }

            $user->update([
                'name' => $request->input('name', $user->name),
                'last_name' => $request->input('last_name', $user->last_name),
                'phne' => $request->input('phne', $user->phne),
                'country' => $request->input('country', $user->country),
            ]);

            return response()->json([
                'success' => true,
                'message' => 'User updated successfully',
                'user' => [
                    'name' => $user->name,
                    'email' => $user->email,
                    'last_name' => $user->last_name,
                    'phne' => $user->phne,
                    'country' => $user->country,
                ]
            ]);

        } catch (JWTException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Token invalid or expired',
                'error' => $e->getMessage()
            ], 401);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to update user',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Logout user by invalidating token
     */
    public function logout()
    {
        try {
            JWTAuth::invalidate(JWTAuth::getToken());

            return response()->json(['message' => 'Logged out successfully']);
        } catch (\Exception $e) {
            return response()->json([
                'message' => 'Logout failed',
                'error' => $e->getMessage()
            ], 500);
        }
    }
}
