<?php

namespace Blazemedia\OneSignal\Push;

use Blazemedia\OneSignal\Push\Notification;

/**
 * OneSignal Client for sending push notifications
 */
class Client
{
    protected string $uri = 'https://api.onesignal.com/notifications';
    protected string $apiKey;
    protected string $appId;

    /**
     * Constructor
     */
    public function __construct(string $appId, string $apiKey)
    {
        $this->apiKey = $apiKey;
        $this->appId = $appId;
    }

    /**
     * Send notification
     */
    public function send(Notification $notification)
    {
        $notification->setUtm('push-notifications', 'OneSignal');

        $body = array_merge($notification->getOSVars(), [
            'app_id' => $this->appId,
            "included_segments" => ["Total Subscriptions","All"],
        ]);

        try {
            $response = \wp_remote_post($this->uri, [
                'headers' => $this->getOSHeaders(),
                'body' => json_encode($body),
                'timeout' => 30,
                'sslverify' => false, // Disabilita i controlli SSL
            ]);

            if (\is_wp_error($response)) {
                throw new \Exception("HTTP Error: " . $response->get_error_message());
            }

            $httpCode = \wp_remote_retrieve_response_code($response);
            $body = \wp_remote_retrieve_body($response);

            if ($httpCode >= 400) {
                throw new \Exception("HTTP Error {$httpCode}: " . $body);
            }

            return json_decode($body, true);
            
        } catch (\Exception $e) {
            throw new \Exception("Failure: push notification not sent: " . $e->getMessage());
        }
    }

    /**
     * Get OneSignal headers
     */
    protected function getOSHeaders()
    {
        return [
            "Authorization" => "Basic {$this->apiKey}",
            "accept" => "application/json",
            "Content-Type" => "application/json"
        ];
    }
} 