<?php

namespace MDirectorNewsletter\includes;

/**
 * EmBlue API with Bearer Token
 *
 * @package    Mdirector_Newsletter
 * @subpackage Mdirector_Newsletter/api
 */
class Mdirector_Newsletter_Api
{
    private $bearer_token;
    
    /**
     * Call the API using a Bearer Token
     *
     * @param string $token Bearer token
     * @param string $url Full endpoint URL
     * @param string $method GET, POST, PUT, DELETE
     * @param array  $params Request parameters
     * @return string|\WP_Error
     */
    public function callAPI($token, $url, $method, $params = [])
    {
        if (empty($token)) {
            return new \WP_Error('no_token', 'Bearer token not configured');
        }       
        $args = [
            'method'  => strtoupper($method),
            'headers' => [
                'Authorization' => 'Bearer ' . $token,
                'Content-Type'  => 'application/json',
                'X-Team' => 'N3',   
                'X-App' => 'N3-WP-PLUGIN',
            ],
            'timeout' => 30,
        ];
        
        // Add body if there are parameters
        if (!empty($params) && in_array($method, ['POST', 'PUT'])) {
            $args['body'] = json_encode($params);
        }

        // For GET, append parameters to the URL
        if ($method === 'GET' && !empty($params)) {
            $url = add_query_arg($params, $url);
        }
                
        $response = wp_remote_request($url, $args);

        // Handle WordPress errors
        if (is_wp_error($response)) {
            return $response;
        }

        $status_code = wp_remote_retrieve_response_code($response);
        $body        = wp_remote_retrieve_body($response);

        // Handle HTTP errors
        if ($status_code >= 400) {
            return new \WP_Error(
                'api_error',
                "API error (HTTP $status_code): $body"
            );
        }

        return $body;
    }    
    
}
