<?php
namespace WPDRMS\ASP\Updates;

use stdClass;
use WP_Error;
use WPDRMS\ASP\Misc\PluginLicense;

class Manager {

	/**
	 * Plugin Slug (plugin_directory/plugin_file.php)
	 *
	 * @var string
	 */
	public $plugin_slug;

	/**
	 * Plugin name (plugin_file)
	 *
	 * @var string
	 */
	public $slug;

	/**
	 * Updates Object
	 *
	 * @var Object
	 */
	private Remote $updates_obj;

	private $download_link_url = 'https://update.wp-dreams.com/';

	/**
	 * Initialize a new instance of the WordPress Auto-Update class
	 *
	 * @param string $plugin_slug
	 * @param object $updates_o
	 */
	function __construct( $plugin_name, $plugin_slug, Remote $updates_o ) {
		// Set the class public variables
		$this->plugin_slug = $plugin_slug;
		$this->updates_obj = $updates_o;
		$t                 = explode( '/', $plugin_slug );
		$this->slug        = str_replace( '.php', '', $t[1] );

		// define the alternative API for updating checking
		add_filter( 'pre_set_site_transient_update_plugins', array( &$this, 'check_update' ) );

		// Define the alternative response for information checking
		add_filter( 'plugins_api', array( &$this, 'check_info' ), 10, 3 );
		add_filter( 'plugin_row_meta', array( $this, 'plugin_row_meta' ), 10, 2 );

		add_action( 'in_plugin_update_message-' . $plugin_name, array( &$this, 'addUpgradeMessageLink' ) );
	}

	/**
	 * Add our self-hosted autoupdate plugin to the filter transient
	 *
	 * @param $transient
	 *
	 * @return object $ transient
	 */
	public function check_update( $transient ) {
		if ( empty( $transient->checked ) ) {
			return $transient;
		}

		if ( !is_object($transient) && isset($transient->response[ $this->plugin_slug ]) ) {
			return $transient;
		}

		$obj = $this->getPluginInformationObject();
		if ( $this->updates_obj->needsUpdate( true ) ) {
			$update_link = '';
			// No need to check the remote, as the ->getDownLoadURL will do it later
			$license_key = PluginLicense::isActivated();
			if ( $license_key !== false ) {
				if ( get_site_transient('_asp_update_dl_url') === false ) {
					$response = $this->getDownloadUrl( $license_key );
					if ( !empty($response) ) {
						if ( isset($response['status']) && $response['status'] != 1 ) {
							return $transient;
						} else {
							$update_link = $response['url'];
							set_site_transient('_asp_update_dl_url', $update_link, 60);
						}
					}
				} else {
					$update_link = get_site_transient('_asp_update_dl_url');
				}
			}

			$obj->package                   = $update_link;
			$obj->download_link             = $update_link;
			$obj->versions                  = array();
			$obj->versions[ $obj->version ] = $update_link;

			$transient->response[ $this->plugin_slug ] = $obj;
			unset($transient->no_update[ $this->plugin_slug ]);
		} else {
			$transient->no_update[ $this->plugin_slug ] = $obj;
			unset( $transient->response[ $this->plugin_slug ] );
		}

		return $transient;
	}

	public function plugin_row_meta( $plugin_meta, $plugin_file ) {
		if ( ASP_PLUGIN_BASE === $plugin_file ) {
			$plugin_slug = $this->slug;
			$plugin_name = __( 'Ajax Search Pro', 'ajax-search-pro' );

			$row_meta = array(
				'view-details' => sprintf(
					'<a href="%s" class="thickbox open-plugin-details-modal" aria-label="%s" data-title="%s">%s</a>',
					esc_url( network_admin_url( 'plugin-install.php?tab=plugin-information&plugin=' . $plugin_slug . '&TB_iframe=true&width=600&height=550' ) ),
					/* translators: %s: Plugin name - Elementor Pro. */
					esc_attr( sprintf( __( 'More information about %s', 'ajax-search-pro' ), $plugin_name ) ),
					esc_attr( $plugin_name ),
					__( 'View details', 'ajax-search-pro' )
				),
				'changelog'    => '<a href="https://changelog.ajaxsearchpro.com/" title="' . esc_attr( __( 'View Ajax Search Pro Pro Changelog', 'ajax-search-pro' ) ) . '" target="_blank">' . __( 'Changelog', 'ajax-search-pro' ) . '</a>',
			);

			$plugin_meta = array_merge( $plugin_meta, $row_meta );
		}

		return $plugin_meta;
	}

	/**
	 * Add our self-hosted description to the filter
	 *
	 * @param boolean $false
	 * @param array   $action
	 * @param object  $arg
	 *
	 * @return bool|object
	 */
	public function check_info( $false, $action, $arg ) {

		if ( !is_object($arg) || !isset($arg->slug) || !isset($this->slug) ) {
			return $false;
		}

		if ( $arg->slug == $this->slug ) {
			return $this->getPluginInformationObject();
		}

		return $false;
	}

	/**
	 * Shows message on Wp plugins page with a link for updating from envato.
	 */
	public function addUpgradeMessageLink() {
		echo '<style media="all">tr#ajax-search-pro + tr.plugin-update-tr a.thickbox + em { display: none; }</style>';
		if ( PluginLicense::isActivated() === false ) {
			echo ' <a href="' . get_admin_url() . 'admin.php?page=asp_updates_help">' . __( 'Activate your license', 'ajax-search-pro') . '</a> ' . __( 'for automatic updates or', 'ajax-search-pro') . ' <a target="_blank" href="https://wp-dreams.com/products/">' . __( 'download the latest version.', 'ajax-search-pro' ) . '</a>';
		}
	}


	/**
	 * Get unique, short-lived download link
	 *
	 * @param string $license_key
	 *
	 * @return array|boolean JSON response or false if request failed
	 */
	public function getDownloadUrl( $license_key ) {
		$url      = rawurlencode( $_SERVER['HTTP_HOST'] );
		$key      = rawurlencode( $license_key );
		$url      = $this->download_link_url . "tokens/generate/$key?url=" . $url;
		$response = wp_remote_get( $url );

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

		return json_decode( $response['body'], true );
	}

	private function getPluginInformationObject(): stdClass {
		$information = new stdClass();

		$information->name          = 'Ajax Search Pro';
		$information->plugin        = $this->plugin_slug;
		$information->slug          = $this->slug;
		$information->author        = '<a href="https://ajaxsearchpro.com/">AjaxSearchPro.com</a>';
		$information->new_version   = $this->updates_obj->getVersionString();
		$information->version       = $this->updates_obj->getVersionString();
		$information->requires      = $this->updates_obj->getRequiresVersion();
		$information->tested        = $this->updates_obj->getTestedVersion();
		$information->downloaded    = $this->updates_obj->getDownloadedCount();
		$information->last_updated  = $this->updates_obj->getLastUpdated();
		$information->url           = 'https://ajaxsearchpro.com/';
		$information->sections      = array(
			'changelog' => '<h4>Version ' . $this->updates_obj->getVersionString() . "</h4><p>
					For the changelog please visit <a target='_blank' href='https://changelog.ajaxsearchpro.com/'>the knowledge base.</a>
				</p>",
		);
		$information->banners       = array(
			'high' => 'https://ajaxsearchpro.com/assets/banner-1544x500-min.png',
			'low'  => 'https://ajaxsearchpro.com/assets/banner-1544x500-min.png',
		);
		$information->icons         = array(
			'1x'      => 'https://ajaxsearchpro.com/wp-content/uploads/2025/12/ajax-search-pro-256x256-rounded.png',
			'2x'      => 'https://ajaxsearchpro.com/wp-content/uploads/2025/12/ajax-search-pro-256x256-rounded.png',
			'default' => 'https://ajaxsearchpro.com/wp-content/uploads/2025/12/ajax-search-pro-256x256-rounded.png',
		);
		$information->download_link = 'https://wp-dreams.com/products/';

		return $information;
	}
}
