<?php

namespace wpbuddy\rich_snippets\pro;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
} // Exit if accessed directly


/**
 * Class Update Controller.
 *
 * Performs plugin updates.
 *
 * @package wpbuddy\rich_snippets
 *
 * @since   2.0.0
 */
final class Update_Controller {


	/**
	 * Update check the WordPress way.
	 *
	 * @param $toUpdate
	 * @param $pluginData
	 *
	 * @return array|false|mixed
	 * @since 2.30.4
	 */
	public static function check_plugin_update( $toUpdate, $pluginData ) {
		static $update_info = null;
		static $update_check = 0;

		if ( $toUpdate ) {
			return $toUpdate;
		}

		if ( ! $update_check ) {
			$update_check = (int) get_option( 'wpb_rs/update-check', 0 );
		}

		if ( array_key_exists( 'force-check', $_GET ) && $_GET['force-check'] === '1' ) {
			$update_check = 0;
		}

		# Do not check for updates more than once a week.
		if ( $update_check > time() ) {
			return $toUpdate;
		}

		if ( false === stripos( $pluginData['UpdateURI'], 'rich-snippets.io' ) ) {
			return $toUpdate;
		}

		if ( ! $update_info ) {

			$pc = get_option( 'wpb_rs/purchase_code', '' );

			$matched = preg_match( '#[\w\d]{8}-(?:[\w\d]{4}-){3}[\w\d]{12}#', $pc );

			if ( 1 === $matched ) {
				add_filter( 'http_request_args', array( 'wpbuddy\rich_snippets\WPBuddy_Model', 'request_args' ) );
			}

			$response = wp_remote_get( $pluginData['UpdateURI'] );

			update_option( 'wpb_rs/update-check', time() + WEEK_IN_SECONDS, true );

			if ( 1 === $matched ) {
				remove_filter( 'http_request_args', array( 'wpbuddy\rich_snippets\WPBuddy_Model', 'request_args' ) );
			}

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

			$body = wp_remote_retrieve_body( $response );

			try {
				$update_info = json_decode( $body, true, 512, JSON_THROW_ON_ERROR );
			} catch ( \Exception $e ) {
				return false;
			}
		}

		if ( ! version_compare( $update_info['version'], $pluginData['Version'], '>' ) ) {
			return false;
		}

		$update_info['id']   = $pluginData['UpdateURI'];
		$update_info['slug'] = plugin_basename( WPB_RS_FILE );

		return $update_info;
	}

}
