<?php

namespace {{ namespace }};

use App\Models\User;
use GuzzleHttp\Client;

class {{ class }} {
    public function register(User $user, $token)
    {
        $user->device_token = $token;
        $user->save();

        return $user;
    }
    public function send($to, $message) {
        $fields = array(
            'to'   => $to,
            'data' => $message,
        );

        return $this->sendPushNotification($fields);
    }

    public function sendMultiple($registration_ids, $message, $reload = [], $ttl = 15) {
        $fields['registration_ids'] = $registration_ids;
        $fields['notification'] = $message;
        $fields['data']  = $message['payload'];
        $fields['data']['target_reload']  = $reload;
        $fields['priority'] = 'high';
        $fields['time_to_live'] = $ttl;

        return $this->sendPushNotification( $fields );
    }

    private function sendPushNotification($fields)
    {
        $senderId = config('firebase.sender_id');
        $url = "https://fcm.googleapis.com/fcm/send";
        $SERVER_API_KEY = config('firebase.servr_api_key');

        $client = new Client();
        $result = $client->post( $url, [
            'verify'  => false,
            'json'    => $fields,
            'headers' => [
                'Authorization' => 'key='. $SERVER_API_KEY,
                'Content-Type'  => 'application/json',
            ],
        ]);

        return json_decode($result->getBody(), true);
    }
}