<?php
/**
 * @package CatalogPilot\AiStudio
 */

namespace CatalogPilot\AiStudio;

defined( 'ABSPATH' ) || exit;

final class Gateway {

	private static function base_url() : string {
		$url = untrailingslashit( (string) apply_filters( 'cpais_gateway_base_url', 'https://api.wpcrypto.net' ) );
		if ( substr( $url, -3 ) === '/v1' ) {
			$url = substr( $url, 0, -3 );
		}
		return $url;
	}

	public static function is_available() : bool {
		if ( ! Pro::can_use_pro() ) {
			return false;
		}
		return self::is_connected();
	}

	// Site is registered with the managed service (install present), regardless of plan.
	// Free installs use this for the small free-trial allowance (server-enforced).
	public static function is_connected() : bool {
		$install = self::get_install();
		return ! empty( $install['install_id'] ) && ! empty( $install['secret_key'] ) && ! empty( $install['public_key'] );
	}

	public static function get_install() : array {
		if ( ! function_exists( 'cpais_fs' ) ) {
			return array();
		}
		$fs = cpais_fs();
		if ( ! $fs ) {
			return array();
		}
		$site = method_exists( $fs, 'get_site' ) ? $fs->get_site() : null;
		if ( ! $site ) {
			return array();
		}
		return array(
			'install_id' => (int) ( $site->id ?? 0 ),
			'public_key' => (string) ( $site->public_key ?? '' ),
			'secret_key' => (string) ( $site->secret_key ?? '' ),
		);
	}

	public static function generate( array $body ) {
		return self::call( 'generate', $body );
	}

	public static function generate_image( array $body ) {
		return self::call( 'generate-image', $body );
	}

	public static function quota() {
		return self::call( 'quota', array() );
	}

	public static function quota_cached( bool $force = false ) : array {
		if ( ! self::is_connected() ) {
			return array();
		}
		$cached = get_transient( 'cpais_gateway_quota' );
		if ( ! $force && is_array( $cached ) ) {
			return $cached;
		}
		$res = self::quota();
		if ( is_wp_error( $res ) || ! is_array( $res ) || ! isset( $res['plan'] ) ) {
			return array();
		}
		set_transient( 'cpais_gateway_quota', $res, 5 * MINUTE_IN_SECONDS );
		return $res;
	}

	private static function call( string $action, array $body ) {
		$install = self::get_install();
		if ( empty( $install['install_id'] ) ) {
			return new \WP_Error( 'cpais_no_install', __( 'Site is not connected to Freemius yet.', 'catalogpilot-ai-studio-for-woocommerce' ) );
		}

		$payload = array_merge(
			array(
				'action'             => $action,
				'install_id'         => $install['install_id'],
				'install_public_key' => $install['public_key'],
				'install_secret_key' => $install['secret_key'],
			),
			$body
		);

		$resp = wp_remote_post( self::base_url() . '/gateway', array(
			'timeout' => 60,
			'headers' => array( 'Content-Type' => 'application/json' ),
			'body'    => wp_json_encode( $payload ),
		) );

		if ( is_wp_error( $resp ) ) {
			return $resp;
		}
		$code = (int) wp_remote_retrieve_response_code( $resp );
		$data = json_decode( wp_remote_retrieve_body( $resp ), true );

		if ( 200 !== $code ) {
			$err = is_array( $data ) && isset( $data['error']['code'] ) ? (string) $data['error']['code'] : 'gateway_error';
			$msg = is_array( $data ) && isset( $data['error']['message'] ) ? (string) $data['error']['message'] : sprintf( 'Gateway returned HTTP %d.', $code );
			return new \WP_Error( 'cpais_' . $err, $msg, array( 'status' => $code, 'body' => $data ) );
		}

		return is_array( $data ) ? $data : array();
	}
}
