<?php

namespace App\Service;

use Illuminate\Support\Facades\Http;
// use Google\Client;

class FirebaseService
{
    protected $firebaseProjectId;

    public function __construct()
    {
        $this->firebaseProjectId = env('FIREBASE_PROJECT_ID'); // Get Project ID from .env
    }

    private function getAccessToken()
    {
        $client = new Client();
        $client->setAuthConfig(storage_path('firebase-adminsdk.json')); // Ensure JSON is in storage/
        $client->addScope('https://www.googleapis.com/auth/firebase.messaging');

        if ($client->isAccessTokenExpired()) {
            $client->fetchAccessTokenWithAssertion();
        }

        return $client->getAccessToken()['access_token'];
    }

    public function sendNotification($deviceToken, $title, $body, $data = [])
    {
        $accessToken = $this->getAccessToken(); // Correct method call
        $url = "https://fcm.googleapis.com/v1/projects/{$this->firebaseProjectId}/messages:send";

        $payload = [
            "message" => [
                "token" => $deviceToken,  // Corrected from 'to' to 'token'
                "notification" => [
                    "title" => $title,
                    "body" => $body,
                    "sound" => "default"
                ],
                "data" => $data // Custom data if needed
            ]
        ];

        $response = Http::withHeaders([
            'Authorization' => 'Bearer ' . $accessToken, // Corrected from 'key=' to 'Bearer'
            'Content-Type' => 'application/json',
        ])->post($url, $payload);

        return $response->json($response);
    }
}
