<?php
/**
 * Theme update checker.
 *
 * @package EasySite_Pro
 */

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

/**
 * Check remote for theme updates.
 *
 * @param object $transient Update transient.
 * @return object
 */
function easysite_check_theme_update( $transient ) {
	if ( empty( $transient->checked ) ) {
		return $transient;
	}

	$remote_url = apply_filters( 'easysite_update_url', '' );
	if ( ! $remote_url ) {
		return $transient;
	}

	$response = wp_remote_get( $remote_url, array( 'timeout' => 10 ) );
	if ( is_wp_error( $response ) ) {
		return $transient;
	}

	$data = json_decode( wp_remote_retrieve_body( $response ), true );
	if ( empty( $data['version'] ) || empty( $data['download_url'] ) ) {
		return $transient;
	}

	if ( version_compare( EASYSITE_PRO_VERSION, $data['version'], '<' ) ) {
		$theme_slug = get_template();
		$transient->response[ $theme_slug ] = array(
			'theme'       => $theme_slug,
			'new_version' => $data['version'],
			'url'         => isset( $data['homepage'] ) ? $data['homepage'] : '',
			'package'     => $data['download_url'],
		);
	}

	return $transient;
}
add_filter( 'pre_set_site_transient_update_themes', 'easysite_check_theme_update' );

/**
 * Show update notice on EasySite Setup.
 */
function easysite_update_notice() {
	$screen = get_current_screen();
	if ( ! $screen || strpos( $screen->id, 'easysite' ) === false ) {
		return;
	}
	$updates = get_site_transient( 'update_themes' );
	$theme   = get_template();
	if ( empty( $updates->response[ $theme ] ) ) {
		return;
	}
	$new = $updates->response[ $theme ]['new_version'];
	echo '<div class="notice notice-info"><p>' . esc_html( sprintf( __( 'EasySite Pro %s is available. Update via Appearance → Themes.', 'easysite-pro' ), $new ) ) . '</p></div>';
}
add_action( 'admin_notices', 'easysite_update_notice' );
