<?php

if(!defined('ABSPATH')) die('-1');

class AwesomeLiveChat_Updater extends AwesomeLiveChat
{
    /**
     * Boots object
     *
     * @since  1.0.0
     * @access private
     * @var object
     */
    private $Boots;

    /**
     * Settings/Options
     *
     * @since  1.0.0
     * @access private
     * @var array
     */
    private $Options;

    /**
     * Library
     *
     * @since  1.0.0
     * @access private
     * @var object
     */
    private $_;

    /**
     * API URL
     *
     * @since  1.0.0
     * @access private
     * @var string
     */
    private $api_url;

    /**
     * Plugin Slug
     *
     * @since  1.0.0
     * @access private
     * @var string
     */
    private $plugin_slug;

    /**
     * Plugin version
     *
     * @since  1.0.0
     * @access private
     * @var string
     */
    private $plugin_version;

    /**
     * WP Version
     *
     * @since  1.0.0
     * @access private
     * @var string
     */
    private $wp_version;

    /**
     * Site URL
     *
     * @since  1.0.0
     * @access private
     * @var string
     */
    private $site_url;

    /**
     * Key
     *
     * @since  1.0.0
     * @access private
     * @var string
     */
    private $key;

    /**
     * Verified?
     *
     * @since  1.0.0
     * @access private
     * @var bool
     */
    private $verified;

    /**
     * Get the Boots framework object.
     * Get the plugin settings.
     * Get the plugin library.
     * Get notifier api url.
     * Get plugin slug.
     * Get wp version.
     * Get site url.
     * Set key.
     *
     * @since  1.0.0
     * @uses   AwesomeLiveChat::boots()
     *         return boots object
     * @uses   AwesomeLiveChat::options()
     *         return options
     * @uses   AwesomeLiveChat_Library
     *         plugin library/helper
     * @access public
     * @param  void
     * @return void
     */
    public function __construct()
    {
        $this->Boots   = $this->boots();
        $this->Options = $this->options();
        $this->_       = new AwesomeLiveChat_Library();

        $this->api_url     = $this->Options['NOTIFIER_URL'];
        //basename($this->Options['APP_DIR']);
        $this->plugin_slug = $this->Options['APP_ID'];
        $this->plugin_version = $this->Options['APP_VERSION'];
        $this->wp_version  = $this->Options['WP_VERSION'];
        $this->site_url    = $this->Options['WP_SITE_URL'];
        $this->key = $this->plugin_slug . '/' . $this->Options['APP_FILE'];

        /*add_filter(
            'pre_set_site_transient_update_plugins',
            array($this, 'check4update')
        );
        add_filter('plugins_api', array($this, 'api_call'), 10, 3);*/

        // Notify verification
        /*
        $License = $this->Boots->Database
        ->term('alc_license', array())
        ->get();
        if(!$License || !isset($License['verified']) || !$License['verified'])
            add_action('admin_notices', array($this, 'notice'));
        */
        // Verify plugin
        add_filter('awesome_live_chat_verify', array($this, 'verify'));
        // Unverify plugin
        add_action('awesome_live_chat_unverify', array($this, 'unverify'));
        // About externals
        // $this->about();
    }

    private function prepare($args = array())
    {
        return array(
            'body' => array_merge(array(
                'r'       => $this->site_url,
                'version' => $this->plugin_version
            ), $args),
            'user-agent' => 'WordPress/'. $this->wp_version .'; '. $this->site_url
        );
    }

    private function about()
    {
        $response = get_transient('awesome_live_chat_about');
        if($response !== false) return $response;
        $request = $this->prepare();
        $raw_response = wp_remote_get($this->api_url . '/promotions', $request);
        if(!is_wp_error($raw_response) && ($raw_response['response']['code'] == 200))
            $response = json_decode($raw_response['body'], true);
        else $response = array();
        // Avoid XSS Attacks!
        array_walk_recursive($response, array($this, 'strip'));
        set_transient('awesome_live_chat_about', $response, 60 * 60 * 24);
        return $response;
    }

    public function strip(& $item, $key)
    {
        $item = strip_tags($item, '<div><span><h1><h2><h3><p><ul><li><a><img>');
    }

    public function notice()
    {
        $page = $this->Options['WP_ADMIN_URL'] . '/admin.php?page=awesome_live_chat_admin#About';
        ?>
        <div class="notice notice-error is-dismissible">
            <p><?php echo sprintf(__('Whoops! Could not verify your purchase key for %s. Please provide <a href="%s">your purchase key here.</a>', 'awesome-live-chat'), 'Awesome Live Chat', $page); ?></p>
        </div>
        <?php
    }

    public function verify($key)
    {
        $request = $this->prepare();
        $raw_response = wp_remote_get($this->api_url . '/verify:' . $key . '/?token=' . $this->site_url . '&r=' . $this->site_url, $request);
        if(!is_wp_error($raw_response) && ($raw_response['response']['code'] == 200))
            $response = json_decode($raw_response['body'], true);
        else $response = false;
        return $response == 'true';
    }

    public function unverify($key)
    {
        $request = $this->prepare();
        $raw_response = wp_remote_get($this->api_url . '/unverify:' . $key, $request);
        if(!is_wp_error($raw_response) && ($raw_response['response']['code'] == 200))
            $response = json_decode($raw_response['body'], true);
        else $response = false;
        return $response;
    }

    public function check4update($transient)
    {
        if(empty($transient->checked)) return $transient;

        # envato specific

        $this->plugin_version = $transient->checked[$this->key];

        $request = $this->prepare('basic_check');
        $raw_response = wp_remote_post($this->api_url, $request);
        $response = null;

        if(!is_wp_error($raw_response) && ($raw_response['response']['code'] == 200))
        $response = unserialize($raw_response['body']);

        if(!empty($response)) $transient->response[$this->key] = $response;

        return $transient;
    }

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

        $plugin_info     = get_site_transient('update_plugins');
        $current_version = $plugin_info->checked[$this->key];
        $args->version   = $current_version;

        $request = $this->prepare($action);
        $raw_response = wp_remote_post($this->api_url, $request);

        if(is_wp_error($raw_response))
        {
            $response = new WP_Error('plugins_api_failed', __('An Unexpected HTTP Error occurred during the API request.', 'awesome-live-chat') . '</p><p><a href="?" onclick="document.location.reload(); return false;">' . __('Try again', 'awesome-live-chat') . '</a>', $raw_response->get_error_message());
        }
        else
        {
            $response = unserialize($raw_response['body']);
            if($response === false)
            $response = new WP_Error('plugins_api_failed', __('An unknown error occurred', 'awesome-live-chat'), $raw_response['body']);
        }

        return $response;
    }
}
new AwesomeLiveChat_Updater();
