<?php

namespace SWPanel;

defined('ABSPATH') || die('No direct access.');

class WpRestClient {
    public static function post($endpoint, $params = []) {
        return static::request('POST', $endpoint, $params);
    }

    public static function get($endpoint, $params = []) {
        return static::request('GET', $endpoint, $params);
    }

    public static function put($endpoint, $params = []) {
        return static::request('PUT', $endpoint, $params);
    }

    protected static function request($method, $endpoint, $params = []) {
        $request = new \WP_REST_Request($method, $endpoint);

        if ($method === 'GET') {
            $request->set_query_params($params);
        } else {
            $request->set_body_params($params);
        }

        $response = rest_do_request($request);

        if (is_wp_error($response)) {
			// phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped
            throw new \Exception(__('There was an error communicating with the WordPress API. Please check your site and try again.', 'swpanel-ai'));
        }

        $code = $response->get_status();
        if ($code < 200 || $code >= 300) {
			// phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped
            throw new \Exception(__('The WordPress API returned an unexpected response. Please try again later.', 'swpanel-ai'));
        }

        return $response->get_data();
    }
}
