<?php
/*
* Define class AATeam_Product_Updater
* Make sure you skip down to the end of this file, as there are a few
* lines of code that are very important.
*/
!defined('ABSPATH') and exit;
if (class_exists('Kingdom_AATeam_Product_Updater') != true) {
    class Kingdom_AATeam_Product_Updater
    {
    	/*
        * Store some helpers config
        */	
        protected $the_theme = null;
		
		protected $updater_dev = null;
		
		/**
		 * Current version
		 *
		 * @var string
		 */
		public $product_data;
	
		/**
		 * The product remote update url
		 *
		 * @var string
		 */
		protected $update_url = 'http://docs.aa-team.com/apps-versions/';
		
		/**
		 * The product download update url
		 *
		 * @var string
		 */
		protected $download_url = 'http://docs.aa-team.com/apps-versions/';
		
		protected $key_alias = '_cb_register_ipc';
		
		/**
		 * Product alias & path
		 *
		 * @var string
		 */
		public $product_slug;
		public $product_path;
		
		/**
		 * @var string
		 */
		public $title = 'kingdom';
		    
        /*
        * Required __construct() function that initalizes the AA-Team Framework
        */
        function __construct( $the_theme, $product_slug, $product_path )
        {
        	
            // Set the class public variables
            $this->update_url = $this->update_url . $product_slug;
            $this->the_theme = $the_theme;
            $this->product_data = wp_get_theme( 'kingdom' );
			$this->current_version = $this->product_data->get( 'Version' );
			$this->product_slug = $product_slug;
			$this->product_path = $product_path;
			$this->updater_dev = $the_theme->updater_dev;
			
			// define the alternative API for updating checking
			add_filter( 'pre_site_transient_update_themes', array(
				$this,
				'check_update'
			) );
			
			// Define the alternative response for information checking
			/*add_filter( 'themes_api', array(
				$this,
				'check_info',
			), 10, 3 );*/
			
			add_filter( 'upgrader_pre_download', array(
				$this,
				'preUpgradeFilter',
			), 10, 4 );
        }

        
		/**
		 * Get unique, short-lived download link
		 *
		 * @return array|boolean JSON response or false if request failed
		 */
		public function getDownloadUrl() {
			$url = $this->getUrl();
			
			$response = wp_remote_get( $url );

			if ( is_wp_error( $response ) ) {
				return false;
			}
	
			return json_decode( $response['body'], true );
		}
		
		protected function getUrl() {
			global $wpdb;
			
			if( isset($this->key_alias) && trim($this->key_alias) != '' ) {
				$ipc = 2712;
			}
			
			$url = $this->download_url . '?product=' . $this->product_slug . '&ipc=' . $ipc . '&version=' . $this->current_version . '&site_url=' . urlencode( esc_url(home_url('/')) ) . ( isset($this->updater_dev) ? '&updater_dev=' . $this->updater_dev : '' );
			
			if( $this->product_slug == 'woozone' ) {
				$product_count = $wpdb->get_col( $wpdb->prepare( "
			        SELECT COUNT(pm.meta_id) FROM {$wpdb->postmeta} pm
			        LEFT JOIN {$wpdb->posts} p ON p.ID = pm.post_id
			        WHERE pm.meta_key = '%s' 
			        AND p.post_type = '%s'
			    ", '_amzASIN', 'product' ) );
				
				if( is_array($product_count) && count($product_count) > 0 ) {
					$url .= '&product_count=' . end($product_count);
				}
			}
	
			return $url;
		}
		
		/**
		 * Get link to newest product version
		 *
		 * @return mixed|string|WP_Error
		 */
		public function preUpgradeFilter( $reply, $package, $updater ) {
			$condition = isset( $updater->skin->theme_info ) && $updater->skin->theme_info['Name'] === $this->product_data['Name'];
			if ( ! $condition ) {
				return $reply;
			}
			
			$res = $updater->fs_connect( array( WP_CONTENT_DIR ) );
			if ( ! $res ) {
				return new WP_Error( 'no_credentials', __( "Error! Can't connect to filesystem", 'woozone' ) );
			}
			
			$updater->strings['downloading_package_url'] = __( 'Getting download link...', 'woozone' );
			$updater->skin->feedback( 'downloading_package_url' );
	
			$response = $this->getDownloadUrl();
			
			if ( ! $response ) {
				return new WP_Error( 'no_credentials', __( 'Download link could not be retrieved', 'woozone' ) );
			}
	
			if ( ! $response['status'] ) {
				return new WP_Error( 'no_credentials', $response['error'] );
			}
			
			if( $response['status'] == 'invalid' ) {
				return new WP_Error( 'no_credentials', $response['html'] );
			}
			
			$updater->strings['downloading_package'] = __( 'Downloading package...', 'woozone' );
			$updater->skin->feedback( 'downloading_package' );
	
			$downloaded_archive = download_url( $response['url'] );
			if ( is_wp_error( $downloaded_archive ) ) {
				return $downloaded_archive;
			}
	
			$plugin_directory_name = dirname( $this->product_slug );
	
			// WP will use same name for plugin directory as archive name, so we have to rename it
			if ( basename( $downloaded_archive, '.zip' ) !== $plugin_directory_name ) {
				$new_archive_name = dirname( $downloaded_archive ) . '/' . $plugin_directory_name . time() . '.zip';
				if ( rename( $downloaded_archive, $new_archive_name ) ) {
					$downloaded_archive = $new_archive_name;
				}
			}
	
			return $downloaded_archive;
		}

		/**
		 * Add our self-hosted autoupdate plugin to the filter transient
		 *
		 * @param $transient
		 *
		 * @return object $ transient
		 */
		public function check_update( $transient ) {
            $theme_slug = get_template(); 
			// Extra check for 3rd plugins
			if ( isset( $transient->response[ $this->product_path ] ) ) {
				return $transient;
			}
			
			// Get the remote version
			$remote_version = $this->getRemote_version();  
			// If a newer version is available, add the update
			if ( version_compare( $this->current_version, $remote_version, '<' ) ) {
				//$obj = new stdClass();
				//$obj->slug = $this->product_slug;
				$transient->response[ "$theme_slug" ] = array(
					'new_version' => $remote_version,
					'url' => $this->update_url . '/changelog' . ( isset($this->updater_dev) ? $this->updater_dev : '' ) . '.html',
					'package' => $this->product_slug . '.zip',
				);
			}

			return $transient;
		}
		
		/**
		 * Add our self-hosted description/changelog to the filter
		 *
		 * @param bool $false
		 * @param array $action
		 * @param object $arg
		 *
		 * @return bool|object
		 */
		public function check_info($false, $action, $arg ) {
			if ( isset( $arg->slug ) && $arg->slug === $this->product_slug ) {
				$changelog = $this->getRemote_information();
				
				$array_pattern = array(
					'/^([\*\s])*(\d\d\.\d\d\.\d\d\d\d[^\n]*)/m',
					'/^\n+|^[\t\s]*\n+/m',
					'/\n/',
				);
				$array_replace = array(
					'<div>&nbsp;</div><strong>$2</strong>',
					'</div><div>',
					'</div><div>',
				);
			
				$changelog->name = $this->title;
				$changelog->sections = (array) $changelog->sections;
				$changelog->sections['changelog'] = '<div>' . preg_replace( $array_pattern, $array_replace, $changelog->sections['changelog'] ) . '</div>';
				
				return $changelog;
			}
	
			return $false;
		}

		public function theme_api_call($def, $action, $args)
        {
            if (!is_object($args) || !isset($args->slug) || $args->slug != $this->slug)
                return false;


            //$args->package_type = $this->package_type;

            $request_string = $this->prepare_request($action, $args);
            if($request_string === FALSE)
            return new WP_Error('theme_api_failed', __('An error occour when try to identify the theme.' , 'apto') . '</p> <p><a href="?" onclick="document.location.reload(); return false;">'. __( 'Try again', 'apto' ) .'</a>');;

            $request_uri = $this->api_url . '?' . http_build_query( $request_string , '', '&');
            $data = wp_remote_get( $request_uri );

            if(is_wp_error( $data ) || $data['response']['code'] != 200)
            return new WP_Error('theme_api_failed', __('An Unexpected HTTP Error occurred during the API request.' , 'apto') . '</p> <p><a href="?" onclick="document.location.reload(); return false;">'. __( 'Try again', 'apto' ) .'</a>', $data->get_error_message());

            $response_block = json_decode($data['body']);
            //retrieve the last message within the $response_block
            $response_block = $response_block[count($response_block) - 1];
            $response = $response_block->message;

            if (is_object($response) && !empty($response)) // Feed the update data into WP updater
                {
                    //include slug and theme data
                    $response->theme = $this->slug;

                    return $response;
                }
        }
	
		/**
		 * Return the remote version
		 *
		 * @return string $remote_version
		 */
		public function getRemote_version() {
			$request = wp_remote_get( $this->update_url . '/latest' . ( isset($this->updater_dev) ? $this->updater_dev : '' ) ); 
			if ( ! is_wp_error( $request ) || wp_remote_retrieve_response_code( $request ) === 200 ) {
				return $request['body'];
			}
	
			return false;
		}
	
		/**
		 * Get information about the remote version
		 *
		 * @return bool|object
		 */
		public function getRemote_information() {
			$request = wp_remote_get( $this->update_url . '/changelog' . ( isset($this->updater_dev) ? $this->updater_dev : '' ) . '.json' );
			
			if ( ! is_wp_error( $request ) || wp_remote_retrieve_response_code( $request ) === 200 ) {
				return json_decode( $request['body'] );
			}
	
			return false;
		}
	}
}