<?php

namespace PixelioCartAbandonRecoveryMore\Admin\Services;





use PixelioCartAbandonRecoveryMore\Admin\Wrapper\Pixelio_Cart_Abandon_Recovery_More_Wordpress_Wrapper;
use PixelioCartAbandonRecoveryMore\Frontend\Models\Pixelio_Cart_Abandon_Recovery_More_If_Plugin_Update_Result_Model;
use PixelioCartAbandonRecoveryMore\Includes\Utils\Pixelio_Cart_Abandon_Recovery_More_Util;

if (!defined('ABSPATH')) exit;


class Pixelio_Cart_Abandon_Recovery_More_Update_Service
{
	/**
	 * WordPress abstraction layer (POST, sanitize, esc_html, etc).
	 *
	 * @var object
	 */

	/**
	 * Pixelio utility service (options + business logic).
	 *
	 * @var object
	 */
	private Pixelio_Cart_Abandon_Recovery_More_Util $pixelio_util;
	private Pixelio_Cart_Abandon_Recovery_More_Wordpress_Wrapper  $wordpress_wrapper;


	public function __construct( $pixelio_util,$wordpress_wrapper)
	{
		$this->pixelio_util = $pixelio_util;
		$this->wordpress_wrapper = $wordpress_wrapper;
	}

	public function check_for_updates(): Pixelio_Cart_Abandon_Recovery_More_If_Plugin_Update_Result_Model
	{
		$response = $this->pixelio_call_update_api();

		if (! $this->pixelio_is_valid_update_response($response)) {
			return Pixelio_Cart_Abandon_Recovery_More_If_Plugin_Update_Result_Model::pixelio_no_update();
		}

		return $this->pixelio_build_update_result($response);
	}

	private function pixelio_call_update_api()
	{
		$url = $this->pixelio_util
				->pixelio_cart_abandon_recovery_more_get_url() . 'update_available';

		return $this->pixelio_util
			->pixelio_cart_abandon_recovery_more_call_api($url);
	}

	private function pixelio_is_valid_update_response($response): bool
	{
		if ($this->wordpress_wrapper->pixelio_is_wp_error($response)) {
			return false;
		}

		if (!isset($response['updates']['current_version'])) {
			return false;
		}

		$current = (float) $response['updates']['current_version'];

		return $current > (float) Pixelio_Cart_Abandon_Recovery_More_Util::$plugin_version;
	}

	private function pixelio_build_update_result($response): Pixelio_Cart_Abandon_Recovery_More_If_Plugin_Update_Result_Model
	{
		$locale = $this->pixelio_util
			->pixelio_cart_abandon_recovery_more_get_locale();

		$lang = substr($locale, 0, 2);

		$latest_version = $response['updates']['current_version'] ?? '';
		$force = ! empty($response['updates']['force_update']);

		$current_version = Pixelio_Cart_Abandon_Recovery_More_Util::PIXELIO_CART_ABANDON_RECOVERY_MORE_VERSION;
		$changelog = $response['changelog'][$latest_version][$lang]
			?? $response['changelog'][$latest_version]['en']
			?? '';
		if (
			empty($latest_version)
			|| version_compare($latest_version, $current_version, '<=')
		) {
			return new Pixelio_Cart_Abandon_Recovery_More_If_Plugin_Update_Result_Model(
				false,
				$force,
				$changelog
			);
		}




		return new Pixelio_Cart_Abandon_Recovery_More_If_Plugin_Update_Result_Model(
			true,
			$force,
			$changelog
		);
	}

}
