<?php

namespace Asylum\Update\Update;

class Theme
{
    private $api = 'https://api.asylum.london';
    private $theme;
    private $version;
    private $name;
    private $apiUrl;
    private $key;
    protected $dev = false;

    protected static $checked = [];

    public function __construct($key = null, $dev = false)
    {
        if (($_ENV['APP_ENV'] ?? false) === 'local') {
            return;
        }

        $this->key = $key;
        $this->dev = $dev;
        $this->setThemeData();
    }


    private function setThemeData()
    {

        add_filter('pre_set_site_transient_update_themes', [$this, 'checkUpdate']);

        $this->theme = get_option('template');
        $this->version = wp_get_theme($this->theme)->Version;
        $this->name = wp_get_theme($this->theme)->Name;
    }

    private function setApiUrl()
    {
        $params = [
            'key' => $this->key,
            'dev' => $this->dev,
        ];
        $this->apiUrl = add_query_arg(array_filter($params), sprintf('%s/theme/%s/latest', $this->api, $this->theme));

    }

    public function checkUpdate($transient)
    {
        if (in_array($this->theme, self::$checked)) {
            // return $transient;
        }

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

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

        if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) {
            return $transient;
        }

        $body = json_decode(wp_remote_retrieve_body($response), true);


        if (empty($body)) {
            return $transient;
        }


        if (version_compare($this->version, $body['version'], '<')) {
            $transient->response[$this->theme] = [
                'new_version' => $body['version'],
                'package' => $body['url'],
                'url' => '',
            ];
        } else {
            // No update is available.
            $item = [
                'theme'        => $this->theme,
                'new_version'  => $this->version,
                'url'          => '',
                'package'      => '',
                'requires'     => '',
                'requires_php' => '',
            ];
            // Adding the "mock" item to the `no_update` property is required
            // for the enable/disable auto-updates links to correctly appear in UI.
            $transient->no_update['my-theme'] = $item;
        }


        return $transient;
    }
}
