<div id="recaptcha-container"></div>

<input type="text" id="phone" placeholder="+919876543210">
<button onclick="sendOtp()">Send OTP</button>

<script>
window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container');

function sendOtp() {
    let phone = document.getElementById('phone').value;

    firebase.auth().signInWithPhoneNumber(phone, window.recaptchaVerifier)
    .then(function (confirmationResult) {
        window.confirmationResult = confirmationResult;
        alert('OTP sent');
    })
    .catch(function (error) {
        console.log(error);
    });
}
</script>


<input type="text" id="otp" placeholder="Enter OTP">
<button onclick="verifyOtp()">Verify OTP</button>

<script>
function verifyOtp() {
    let code = document.getElementById('otp').value;

    confirmationResult.confirm(code).then(function (result) {

        result.user.getIdToken().then(function(idToken){

            // ✅ Send to Laravel
            fetch('/verify-otp', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': '{{ csrf_token() }}'
                },
                body: JSON.stringify({
                    id_token: idToken
                })
            })
            .then(res => res.json())
            .then(data => {
                console.log(data);
                alert('Login success');
            });

        });

    }).catch(function (error) {
        alert('Invalid OTP');
    });
}
</script>


use Illuminate\Http\Request;
use Kreait\Firebase\Auth as FirebaseAuth;
use App\Models\User;

class AuthController extends Controller
{
    protected $auth;

    public function __construct(FirebaseAuth $auth)
    {
        $this->auth = $auth;
    }

    public function verifyOtp(Request $request)
    {
        $request->validate([
            'id_token' => 'required'
        ]);

        try {
            $verifiedIdToken = $this->auth->verifyIdToken($request->id_token);
            $uid = $verifiedIdToken->claims()->get('sub');

            $firebaseUser = $this->auth->getUser($uid);

            $phone = $firebaseUser->phoneNumber;

            // 👉 Create / Login user
            $user = User::firstOrCreate(
                ['phone' => $phone],
                ['name' => 'User']
            );

            auth()->login($user);

            return response()->json([
                'success' => true,
                'user' => $user
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Invalid OTP'
            ], 401);
        }
    }
}

Route::post('/verify-otp', [AuthController::class, 'verifyOtp']);