<?php

namespace SWPanel;

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

class APIClient {
    public static function get($endpoint, $data = false) {
        return static::request('GET', $endpoint, $data);
    }

    public static function post($endpoint, $data = false) {
        return static::request('POST', $endpoint, $data);
    }

    public static function put($endpoint, $data = false) {
        return static::request('PUT', $endpoint, $data);
    }

    protected static function request($method, $endpoint, $data = false) {
        $domain = home_url();
		$parsed = wp_parse_url($domain);
        $baseUrl = get_option('swpanel_ai_url', '');
        $url = $baseUrl . "/" . $parsed['host'] . $endpoint;
        $headers = ['Content-Type' => 'application/json'];
        $bearerToken = get_option('swpanel_ai_license_token');
        if ($bearerToken && $baseUrl) {
            $headers['Authorization'] = 'Bearer ' . $bearerToken;
        } else {
			// phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped
            throw new \Exception(__("No token was provided. Please include a valid token to continue.", 'swpanel-ai'));
        }
        $args = [
            'method'    => $method,
            'headers'   => $headers,
            'timeout'   => 180,
        ];
        if (in_array($method, ['POST', 'PUT'])) {
            $args['body'] = wp_json_encode($data);
        } elseif (!empty($data)) {
            $url = add_query_arg($data, $url);
        }
        $response = wp_remote_request($url, $args);
        if (is_wp_error($response)) {
            throw new \Exception('Request error: ' . esc_html($response->get_error_message()));
        }
        $body = wp_remote_retrieve_body($response);
        $code = wp_remote_retrieve_response_code($response);
        $json = json_decode($body, true);
        if ($code < 200 || $code >= 300) {
            if ($code == 401){
                if (isset($json["detail"])) {
			        // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped
                    throw new \Exception(__("No token was provided. Please include a valid token to continue.", 'swpanel-ai'));
                } else {
			        // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped
                    throw new \Exception(__("The token you provided is invalid or expired. Please request a new one and try again.", 'swpanel-ai'));
                }
            }
            if ($code == 422){
			    // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped
                throw new \Exception(__("Required parameters are missing. Please check your inputs and try again.", 'swpanel-ai'));
            }
			// phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped
            throw new \Exception(__("We couldn't get a response from the AI service. Please try again later.", 'swpanel-ai'));
        }
        return $json['result'];
    }
}