<?php

namespace ShopManagerPro\Shared;

class UpdateCheckerService {
	public static string $updateURL = 'https://shopmanagerpro.com/wp-content/uploads/releases/shopmanagerpro/update-info.json';
	private const PLUGIN_SLUG = 'shopmanagerpro';
	private const PLUGIN_BASENAME = SHOP_MANAGER_PRO_PLUGIN_BASENAME;
	private const CACHE_KEY = 'shopmanagerpro_update_info';
	private const CACHE_DURATION = 1 * MINUTE_IN_SECONDS;

	public static function init() {
		add_filter('pre_set_site_transient_update_plugins', [self::class, 'checkForUpdate']);
		add_filter('plugins_api', [self::class, 'pluginInfo'], 10, 3);
		add_action('upgrader_process_complete', [self::class, 'purgeCache'], 10, 2);
	}

	public static function checkForUpdate($transient) {
		if (empty($transient->checked)) {
			return $transient;
		} $remoteInfo = self::getRemoteInfo();
		if (!$remoteInfo) {
			return $transient;
		} if (version_compare(SHOP_MANAGER_PRO_VERSION, $remoteInfo['version'], '<')) {
			$pluginData = ['slug' => self::PLUGIN_SLUG, 'plugin' => self::PLUGIN_BASENAME, 'new_version' => $remoteInfo['version'], 'url' => $remoteInfo['homepage'] ?? '', 'package' => $remoteInfo['download_url'], 'tested' => $remoteInfo['tested'] ?? '', 'requires' => $remoteInfo['requires'] ?? '', 'requires_php' => $remoteInfo['requires_php'] ?? '', 'icons' => $remoteInfo['icons'] ?? [], 'banners' => $remoteInfo['banners'] ?? []];
			$transient->response[self::PLUGIN_BASENAME] = (object) $pluginData;
		}

return $transient;
	}

	public static function pluginInfo($result, string $action, object $args) {
		if ($action !== 'plugin_information') {
			return $result;
		} if (!isset($args->slug) || $args->slug !== self::PLUGIN_SLUG) {
			return $result;
		} $remoteInfo = self::getRemoteInfo();
		if (!$remoteInfo) {
			return $result;
		} $pluginInfo = ['name' => $remoteInfo['name'] ?? 'Shop Manager Pro', 'slug' => self::PLUGIN_SLUG, 'version' => $remoteInfo['version'], 'author' => $remoteInfo['author'] ?? 'Shop Manager Pro', 'homepage' => $remoteInfo['homepage'] ?? '', 'download_link' => $remoteInfo['download_url'], 'trunk' => $remoteInfo['download_url'], 'requires' => $remoteInfo['requires'] ?? '', 'tested' => $remoteInfo['tested'] ?? '', 'requires_php' => $remoteInfo['requires_php'] ?? '', 'last_updated' => $remoteInfo['last_updated'] ?? '', 'sections' => $remoteInfo['sections'] ?? [], 'banners' => $remoteInfo['banners'] ?? [], 'icons' => $remoteInfo['icons'] ?? []];

		return (object) $pluginInfo;
	}

	private static function getRemoteInfo() {
		$cachedInfo = get_transient(self::CACHE_KEY);
		if ($cachedInfo !== false) {
			return $cachedInfo;
		} $response = wp_remote_get(self::$updateURL, ['timeout' => 10, 'headers' => ['Accept' => 'application/json']]);
		if ($response instanceof \WP_Error) {
			Utils\Logger::error('Failed to check for updates', ['error' => $response->get_error_message()]);

			return false;
		} $responseCode = wp_remote_retrieve_response_code($response);
		if ($responseCode !== 200) {
			Utils\Logger::error('Update check failed', ['response_code' => $responseCode]);

			return false;
		} $body = wp_remote_retrieve_body($response);
		$data = Utils\JSON::decode($body);
		if (!$data || !isset($data['version'])) {
			Utils\Logger::error('Invalid update response format');

			return false;
		} set_transient(self::CACHE_KEY, $data, self::CACHE_DURATION);

		return $data;
	}

	public static function purgeCache($upgrader, $options) {
		if ($options['action'] === 'update' && $options['type'] === 'plugin') {
			if (isset($options['plugins']) && in_array(self::PLUGIN_BASENAME, $options['plugins'])) {
				delete_transient(self::CACHE_KEY);
			}
		}
	}
}
