<?php

/**
 * To use, add the following code to the plugin init:
 *
 * require_once ( plugin_dir_path( __FILE__ ) . 'admin/class-update-plugin.php' );
 * new Update_Plugin( __FILE__ );
 *
 * Then include this file with the plugin.
 *
 * - Requires WordPress -
 *
 * @author  Gabriel Mariani <gabriel@coursevector.com>
 */
class CV_Monitor_Update_Plugin {

	/**
	 * The plugin current version
	 * @var string
	 */
	private $current_version;

	/**
	 * The plugin remote update path
	 * @var string
	 */
	private $update_path = 'https://apps.coursevector.com/plugins/update2.php?p=';

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

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

	private $file_path;

	private $last_checked;

	/**
	 * Initialize a new instance of the WordPress Auto-Update class
	 * @param string $current_version
	 * @param string $plugin_slug
	 */
	public function __construct( $file_path, $slug, $version ) {
		// /home/blogcv/public_html/wp-content/plugins/cv-monitor/cv-monitor.php
		// to
		// cv-monitor/cv-monitor.php
		$this->file_path = $file_path;
		$arrPath = explode( DIRECTORY_SEPARATOR, $file_path );
		$this->plugin_slug = $arrPath[count($arrPath) - 2] . DIRECTORY_SEPARATOR . $arrPath[count($arrPath) - 1];
		$this->current_version = $version;
		$this->slug = $slug;
		$this->update_path .= $this->slug;

		//add_action( 'admin_init', array( &$this, 'action_admin_init' ) );
		//add_action( 'init', array( &$this, 'action_admin_init' ) );

		// 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
		// apply_filters( 'plugins_api', false|object|array $result, string $action, object $args )
		add_filter( 'plugins_api', array( &$this, 'check_info' ), 10, 3 );
	}

	/*
	Grab plugin data from the header that is parsed by wordpress

	Removed to remove dependency on get_plugin_data
	*/
	/*public function action_admin_init() {
		// If running blog-side, bail unless we've not checked in the last 12 hours
		if ( !function_exists( 'get_plugin_data' ) ){
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
		}

		$data = get_plugin_data( $this->file_path );
		 = $data['Version'];
		$this->slug = $data['TextDomain'];
		$this->update_path .= $this->slug;

		// 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 our self-hosted autoupdate plugin to the filter transient
	 *
	 * @param object $transient
	 * @return object
	 */
	public function check_update( $transient ) {
		if ( false === ( $data = get_site_transient( 'cv_monitor_update' ) ) ) {
			// Get the remote version
			$data = $this->get_remote( 'version' );
			if ( $data ) {
				$data->plugin = $this->plugin_slug;
				set_site_transient( 'cv_monitor_update', $data, 60 * 15 );
			} else {
				error_log('CV Monitor : Error getting version ' . print_r( $data, true ) );
			}
		}

		// If a newer version is available, add the update
		if ( version_compare( $this->current_version, $data->new_version, '<' ) ) {
			$transient->response[$this->plugin_slug] = $data;
		} else {
			$transient->no_update[$this->plugin_slug] = $data;
		}

		return $transient;
	}

	/**
	 * Add our self-hosted description to the filter
	 *
	 * @param boolean $false
	 * @param array $action
	 * @param object $arg
	 * @return bool|object
	 */
	public function check_info( $result, $action, $arg ) {
		// https://developer.wordpress.org/reference/functions/plugins_api/
		// query_plugins - action is object
		// plugin_information - action is object
		// hot_tags - action is array
		// hot_categories - action is array
		if ("plugin_information" !== $action) {
			return $result;
		}

		if ( $arg->slug === $this->slug ) {
			return $this->get_remote( 'info' );
		}
		return false;
	}

	/**
	 * Return the remote version
	 * @return string
	 */
	private function get_remote( $action ) {
		switch ( $action ) {
			case 'version' : // Return the remote version
			case 'info' : // Get information about the remote version
			case 'license' : // Return the status of the plugin licensing
				// Ok
			default :
				$action = 'version';
		}

		if ( false === ($raw_response = get_transient( 'cv_monitor_upgrade_' . $action ))) {
			$raw_response = wp_remote_post( $this->update_path, array( 'body'=>array( 'action'=>$action ) ) );

			if ( is_wp_error( $raw_response ) || 200 != wp_remote_retrieve_response_code( $raw_response ) ) {
				error_log('CV Monitor : Error getting ' . $action . ' ' . print_r( $raw_response, true ) );
				return false;
			}

			set_transient( 'cv_monitor_upgrade_' . $action, $raw_response, 60 * 15 );
		}

		$response = wp_remote_retrieve_body( $raw_response );
		if ( 'license' != $action ) {
			$response = unserialize( $response );
		}
		return $response;
	}
}