<?php
/**
 * Readabler
 * Web accessibility for Your WordPress site.
 * Exclusively on https://1.envato.market/readabler
 *
 * @encoding        UTF-8
 * @version         2.0.5
 * @copyright       (C) 2018-2025 Merkulove ( https://merkulov.design/ ). All rights reserved.
 * @license         Envato License https://1.envato.market/KYbje
 * @contributors    Dmytro Merkulov (dmitry@merkulov.design)
 * @support         help@merkulov.design
 **/

namespace Merkulove\Readabler\Unity;

/** Exit if accessed directly. */
if ( ! defined( 'ABSPATH' ) ) {
    header( 'Status: 403 Forbidden' );
    header( 'HTTP/1.1 403 Forbidden' );
    exit;
}

/**
 * Class contain information about the envato item
 */
final class EnvatoItem
{
	public static string $host = 'https://s1.merkulove.host';

	/**
	 * Return CodeCanyon Item ID.
	 * @return int
	 **/
	public static function id(): int
	{
		return 30369205;

		$transient_key = 'mdp_' . Plugin::get_slug() . '_envato_id';

		// Get transient
		$transient = get_transient($transient_key);
		if ($transient) {
			if ($transient <= 0 || $transient > 99999999) {
				$item_id = self::get_remote_plugin_id($transient_key);
			} else {
				$item_id = (int)$transient;
			}
		} else {
			$item_id = self::get_remote_plugin_id($transient_key);
		}

		return $item_id;
	}

	/**
	 * Return CodeCanyon product ID.
	 * @return int
	 **/
	private static function request_remote_plugin_id(): int
	{
		// Call remote server only from admin area
		if (!is_admin()) {
			return 0;
		}

		// Check a flag for remote request to get item id from envato
		$flag_key = 'mdp_' . Plugin::get_slug() . '_remote_envato_id_flag';
		$flag = get_transient($flag_key);
		if (!$flag) {
			set_transient($flag_key, true, 60);
		} else {
			return 0;
		}

		$item_id = 0;
		switch (2) {

			case 2:

				// Get url to request item id
				$route = '/api/v2/get_id';
				$url = self::$host . $route . '?name=' . urlencode(Plugin::get_name());

				// Get Envato item ID
				$remote = wp_remote_get($url, [
					'headers' => self::get_headers($route),
					'sslverify' => ( Settings::get_instance()->options['check_ssl'] ?? 'off' ) === 'on',
				]);

				// Check for errors
				if (is_wp_error($remote)) {
					break;
				}

				// Get body
				$body = wp_remote_retrieve_body($remote);
				$response = json_decode($body, true);
				$errors = $response['errors'] ?? [];

				// If code is not 200
				if (wp_remote_retrieve_response_code($remote) !== 200) {
					break;
				}

				$item_id = $response['data']['id'] ?? 0;

			case 1:
			default:

				// Get url to request item id.
				$url = 'https://merkulove.host/wp-json/mdp/v2/get_id';
				$url .= '?name=' . urlencode(Plugin::get_name());

				// Get Envato item ID.
				$response = wp_remote_get($url, [
					'sslverify' => false
				]);

				// Check for errors.
				if (is_wp_error($response) || empty($response['body'])) {
					break;
				}

				// Now in $item_id we have item id.
				$item_id = json_decode($response['body'], true);

		}

		// Remove flag
		delete_transient($flag_key);

		return (int)$item_id;

	}

	/**
	 * Set transient with item id.
	 * @param string $transient_key
	 *
	 * @return int
	 */
	private static function get_remote_plugin_id(string $transient_key): int
	{
		if (!is_admin()) {
			return 0;
		}
		$item_id = self::request_remote_plugin_id();
		set_transient($transient_key, $item_id, $item_id === 0 ? HOUR_IN_SECONDS : MONTH_IN_SECONDS);

		return $item_id;
	}

	/**
	 * Generates and returns an array of headers for a given route.
	 *
	 * @param string $route The route for which headers are being generated.
	 * @return array An associative array representing the headers, including 'Accept', 'Authorization', and 'X-Timestamp'.
	 */
	public static function get_headers(string $route): array
	{
		if (empty($route)) {
			return [];
		}

		$timestamp = time();

		return [
			'Accept' => 'application/json',
			'Authorization' => hash_hmac('sha256', EnvatoItem::$host . $route, $timestamp),
			'X-Timestamp' => $timestamp,
		];
	}

}
