<?php

namespace Asylum\Update\Update;

use Asylum\Update\Interfaces\PluginInterface;

class Plugin implements PluginInterface
{
    private $apiUrl;

    private $apiPassword = '';

    private $pluginVersion;

    private $pluginPath = '';

    private $pluginUrl = '';

    private $plugin;

    private $protected;

    private $dev;

    private static $called = false;

    public function __construct($plugin, $path, $url, $dev = false, $key = '')
    {
        $this->pluginPath = $path;
        $this->pluginUrl = $url;
        $this->plugin = $plugin;
        $this->apiPassword = $key;
        $this->dev = $dev;

        error_log('init');

        add_filter('pre_set_site_transient_update_plugins', [$this, 'displayTransientUpdate']);
        add_filter('plugins_api', [$this, 'updateDetails'], 10, 3);
    }

    public function setApiUrl()
    {
        $params = [
            'key' => $this->apiPassword,
            'dev' => $this->dev,
        ];

        $this->apiUrl = add_query_arg(array_filter($params), sprintf('https://api.asylum.london/plugin/%s/latest', $this->plugin));
    }

    public function setPluginVersion()
    {
        $plugin = get_plugin_data($this->pluginPath . '/' . $this->plugin . '.php');
        $this->pluginVersion = $plugin['Version'];
    }

    public function displayTransientUpdate($transient)
    {

        if (self::$called) {
            return $transient;
        }

        $this->setApiUrl();

        if (!$this->apiUrl) {
            return $transient;
        }

        // $api = add_query_arg('forcePassword', $this->apiPassword, $this->apiUrl);

        $response = wp_remote_get($this->apiUrl);

        error_log($this->apiUrl);
        $data = json_decode(wp_remote_retrieve_body($response), true);

        if (is_wp_error($response)) {
            return $transient;
        }

        $this->setPluginVersion();


        if (!isset($data['latest_version'])) {
            return $transient;
        }

        $result = $data['latest_version'];

        $updateVersion = $result;

        $key = sprintf('%s/%s.php', $this->plugin, $this->plugin);
        /* Latest Release Update */

        if (version_compare($this->pluginVersion, $updateVersion, '<')) {
            $transient->response[$key] = $this->transientObject($data);
            return $transient;
        }

        /* Specific Version Update */
        // if (version_compare($this->pluginVersion, $updateVersion, '!=')) {
        //     $transient->response[$key] = $this->transientObject($data);
        //     return $transient;
        // }

        return $transient;
    }

    public function transientObject($data)
    {
        $updateVersion = $data['latest_version'];

        $package = $data['package'];

        if ($this->protected) {
            $package = add_query_arg(
                [
                    'forcePass' => $this->apiPassword
                ],
                $package
            );
        }

        $response = new \stdClass();
        $response->slug = $data['slug'];
        $response->new_version = $updateVersion;
        $response->url = $data['url'];
        $response->package = $package;
        $response->icons = [
            '2x' => $this->pluginUrl . '/dist/img/thumbnail-256x256.png',
            '1x' => $this->pluginUrl . '/dist/img/thumbnail-128x128.png'
        ];
        $response->tested = $data['tested'] ?? false;
        $response->extra = $data;
        return $response;
    }

    public function updateDetails($res, $action, $args)
    {
        if ($action === 'plugin_information') {
            if (isset($args->slug) && $args->slug === basename($this->pluginPath)) {
                $data = get_site_transient('update_plugins');
                $update = $data->response[$args->slug . '/' . $args->slug . '.php'] ?? [];
                $plugin = get_plugin_data(trailingslashit(WP_PLUGIN_DIR) . $args->slug . '/' . $args->slug . '.php');

                if ($update) {
                    error_log('API CALL!');
                }

                $res = new \stdClass;

                $res->name = $plugin['Name'];
                $res->version = $update->extra['latest_version'];
                $res->slug = $update->slug;
                $res->download_link = $update->package;
                $res->tested = $update->extra['tested'];
                $res->requires = $update->extra['requires'];

                $res->requires_php = $update->extra['requires_php'];

                $res->last_updated = $update->extra['date'] ?? '';
                $res->homepage = $update->url;

                $res->sections = [
                    'description' => $plugin['Description'],
                    // 'installation' => '<ul><li>Upload plugin</li></ul>',
                    // 'faq' => '',
                    // 'screenshots' => '',
                ];

                $res->banners = [
                    'low' => $this->pluginUrl . '/dist/img/banner-772x250.png',
                    'high' => $this->pluginUrl . '/dist/img/banner-772x250.png'
                ];

                $res->external = true;

                // Add change log tab if the server sent it
                if (isset($data->extra['changelog'])) {
                    $res->sections['changelog'] = $data->extra['changelog'];
                }

                return $res;
            }
        }
        return $res;
    }
}
