<?php

namespace App\Services;


use GuzzleHttp\Client;
use Google\Auth\ApplicationDefaultCredentials;
use Google\Auth\Middleware\AuthTokenMiddleware;
use Google\Auth\Credentials\ServiceAccountCredentials;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;


class NotificationService
{
    protected $client;

    public function __construct()
    {
        $serviceAccountPath = storage_path('bayea3-firebase-adminsdk.json');

        // Verify that the file exists
        if (!file_exists($serviceAccountPath)) {
            throw new \Exception("Service account file not found: $serviceAccountPath");
        }

        // Create credentials using the service account JSON file
        $credentials = new ServiceAccountCredentials(
            ['https://www.googleapis.com/auth/firebase.messaging'],
            $serviceAccountPath
        );

        // Create a middleware to add the auth token to requests
        $middleware = Middleware::mapRequest(function ($request) use ($credentials) {
            $accessToken = $credentials->fetchAuthToken()['access_token'];
            return $request->withHeader('Authorization', 'Bearer ' . $accessToken);
        });

        // Create a Guzzle client with the middleware
        $stack = HandlerStack::create();
        $stack->push($middleware);

        $this->client = new Client([
            'handler' => $stack,
            'verify' => storage_path('cacert.pem'), // Ensure this path is correct
        ]);
    }

    public function sendNotification($deviceToken, $title, $body)
    {
        $url = 'https://fcm.googleapis.com/v1/projects/bayea3/messages:send';

        // Send a POST request to FCM
        $response = $this->client->post($url, [
            'json' => [
                'message' => [
                    'token' => $deviceToken,
                    'notification' => [
                        'title' => $title,
                        'body' => $body,
                    ],
                ],
            ],
        ]);

        return $response->getBody()->getContents();
    }
}
