<?php

namespace App\Http\Controllers;

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)
    {
        try {
            $verifiedIdToken = $this->auth->verifyIdToken($request->id_token);
            $uid = $verifiedIdToken->claims()->get('sub');

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

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

            auth()->login($user);

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

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



public function logout(Request $request)
{
    $token = $request->bearerToken(); // get token from header

    $curl = curl_init();

    curl_setopt_array($curl, array(
        CURLOPT_URL => 'https://demoweblinks.in/cusella/public/api/logout',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_HTTPHEADER => array(
            'Authorization: Bearer ' . $token
        ),
    ));

    $response = curl_exec($curl);
    curl_close($curl);

    return response()->json([
        'status' => true,
        'message' => 'Logged out successfully',
        'api_response' => json_decode($response, true)
    ]);
}
}