<?php

namespace Blazemedia\OneSignal\Push;

/**
 * HTTP Client for OneSignal API
 */
class HttpClient
{
    /**
     * Send POST request
     */
    public function post(string $url, array $options = [])
    {
        $headers = $options['headers'] ?? [];
        $json = $options['json'] ?? [];

        $ch = curl_init();

        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => json_encode($json),
            CURLOPT_HTTPHEADER => $this->formatHeaders($headers),
            CURLOPT_TIMEOUT => 30,
            CURLOPT_SSL_VERIFYPEER => false,
        ]);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);

        curl_close($ch);

        if ($error) {
            throw new \Exception("cURL Error: " . $error);
        }

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

        return json_decode($response, true);
    }

    /**
     * Format headers for cURL
     */
    private function formatHeaders(array $headers): array
    {
        $formatted = [];
        foreach ($headers as $key => $value) {
            $formatted[] = "{$key}: {$value}";
        }
        return $formatted;
    }
} 