<?php
/**
 * This class checkes and notifies the user if there is a new version of theme available
 *
 * 
 * @package    auxin
 * @author     averta (c) 2010-2016
 * @link       http://averta.net

*/

// no direct access allowed
if ( ! defined('ABSPATH') ) {
    die();
}

if( class_exists('auxin_Theme_Check_Update') ){
    return;
}


class Auxin_Theme_Check_Update
{
    /**
     * The theme current version
     * @var string
     */
    public $current_version;

    /**
     * The theme remote update path
     * @var string
     */
    public $update_path;

    /**
     * Theme Slug (theme_directory/theme_file.php)
     * @var string
     */
    public $template;

    /**
     * The item name while requesting to update api
     * @var string
     */
    public $request_name;

    /**
     * The item ID in marketplace
     * @var string
     */
    public $theme_id;

    /**
     * The item name while requesting to update api
     * @var string
     */
    public $banners;


    /**
     * Initialize a new instance of the WordPress Auto-Update class
     * @param string $current_version
     * @param string $update_path
     * @param string $template
     * @param string $slug
     */
    function __construct( $current_version, $update_path, $template, $slug, $item_request_name = '' ) {
        // Set the class public variables
        $this->current_version  = $current_version;
        $this->update_path      = $update_path;
        $this->template         = $template;
        $this->slug             = $slug;

        $this->request_name     = empty( $item_request_name ) ? $this->slug : $item_request_name;

        // define the alternative API for updating checking
        add_filter( 'pre_set_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 our self-hosted autoupdate theme to the filter transient
     *
     * @param $transient
     * @return object $ transient
     */
    public function check_update( $transient ) {

        if( apply_filters( 'auxin_disable_theme_auto_update', 0 ) )
            return $transient;

        // Get the remote version
        $remote_version = $this->get_remote_version();

        // echo '<pre>';
        // $isl = version_compare( $this->current_version, $remote_version, '<' );
        // echo 'current is less than remote? : ' . $this->current_version .' < '. $remote_version;
        // var_dump( $isl );
        // echo '</pre>';

        $theme_data = wp_get_theme();

        // If a newer version is available, add the update info to update transient
        if ( version_compare( $this->current_version, $remote_version, '<' ) ) {
            $template_reponse = array();
            $template_reponse['slug']      = $this->slug;
            $template_reponse['theme']     = $this->template;
            $template_reponse['new_version'] = $remote_version;
            $template_reponse['url']       = $theme_data->ThemeURI;
            $template_reponse['package']   = '';
            $transient->response[ $this->template ] = $template_reponse;

        } elseif ( isset( $transient->response[ $this->template ] ) ) {
            unset( $transient->response[ $this->template ] );
        }

        return $transient;
    }


    /**
     * Return the remote version
     * @return string $remote_version
     */
    public function get_remote_version() {
        global $wp_version;

        $theme_data = wp_get_theme();

        $this_theme        = $theme_data;
        $this_theme['ID']        = $this->theme_id;
        $this_theme['Slug']      = $this->slug;
        $this_theme['Activated'] = get_option( $this->slug . '_is_license_actived', 0);

        $args = array(
            'user-agent' => 'WordPress/'.$wp_version.'; '. get_site_url(),
            'timeout'    => ( ( defined('DOING_CRON') && DOING_CRON ) ? 30 : 3),
            'body' => array(
                'cat'       => 'version-check',
                'action'    => 'final',
                'item-name' => $this->request_name,
                'theme'     => $theme_data->Name
            )
        );

        $request = wp_remote_post( $this->update_path, $args );

        if ( ! is_wp_error( $request ) || wp_remote_retrieve_response_code( $request ) === 200 ) {
            return $request['body'];
        }
        return false;
    }


    /**
     * 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( apply_filters( 'auxin_disable_theme_auto_update', 0 ) )
            return $false;

        if( ! isset( $arg->slug ) )
            return $false;

        if ( $arg->slug === $this->slug ) {
            $information = $this->get_remote_information();
            return apply_filters( 'auxin_pre_insert_theme_info' . $this->slug , $information );
        }
        return $false;
    }


    /**
     * Get information about the remote version
     * @return bool|object
     */
    public function get_remote_information() {
        global $wp_version;

        $request = wp_remote_post( $this->update_path, array(
                'user-agent' => 'WordPress/'.$wp_version.'; '. get_site_url(),
                'body' => array(
                    'cat'       => 'info',
                    'action'    => 'details',
                    'item-name' => $this->request_name
                )
            )
        );

        if ( ! is_wp_error( $request ) || wp_remote_retrieve_response_code( $request ) === 200 ) {

            $theme_info_data = wp_get_theme();

            $info = maybe_unserialize( $request['body'] );
            $info->slug             = $this->slug;
            $info->theme_name       = isset( $theme_info_data['Name'] )      ? $theme_info_data['Name']      : '';
            $info->author           = isset( $theme_info_data['Author'] )    ? $theme_info_data['Author']    : '';
            $info->homepage         = isset( $theme_info_data['ThemeURI'] ) ? $theme_info_data['ThemeURI']   : '';

            $info->banners['low']   = isset( $this->banners['low']  ) ? $this->banners['low']  : '';
            $info->banners['high']  = isset( $this->banners['high'] ) ? $this->banners['high'] : '';
            // @TODO
            // $info->download_link    = msp_get_setting( 'token', 'msp_envato_license' );

            return $info;
        }
        return false;
    }

}
