<?php
/**
 * HTTP client for Boostanova AI backend.
 *
 * @package BOOSAIAS_For_WooCommerce
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class BOOSAIAS_Api_Client {

	private function get_backend_url() {
		// Allow override via wp-config.php for local development.
		if ( defined( 'BOOSAIAS_BACKEND_URL' ) ) {
			return untrailingslashit( BOOSAIAS_BACKEND_URL );
		}
		return 'https://woo-ai-backend-zqxo.vercel.app';
	}

	private function get_license_key() {
		return (string) get_option( 'boosaias_license_key', '' );
	}

	public function post( $endpoint, $body, $timeout = 15 ) {
		$url = $this->get_backend_url() . $endpoint;
		$key = $this->get_license_key();

		$args = array(
			'headers' => array(
				'Content-Type'  => 'application/json',
				'X-License-Key' => $key,
				'X-Site-Url'    => get_site_url(),
			),
			'body'    => wp_json_encode( $body ),
			'timeout' => $timeout,
		);

		$response = wp_remote_post( $url, $args );

		if ( is_wp_error( $response ) ) {
			// retry once
			$response = wp_remote_post( $url, $args );
		}

		return $response;
	}

	public function activate_license( $license_key, $settings = array() ) {
		$url  = $this->get_backend_url() . '/api/license/activate';
		$body = array(
			'license_key' => $license_key,
			'site_url'    => get_site_url(),
			'settings'    => $settings,
		);

		$response = wp_remote_post(
			$url,
			array(
				'headers' => array( 'Content-Type' => 'application/json' ),
				'body'    => wp_json_encode( $body ),
				'timeout' => 15,
			)
		);

		if ( is_wp_error( $response ) ) {
			$response = wp_remote_post(
				$url,
				array(
					'headers' => array( 'Content-Type' => 'application/json' ),
					'body'    => wp_json_encode( $body ),
					'timeout' => 15,
				)
			);
		}

		return $response;
	}
}
