<?php

namespace Sowmedia\Repo\Updaters;

/**
 * Main Sowmedia_Updatable Class
 * @author Sowmedia.nl (Steve Lock)
 */
class LegacyUpdater {

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

    /**
     * The plugin current version
     * @var string
     */
    public $current_type;

    /**
     * The WordPress current version
     * @var string
     */
    public $wp_version;

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

    /**
     * Path Slug (directory/file.ext)
     * @var string
     */
    public $index_slug;

    /**
     * Plugin or Theme slug (directory)
     * @var string
     */
    public $slug;

    /**
     * Initialize a new instance of the WordPress Auto-Update class
     * @param string $current_version
     * @param string $update_path
     * @param string $passtrough
     */
    function __construct($update_path, $passtrough)
    {


        // Set the current WordPress version
        global $wp_version;
        $this->wp_version  = $wp_version;

        // Set the class public variables
        $this->update_path = trailingslashit($update_path);

        if(is_string($passtrough)) {

            // Handle as plugin
            $this->current_type = 'plugin';
            $this->index_slug = $passtrough;
            list ($t1, $t2) = explode('/', $passtrough);
            $this->slug = $t1;

            // 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);

        } elseif (is_object($passtrough)) {

            // Handle as theme
            $this->current_type = 'theme';

            // Provide support for the old buggy situation
            if(strpos($passtrough->get( 'Name' ), '/')) {
                list ($t1, $t2) = explode('/', $passtrough->get( 'Name' ));
                $this->slug = $this->index_slug = $t1;
            } else {
                $this->slug = $this->index_slug = $passtrough->stylesheet;
            }

            // 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 plugin to the filter transient
     *
     * @param $transient
     * @return object $ transient
     */
    public function check_update($transient)
    {

        // comment this when debugging
        if (empty($transient->checked)) {
            return $transient;
        }

        // Get the current version
        $this->current_version = $transient->checked[$this->index_slug];

        // Get remote information
        $information = $this->getRemote_information();

        // If a newer version is available, add the update
        if ($information && version_compare($this->current_version, $information->new_version, '<')) {
            $obj = new \stdClass();
            $obj->slug = $this->slug;
            $obj->new_version = $information->new_version;
            $obj->url = $information->url;
            $obj->package = $information->package;

            // adapt to different update handlers in wp core
            if ($this->current_type == 'plugin') $return = $obj;
            elseif ($this->current_type == 'theme') $return = (array) $obj;

            // store result
            $transient->response[$this->index_slug] = $return;

        }

        return $transient;
    }

    /**
     * Add our self-hosted description to the filter
     *
     * @param boolean $false
     * @param array $actionw
     * @param object $args
     * @return bool|object
     */
    public function check_info($false, $action, $args)
    {
        if (isset($args->slug) && $args->slug === $this->slug) {
            $information = $this->getRemote_information();
            return $information;
        } else return $false;
    }

    /**
     * Return the remote version
     * @return string $remote_version
     */
    public function getRemote_version()
    {
        $request = wp_remote_post(
            $this->update_path, array(
                'body' => array(
                    'action' => 'version',
                    'slug' => $this->slug,
                    'api-key' => md5( get_bloginfo('url'))
                ),
                'user-agent' => 'WordPress/' . $this->wp_version . '; ' . get_bloginfo('url')
            )
        );
        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_post(
            $this->update_path, array(
                'body' => array(
                    'action' => 'info',
                    'slug' => $this->slug,
                    'api-key' => md5( get_bloginfo('url'))
                ),
                'user-agent' => 'WordPress/' . $this->wp_version . '; ' . get_bloginfo('url')
            )
        );
        if (!is_wp_error($request) || wp_remote_retrieve_response_code($request) === 200) {
            return unserialize($request['body']);
        }
        return false;
    }

    /**
     * Return the status of the plugin licensing
     * @return boolean $remote_license
     */
    public function getRemote_license()
    {
        $request = wp_remote_post(
            $this->update_path, array(
                'body' => array(
                    'action' => 'license',
                    'slug' => $this->slug,
                    'api-key' => md5( get_bloginfo('url'))
                ),
                'user-agent' => 'WordPress/' . $this->wp_version . '; ' . get_bloginfo('url')
            )
        );
        if (!is_wp_error($request) || wp_remote_retrieve_response_code($request) === 200) {
            return $request['body'];
        }
        return false;
    }
}
