<?php
if ( ! class_exists( 'IOWP_AutoUpdate' ) ) {

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

        /**
         * The plugin remote update path
         * @var string
         */
        private $update_path;

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

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

        /**
         * License User
         * @var string
         */
        private $license_user;

        /**
         * License Key
         * @var string
         */
        private $license_key;

        /**
         * Initialize a new instance of the WordPress Auto-Update class
         * @param string $current_version
         * @param string $update_path
         * @param string $plugin_slug
         */

        // Perform additional actions to successfully install our plugin
        /*public function postInstall($true, $hook_extra, $result)
        {
            sc_setup();
            flush_rewrite_rules();//force permalink refresh which is needed due to api update
            return $result;
        }*/

        public function __construct($current_version, $update_path, $plugin_slug, $license_user = '', $license_key = '')
        {
            // Set the class public variables
            $this->current_version = $current_version;
            $this->update_path = $update_path;

            // Set the License
            $this->license_user = $license_user;
            $this->license_key = $license_key;

            // Set the Plugin Slug
            $this->plugin_slug = $plugin_slug;
            list ($t1, $t2) = explode('/', $plugin_slug);
            $this->slug = str_replace('.php', '', $t2);
            //$this->slug = $plugin_slug;

            /*
             * got the following error when updating a theme. turns out it doesn't run when upgrading the actual plugin, but will probably run w/ every other ugprade
             * Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'postInstall' not found or invalid function name in /home/demorent/public_html/test/wp-includes/class-wp-hook.php on line 298
             */
            //add_filter( "upgrader_post_install", array($this,"postInstall"), 10, 3 );

            // define the alternative API for updating checking
            add_filter('pre_set_site_transient_update_plugins', array($this, 'check_update'));
            //set_site_transient('update_plugins', null);//enable this to test update call (on plugin activate)

            // 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 $transient
         * @return object $ transient
         */
        public function check_update($transient)
        {
            if (empty($transient->checked)) {
                return $transient;   // also have to remove this one to test update call
            }

            // 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->new_version, '<')) {
                $obj = new stdClass();
                $obj->slug = $this->slug;
                $obj->new_version = $remote_version->new_version;
                $obj->url = $remote_version->url;
                $obj->plugin = $this->plugin_slug;
                $obj->package = $remote_version->package;
                $obj->tested = $remote_version->tested;
                $transient->response[$this->plugin_slug] = $obj;
            }
            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($obj, $action, $arg)
        {
            //return $this->getRemote('info');
            if (($action == 'query_plugins' || $action == 'plugin_information') &&
                isset($arg->slug) && $arg->slug === $this->slug
            ) {
                return $this->getRemote('info');
            }

            return $obj;
        }

        /**
         * Return the remote version
         *
         * @return string $remote_version
         */
        public function getRemote($action = '')
        {
            $params = array(
                'body' => array(
                    'action' => $action,
                    'license_user' => $this->license_user,
                    'license_key' => $this->license_key,
                ),
            );

            // Make the POST request
            $request = wp_remote_post($this->update_path, $params);

            // Check if response is valid
            if (!is_wp_error($request) || wp_remote_retrieve_response_code($request) === 200) {
                return @unserialize($request['body']);
            }

            return false;
        }
    }
}