<?php

use Kreait\Firebase\Factory;
use Kreait\Firebase\Messaging\CloudMessage;
use Kreait\Firebase\Messaging\Notification;

class NotificationHelper
{
    private static $factory;
    private static $messaging;

    /**
     * Initialize Firebase Messaging
     */
    private static function init()
    {
        if (self::$messaging) {
            return true;
        }

        $serviceAccountPath = __DIR__ . '/../config/firebase_credentials.json';

        if (!file_exists($serviceAccountPath)) {
            error_log("Firebase credentials not found at $serviceAccountPath");
            return false;
        }

        try {
            self::$factory = (new Factory)->withServiceAccount($serviceAccountPath);
            self::$messaging = self::$factory->createMessaging();
            return true;
        } catch (Exception $e) {
            error_log("Firebase Initialization Error: " . $e->getMessage());
            return false;
        }
    }

    /**
     * Send a notification to a specific device token
     * 
     * @param string $token Device FCM token
     * @param string $title Notification title
     * @param string $body Notification body
     * @param array $data Optional data payload
     * @return bool success
     */
    public static function sendToToken($token, $title, $body, $data = [])
    {
        if (!self::init()) {
            return false;
        }

        try {
            $notification = ['title' => $title, 'body' => $body];

            $message = [
                'token' => $token,
                'notification' => $notification,
                'data' => $data,
            ];

            self::$messaging->send($message);
            return true;
        } catch (\Throwable $e) {
            error_log('Firebase Sending Error: ' . $e->getMessage() . ' Token: ' . $token);
            return false;
        }
    }

    /**
     * Send a notification to multiple tokens (Multicast)
     * 
     * @param array $tokens List of Device FCM tokens
     * @param string $title Notification title
     * @param string $body Notification body
     * @param array $data Optional data payload
     * @return array Report of success/failures
     */
    public static function sendToTokens(array $tokens, $title, $body, $data = [])
    {
        if (!self::init() || empty($tokens)) {
            return ['success' => 0, 'failure' => 0];
        }

        try {
            $notification = Notification::create($title, $body);

            $message = CloudMessage::new()
                ->withNotification($notification)
                ->withData($data);

            $report = self::$messaging->sendMulticast($message, $tokens);

            return [
                'success' => $report->successes()->count(),
                'failure' => $report->failures()->count(),
                'failures' => $report->failures()->getItems() // Returns map of token => error
            ];
        } catch (\Throwable $e) {
            error_log('Firebase Multicast Sending Error: ' . $e->getMessage());
            return ['success' => 0, 'failure' => count($tokens)];
        }
    }
}
?>