<?php
namespace GPLoker\Inc;

class Updater {

	private $server_api = 'https://zaferinadigital.com/update/theme/gplokerpro';
	private $name = 'gplokerpro';
	private $current_version;

	public function __construct() {

		$current_theme = wp_get_theme();
		$this->current_version = $current_theme->get('Version');
		add_filter( 'pre_set_site_transient_update_themes', [$this, 'update'] );
	}

	public function fetch() {
		$response = wp_remote_get( $this->server_api . '/update-' . $this->name . '.php' );

		if ( is_array( $response ) && ! is_wp_error( $response ) ) {
			$object_response = json_decode( $response['body'], true );

			if ( json_last_error() === JSON_ERROR_NONE ) {
				return $object_response;
			}
		}

		return [];
	}

	public function update( $transient ) {

		$item = array(
			'theme'        => $this->name,
			'new_version'  => $this->current_version,
			'url'          => '',
			'package'      => '',
			'requires'     => '',
			'requires_php' => '',
		);


		$update = $this->fetch();

		if ( $update ) {

			if ( version_compare($this->current_version, $update['new_version'], '<') ) {
				$transient->response[$this->name] = $update;
			} else {
				// set to no update available
				$transient->no_update[$this->name] = $item;
			}

		}

		return $transient;
	}
}

new Updater();