<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;

class FCMService
{ 
    public static function send($fcm_token, $notification)
    {
        $url = 'https://fcm.googleapis.com/fcm/send';
        // $url = 'https://fcm.googleapis.com/v1/projects/594814396007/messages:send';

        $serverKey = config('fcm.server_key');
        $data = [
            "registration_ids" => [$fcm_token],
            "notification" => [
                "title" => $notification['title'],
                "body" => $notification['body'],  
            ]
        ];
        $encodedData = json_encode($data);
    
        $headers = [
            'Authorization:key=' . $serverKey,
            'Content-Type: application/json',
        ];

        $ch = curl_init();
      
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        // Disabling SSL Certificate support temporarly
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);        
        curl_setopt($ch, CURLOPT_POSTFIELDS, $encodedData);

        $result = curl_exec($ch);
        if ($result === FALSE) {
            return array("success"=> false, "message"=> curl_error($ch));
        }        
        // Close connection
        curl_close($ch);
        return array("success"=> true, "message"=> $result);
    }
}