<?php

namespace App\Services\Dashboard\Notification;

class NotificationService
{
    // Function to send Firebase Notification
    function sendNotificationToTopic($topic, $title, $body)
    {
        // Firebase server key (replace with your key)
        $serverKey = env('FIREBASE_TOKEN');

        // The Firebase endpoint for sending messages
        $url = 'https://fcm.googleapis.com/fcm/send';

        // Notification data
        $notification = [
            'title' => $title,
            'body' => $body,
            'sound' => 'default',
        ];

        // Payload data (custom data for your app)
        $data = [
            'custom_key' => 'custom_value'
        ];

        // The message payload (sending to a topic)
        $payload = [
            'to' => '/topics/' . $topic, // Send to topic "all"
            'notification' => $notification,
            'data' => $data,
            'priority' => 'high', // Set priority for the notification
        ];

        // Set headers for the POST request
        $headers = [
            'Authorization: key=' . $serverKey,
            'Content-Type: application/json'
        ];

        // Initialize curl
        $ch = curl_init();

        // Set curl options
        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_VERIFYPEER, false); // For HTTPS
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));

        // Execute curl and capture response
        $response = curl_exec($ch);

        // Check for curl errors
        if ($response === FALSE) {
            die('Curl failed: ' . curl_error($ch));
        }

        // Close curl
        curl_close($ch);

        // Return Firebase response
        return $response;
    }
}
