<?php

namespace Blazemedia\OneSignal\Push;

/**
 * Push Manager for handling OneSignal notifications
 */
class PushManager
{
    private Client $client;

    /**
     * Constructor
     */
    public function __construct()
    {
        $appId  = \get_option('onesignal_app_id');
        $apiKey = \get_option('onesignal_rest_api_key');

        if (!$appId || !$apiKey) {
            throw new \Exception('OneSignal App ID and REST API Key are required');
        }

        $this->client = new Client($appId, $apiKey);
    }

    /**
     * Send notification to OneSignal
     */
    public function sendNotification(array $pushData)
    {
        try {
            $notification = NotificationCreator::fromPushNotification($pushData);
            return $this->client->send($notification);
        } catch (\Exception $e) {
            $error = 'Errore Push notification per push ' . ($pushData['id'] ?? 'unknown') . ' ' . $e->getMessage();
            throw new \Exception($error);
        }
    }

    /**
     * Send notification from WordPress post
     */
    public function sendPostNotification(\WP_Post $post, string $imageUrl = '')
    {
        try {
            $imageUrl = $imageUrl == '' ? get_the_post_thumbnail_url( $post, 'full' ) : $imageUrl;

            $notification = NotificationCreator::fromPost($post, $imageUrl);
            
            return $this->client->send($notification);

        } catch (\Exception $e) {
            $error = 'Errore Push notification per post ' . $post->ID . ' ' . $e->getMessage();
            throw new \Exception($error);
        }
    }

    /**
     * Send custom notification
     */
    public function sendCustomNotification(string $title, string $content, string $url = '', string $image = '')
    {
        try {
            $notification = NotificationCreator::fromData($title, $content, $url, $image);
            return $this->client->send($notification);
        } catch (\Exception $e) {
            $error = 'Errore Push notification: ' . $e->getMessage();
            throw new \Exception($error);
        }
    }

    /**
     * Static method for easy usage
     */
    public static function sendNotificationToOneSignal(array $pushData)
    {
        $manager = new self();
        return $manager->sendNotification($pushData);
    }
} 