<?php
namespace ONLINE_ADAv4\Services;

use ONLINE_ADAv4\Plugin AS Plugin;
use ONLINE_ADAv4\Services\License;

class Updater {
    
    use \ONLINE_ADAv4\Traits\Singleton;

    private $transient = "";

    public function __construct(){

        add_action( 'plugins_loaded', [$this, "init"]);
        
        add_filter('site_transient_update_plugins', [$this, 'update_plugin'] );

        add_action( 'upgrader_process_complete', [$this, 'upgrader_complete'], 10, 2 );

        add_action( 'core_upgrade_preamble', [$this, 'clear_transient']);
    }

    public function init(){

        $this->transient = "plugin_upgrade_" . Plugin::instance()->info['name'];

    }

    public function update_plugin($transient){

        if( false == $response = get_transient( $this->transient ) ) {

            $api_url = trailingslashit(Plugin::instance()->info['license_url']) . 'wp-json/limelight-checkout/v1/product_info';

            $remote = wp_remote_post($api_url, [
                'method' => "POST",
                'headers' => [
                    'Content-Type' => 'application/x-www-form-urlencoded'
                ],
                'body' => Plugin::instance()->info,
                'data_format' => 'body',
                'timeout' => 15
            ]);
            
            $code = wp_remote_retrieve_response_code( $remote );
    
            if ( !is_wp_error( $remote ) && $code == 200 ) {
                
                $response = json_decode(wp_remote_retrieve_body( $remote ), true);

                set_transient( $this->transient, $response, 43200 );
                
            }else{

                set_transient( $this->transient, true, 43200 );

            }
    
        }
    
        if( $response ) {

            if($response['status'] != 'OK') return $transient;

            if( version_compare( Plugin::instance()->info['version'], $response['version'], '<' ) ) {
                
                $res = new \stdClass();
                $res->slug = Plugin::instance()->info['name'];
                $res->plugin = Plugin::instance()->info['name'] . '/index.php';
                $res->new_version = $response['version'];
                $res->package = $response['download_url'];
                $transient->response[$res->plugin] = $res;

            }
    
        }

        return $transient;

    }
    public function upgrader_complete($updgrader_object, $options){

        if ( $options['action'] == 'update' && $options['type'] === 'plugin' )  {

            delete_transient( $this->transient );

        }

    }

    public function clear_transient(){

        delete_transient($this->transient);

    }
}