<?php

namespace Blazemedia\Affiliation\Rendering;

use Blazemedia\Affiliation\Support\Environment;
use Blazemedia\Affiliation\Utils\Logger;

/**
 * Client per effettuare il purge di uno shortcode sul Rendering Manager
 *
 * Esegue una POST verso: {BLZ_API_RENDERING_MANAGER}/v2/purge/shortcode
 * Headers richiesti:
 *  - Content-Type: application/json
 *  - X-API-KEY: sha256(API_SECRET)
 * Body:
 *  - { "shortcode": "[affiliate_table format_id=\"123\"]", "signature": "sha256(API_SECRET)" }
 */
class PurgeClient {

	const TIMEOUT = 15;

	protected string $baseUrl;
	private string $apiSecret;
	private string $apiKey;
	private ?string $source;

	public function __construct(?string $source = null) {

		$this->baseUrl = Environment::get('BLZ_API_RENDERING_MANAGER', 'https://rendering-manager.blazemedia.it/api/') . 'v2/';
		$this->apiSecret = Environment::get('BLZ_AFF_API_SECRET', '');
		$this->apiKey = hash('sha256', $this->apiSecret);
		$this->source = $source ?: home_url();
	}

	/**
	 * Invia richiesta di purge per uno specifico shortcode
	 *
	 * @param string $shortcode Esempio: "[affiliate_table format_id=\"123\"]"
	 * @param string $signature sha256(API_SECRET)
	 * @return bool true se la richiesta ha avuto esito positivo (HTTP 200)
	 */
	public function purgeShortcode(string $shortcode, string $signature): bool {

		$apiCall = $this->baseUrl . 'purge/shortcode';

		$options = [
			'headers'   => [
				'Content-Type' => 'application/json',
				'X-API-KEY'    => $this->apiKey,
				'Source'       => $this->source,
			],
			'body'      => json_encode([
				'shortcode' => urlencode(urlencode($shortcode)),
				'signature' => $signature,
			]),
			'timeout'   => self::TIMEOUT,
			'sslverify' => false,
			'Accept'    => 'application/json',
		];

		try {
			$response = wp_remote_post($apiCall, $options);
		} catch (\Throwable $th) {
			//Print curl request to paste in postman
			print_r('curl -X POST ' . $apiCall . ' -H "Content-Type: application/json" -H "X-API-KEY: ' . $this->apiKey . '" -H "Source: ' . $this->source . '" -d \'{"shortcode": "' . urlencode(urlencode($shortcode)) . '", "signature": "' . $signature . '", "Accept": "application/json"}\'');
			Logger::write("Error purging shortcode {$shortcode}: " . $th->getMessage(), "ERROR");
			return false;
		}

		if (is_wp_error($response)) {
			print_r('curl -X POST ' . $apiCall . ' -H "Content-Type: application/json" -H "X-API-KEY: ' . $this->apiKey . '" -H "Source: ' . $this->source . '" -d \'{"shortcode": "' . urlencode(urlencode($shortcode)) . '", "signature": "' . $signature . '", "Accept": "application/json"}\'');
			Logger::write("Error purging shortcode {$shortcode}: " . $response->get_error_message(), "ERROR");
			return false;
		}

		$responseCode = wp_remote_retrieve_response_code($response);
		if ($responseCode !== 200) {
			print_r('curl -X POST ' . $apiCall . ' -H "Content-Type: application/json" -H "X-API-KEY: ' . $this->apiKey . '" -H "Source: ' . $this->source . '" -d \'{"shortcode": "' . urlencode(urlencode($shortcode)) . '", "signature": "' . $signature . '", "Accept": "application/json"}\'');
			Logger::write("Error purging shortcode {$shortcode}: " . $responseCode, "ERROR");
			return false;
		}

		return true;
	}
}


