<?php
/**
 * Spacetree Changelog Helper
 * 
 * Fetches changelog data from the changelog endpoint.
 *
 * @package Spacetree
 * @since   2.1.0
 */

defined( 'ABSPATH' ) || exit;

/**
 * ST_Changelog class.
 */
class ST_Changelog {

	/**
	 * Get changelog data from endpoint
	 *
	 * @return array|false Changelog data or false on error
	 */
	public static function get_changelog_data() {
		// Use transient caching to avoid excessive API calls
		$cache_key = 'st_changelog_data';
		
		// Allow clearing cache via URL parameter
		if ( isset( $_GET['clear-cache'] ) && $_GET['clear-cache'] === '1' ) {
			delete_transient( $cache_key );
		}
		
		$cached_data = get_transient( $cache_key );
		
		if ( $cached_data !== false ) {
			return $cached_data;
		}

		// Build the full endpoint URL
		$endpoint_url = ST_CHANGELOG_ENDPOINT . '/wp-json/spacetree/v1/changelog';

		// Make the GET request
		$response = wp_remote_get( $endpoint_url, array(
			'timeout' => 15,
			'headers' => array(
				'Accept' => 'application/json',
			),
		) );

		// Check for errors
		if ( is_wp_error( $response ) ) {
			return false;
		}

		$response_code = wp_remote_retrieve_response_code( $response );
		
		if ( $response_code !== 200 ) {
			return false;
		}

		$body = wp_remote_retrieve_body( $response );
		
		// First, convert unicode escape sequences to actual characters
		// This handles \u003C becoming < etc.
		$body = preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/', function ($match) {
			return mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UCS-2BE');
		}, $body);
		
		$data = json_decode( $body, true );

		if ( ! $data || ! isset( $data['success'] ) || ! $data['success'] ) {
			return false;
		}

		$changelog_data = isset( $data['data'] ) ? $data['data'] : array();

		// Cache the data for 6 hours (or less if WP_DEBUG is enabled)
		$cache_duration = defined( 'WP_DEBUG' ) && WP_DEBUG ? 5 * MINUTE_IN_SECONDS : 6 * HOUR_IN_SECONDS;
		$cache_duration = apply_filters( 'st_changelog_cache_duration', $cache_duration );
		set_transient( $cache_key, $changelog_data, $cache_duration );

		return $changelog_data;
	}

	/**
	 * Get changelog for a specific version
	 *
	 * @param string $version Version number (e.g., '2.1.0')
	 * @return array|false Changelog entry or false if not found
	 */
	public static function get_changelog_by_version( $version ) {
		$changelogs = self::get_changelog_data();

		if ( ! $changelogs ) {
			return false;
		}

		foreach ( $changelogs as $changelog ) {
			if ( isset( $changelog['version'] ) && $changelog['version'] === $version ) {
				return $changelog;
			}
		}

		return false;
	}

	/**
	 * Get latest changelog entry
	 *
	 * @return array|false Latest changelog entry or false if none found
	 */
	public static function get_latest_changelog() {
		$changelogs = self::get_changelog_data();

		if ( ! $changelogs || empty( $changelogs ) ) {
			return false;
		}

		return $changelogs[0]; // First entry is the latest
	}

	/**
	 * Clear changelog cache
	 */
	public static function clear_cache() {
		delete_transient( 'st_changelog_data' );
	}

	/**
	 * Format changelog content for display
	 *
	 * @param array $changelog Changelog entry
	 * @return string Formatted HTML
	 */
	public static function format_changelog( $changelog ) {
		if ( ! $changelog ) {
			return '';
		}

		$output = '<div class="st-changelog-entry">';
		
		if ( isset( $changelog['version'] ) ) {
			$output .= '<h3>Version ' . esc_html( $changelog['version'] ) . '</h3>';
		}

		if ( isset( $changelog['release_date'] ) ) {
			$output .= '<p class="changelog-date"><strong>Released:</strong> ' . esc_html( date( 'F j, Y', strtotime( $changelog['release_date'] ) ) ) . '</p>';
		}

		if ( isset( $changelog['content'] ) ) {
			$output .= '<div class="changelog-content">' . wp_kses_post( $changelog['content'] ) . '</div>';
		}

		$output .= '</div>';

		return $output;
	}
}

