<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

/**
 * Handles the update manager for Customer Email Verification Pro.
 */
class Cev_Pro_Update_Manager {

	public $item_code = 'wc_cev';
	public $store_url = 'https://www.zorem.com/';
	public $license_status;
	public $license_key;
	public $license_email;
	public $slug;
	public $plugin;
	public $current_version;
	public $cachedInstalledVersion;

	/**
	 * Constructor - Initializes the update manager.
	 *
	 * @param string $current_version Current plugin version.
	 * @param string $pluginFile Plugin file path.
	 * @param string $slug Plugin slug.
	 */
	public function __construct( $current_version, $pluginFile, $slug = '' ) {
		$this->slug = $slug;
		$this->plugin = $pluginFile;
		$this->current_version = $current_version;
		$this->init();
		$this->cachedInstalledVersion = null;
	}

	/**
	 * Holds the instance of this class.
	 *
	 * @var object Class Instance.
	 */
	private static $instance;

	/**
	 * Get the class instance (Singleton Pattern).
	 *
	 * @return Cev_Pro_Update_Manager
	 */
	public static function get_instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	/**
	 * Initializes plugin update-related hooks.
	 */
	public function init() {
		// Add filters to check for plugin updates.
		add_filter( 'site_transient_update_plugins', array( $this, 'check_update' ) ); // WP 3.0+
		add_filter( 'transient_update_plugins', array( $this, 'check_update' ) ); // WP 2.8+

		// Add an update message link in the plugins page.
		add_action( 'in_plugin_update_message-' . $this->plugin, array( $this, 'addUpgradeMessageLink' ) );

		// Clear cache after plugin update.
		add_action( 'upgrader_process_complete', array( $this, 'after_update' ), 10, 2 );

		// Fetch plugin information.
		add_filter( 'plugins_api', array( $this, 'cev_plugin_info' ), 20, 3 );
	}

	/**
	 * Checks for updates and adds them to the WordPress update transient.
	 *
	 * @param object $transient The update transient.
	 * @return object Modified transient with update information.
	 */
	public function check_update( $transient ) {
		if ( empty( $transient->checked ) ) {
			return $transient;
		}

		// Get cached update data.
		$remote_update = get_transient( 'zorem_upgrade_' . $this->slug );

		// Fetch new update data if cache is empty.
		if ( false == $remote_update ) {
			$remote_update = $this->getRemote_update();
		}

		// Validate update data.
		if ( $remote_update ) {
			if ( is_wp_error( $remote_update ) || wp_remote_retrieve_response_code( $remote_update ) != 200 ) {
				return $transient;
			}

			$data = json_decode( wp_remote_retrieve_body( $remote_update ) );

			if ( ! isset( $data->data->package->new_version ) ) {
				return $transient;
			}

			// Compare versions and add update if needed.
			$remote_version = $data->data->package->new_version;
			if ( version_compare( $this->current_version, $remote_version, '<' ) ) {
				$obj = new stdClass();
				$obj->slug = $this->slug;
				$obj->new_version = $remote_version;
				$obj->plugin = $this->plugin;
				$obj->package = $data->data->package->package;
				$obj->tested = $data->data->package->tested;
				$transient->response[ $this->plugin ] = $obj;
			}
		}

		return $transient;
	}

	/**
	 * Fetches the latest update information from the remote server.
	 *
	 * @return array|false Remote update response or false on failure.
	 */
	public function getRemote_update() {
		// Fix SSL SNI issue for older cURL versions.
		$filter_add = true;
		if ( function_exists( 'curl_version' ) ) {
			$version = curl_version();
			if ( version_compare( $version['version'], '7.18', '>=' ) ) {
				$filter_add = false;
			}
		}
		if ( $filter_add ) {
			add_filter( 'https_ssl_verify', '__return_false' );
		}

		$instance_id = cev_pro()->license->get_instance_id();
		$domain = home_url();

		// API request parameters.
		$api_params = array(
			'wc-api'       => 'wc-am-api',
			'wc_am_action' => 'update',
			'instance'     => $instance_id,
			'object'       => $domain,
			'product_id'   => cev_pro()->license->get_product_id(),
			'api_key'      => cev_pro()->license->get_license_key(),
			'plugin_name'  => $this->plugin,
			'version'      => $this->current_version,
		);

		$request = add_query_arg( $api_params, $this->store_url );
		$response = wp_remote_get( $request, array( 'timeout' => 15, 'sslverify' => false ) );

		// Handle errors.
		if ( is_wp_error( $response ) ) {
			return false;
		}

		// Cache response.
		if ( ! is_wp_error( $response ) || wp_remote_retrieve_response_code( $response ) === 200 ) {
			set_transient( 'zorem_upgrade_' . $this->slug, $response, 43200 ); // Cache for 12 hours.
			return $response;
		}

		return false;
	}

	/**
	 * Adds an update message in the WordPress Plugins page.
	 */
	public function addUpgradeMessageLink() {
		if ( cev_pro()->license->get_license_status() ) {
			return;
		}

		$url = admin_url( 'admin.php?page=customer-email-verification-for-woocommerce&tab=add-ons' );

		/* translators: %s: Customer Email Verification PRO */
		echo sprintf( ' ' . esc_html__( 'To receive automatic updates, license activation is required. Please visit %1$ssettings%2$s to activate your Customer Email Verification Pro.', 'customer-email-verification-pro' ), '<a href="' . esc_url( $url ) . '" target="_blank">', '</a>' );
	}

	/**
	 * Clears update cache after plugin update.
	 *
	 * @param object $upgrader_object WP_Upgrader instance.
	 * @param array  $options Update options.
	 */
	public function after_update( $upgrader_object, $options ) {
		if ( 'update' == $options['action'] && 'plugin' === $options['type'] ) {
			delete_transient( 'zorem_upgrade_' . $this->slug );
		}
	}

	/**
	 * Retrieves plugin information for WordPress plugin details modal.
	 *
	 * @param object $res Response object.
	 * @param string $action Requested action.
	 * @param object $args Request arguments.
	 * @return object|false Updated response object or false on failure.
	 */
	public function cev_plugin_info( $res, $action, $args ) {
		if ( 'plugin_information' !== $action ) {
			return $res;
		}

		$instance_id = cev_pro()->license->get_instance_id();
		$domain = home_url();

		// API request to fetch plugin details.
		$api_params = array(
			'wc-api'       => 'wc-am-api',
			'wc_am_action' => 'plugininformation',
			'instance'     => $instance_id,
			'object'       => $domain,
			'product_id'   => cev_pro()->license->get_product_id(),
			'api_key'      => cev_pro()->license->get_license_key(),
			'plugin_name'  => $this->plugin,
			'version'      => $this->current_version,
		);

		$request = add_query_arg( $api_params, $this->store_url );
		$response = wp_remote_get( $request, array( 'timeout' => 15, 'sslverify' => false ) );

		if ( is_wp_error( $response ) ) {
			return false;
		}

		return $res;
	}
}
