<?php

namespace App\Helpers;

use App\Model\Client\UserFcmToken;
use Google\Client;

class FcmHelper
{
    public static function send($userId, $title, $body)
    {
        $tokens = UserFcmToken::where('user_id', $userId)->pluck('token')->toArray();
        if (!$tokens) return false;

        $keyPath = base_path(env('GOOGLE_APPLICATION_CREDENTIALS'));
        $client = new Client();
        $client->setAuthConfig($keyPath);
        $client->addScope('https://www.googleapis.com/auth/firebase.messaging');
        $accessToken = $client->fetchAccessTokenWithAssertion()['access_token'];

        $projectId = json_decode(file_get_contents($keyPath), true)['project_id'];
        $url = "https://fcm.googleapis.com/v1/projects/$projectId/messages:send";

        foreach ($tokens as $token) {
            $payload = [
                'message' => [
                    'token' => $token,
                    'notification' => ['title' => $title, 'body' => $body],
                ],
            ];

            $ch = curl_init($url);
            curl_setopt_array($ch, [
                CURLOPT_POST => true,
                CURLOPT_HTTPHEADER => [
                    "Authorization: Bearer $accessToken",
                    'Content-Type: application/json',
                ],
                CURLOPT_POSTFIELDS => json_encode($payload),
                CURLOPT_RETURNTRANSFER => true,
            ]);
            curl_exec($ch);
            curl_close($ch);
        }

        return true;
    }
}
