<?php

namespace App\Libraries;

class FCMService
{
    private $serverKey;

    public function __construct()
    {
        $this->serverKey = getenv('FCM_SERVER_KEY'); // keep it in .env
    }

    public function sendNotification($deviceToken, $title, $body, $dataPayload = [])
    {
        $url = "https://fcm.googleapis.com/fcm/send";

        $notification = [
            "title" => $title,
            "body"  => $body,
        ];

        $fields = [
            "to" => $deviceToken,
            "notification" => $notification,
            "data" => $dataPayload,  // custom data for app
            "priority" => "high"
        ];

        $headers = [
            "Authorization: key=" . $this->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_POSTFIELDS, json_encode($fields));
        $result = curl_exec($ch);
        curl_close($ch);

        return $result;
    }
}
