<?php

class DXWPAutoUpdater
{
    private $cache_key;
    private $cache_allowed;
    private $transientCacheTimeInMinutes;

    public function __construct()
    {
        $this->cache_key = 'dance_x_transient_key';
        $this->cache_allowed = false;
        $this->transientCacheTimeInMinutes = 10;

        add_filter('plugins_api', array($this, 'adapt_plugin_view_details'), 20, 3);
        add_filter('site_transient_update_plugins', array($this, 'check_for_plugin_update'));
        add_action('upgrader_process_complete', array($this, 'purgeTransient'), 10, 2);

        add_filter('plugin_row_meta', array($this, 'change_plugin_action_links'), 10, 4);
    }

    function change_plugin_action_links($plugin_meta, $plugin_file, $plugin_data, $status)
    {
        if (DANCE_X_PLUGIN_FOLDER_AND_SLUG === $plugin_file) {

            //das heisst es gibt gerade kein Update -> nur dann den selbstgebauten "View Details"-Link beim Plugin anzeigen
            if (!array_key_exists('update', $plugin_data)) {

                $customViewDetailsLink = admin_url('plugin-install.php?tab=plugin-information&plugin=' . DANCE_X_PLUGIN_SLUG . '&TB_iframe=true');
                $plugin_meta[] = '<a class="thickbox open-plugin-details-modal" href="' . $customViewDetailsLink . '">View Details</a>';
            }
        }

        return $plugin_meta;
    }

    function check_for_plugin_update($transient)
    {
        if (empty($transient->checked)) {
            return $transient;
        }

        $remote = $this->getRemoteVersionInfo();
        if ($remote == false) {
            error_log("Could not get Remote-Version on PUS-Server (while processing 'check_for_plugin_update')!");
            return $transient;
        }

        $pluginData = DXUtil::getPluginData();
        $current_version = $pluginData['Version'];

        //if there is a newer version on the server
        //maybe add more logic and checks here -> check PHP version and WP-Version - but for now this is okay
        if (version_compare($current_version, $remote->version, '<')) {

            $res = new stdClass();

            $res->slug = DANCE_X_PLUGIN_SLUG;               // dance-x-connector
            $res->plugin = DANCE_X_PLUGIN_FOLDER_AND_SLUG;  // dance-x-connector/dance-x-connector.php
            $res->new_version = $remote->version;
            $res->tested = $remote->tested;
            $res->package = $remote->download_url;

            $transient->response[$res->plugin] = $res;
        }

        return $transient;
    }

    function adapt_plugin_view_details($res, $action, $args)
    {
        // do nothing if you're not getting plugin information right now
        if ('plugin_information' !== $action) {
            return $res;
        }

        // do nothing if it is not our plugin
        if (DANCE_X_PLUGIN_SLUG !== $args->slug) {
            return $res;
        }

        // get updates
        $remote = $this->getRemoteVersionInfo();
        if ($remote == false) {
            error_log("Could not get Remote-Version on PUS-Server (while processing 'adapt_plugin_view_details')!");
            return $res;
        }

        if (!$remote) {
            return $res;
        }

        $res = new stdClass();

        $res->name = $remote->name;
        $res->slug = $remote->slug;

        $res->version = $remote->version;
        $res->tested = $remote->tested;
        $res->requires = $remote->requires;
        $res->author = $remote->author;
        $res->download_link = $remote->download_url;
        $res->trunk = $remote->download_url;
        $res->requires_php = $remote->requires_php;
        $res->last_updated = $remote->last_updated;

        $res->sections = array(
            'description' => $remote->sections->description,
            'installation' => $remote->sections->installation,
            'changelog' => $remote->sections->changelog
        );

        if (!empty($remote->banners)) {
            $res->banners = array(
                'low' => $remote->banners->low,
                'high' => $remote->banners->high
            );
        }

        return $res;
    }

    function purgeTransient($upgrader, $options)
    {

        if (
            $this->cache_allowed
            && 'update' === $options['action']
            && 'plugin' === $options['type']
        ) {
            // just clean the cache when new plugin version is installed
            delete_transient($this->cache_key);
        }
    }

    function getRemoteVersionInfo(): bool | object
    {
        $response = get_transient($this->cache_key);

        if (false === $response || !$this->cache_allowed) {

            $request_args = array(
                'headers'   => array(
                    'Content-Type' => 'application/json',
                    //at least some secret for basic-security (no crazy security here!)
                    'X_API_KEY' => '138dd658-991e-44b4-b231-49e4d3beab96'
                )
            );

            $updateUri = DXUtil::getPluginData()['UpdateURI'];

            $response = wp_remote_get($updateUri, $request_args);

            if (is_wp_error($response))
                return false;

            $http_code = wp_remote_retrieve_response_code($response);
            if ($http_code != 200)
                return false;

            set_transient($this->cache_key, $response, $this->transientCacheTimeInMinutes * MINUTE_IN_SECONDS);
        }

        $body = wp_remote_retrieve_body($response);
        $jsonAsArr = json_decode($body);

        return $jsonAsArr;
    }
}

$dxWPAutoUpdater = new DXWPAutoUpdater();
