<?php
namespace Pay4All\Pro\License;

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

/**
 * Private update channel for Pay4All Pro.
 *
 * Plumbs into the WP 5.8+ `update_plugins_pay4all.net` filter — the
 * hostname `pay4all.net` comes from the `Update URI` plugin header.
 * WordPress calls this filter once per plugin during the update-check
 * cycle (result is cached in the `update_plugins` site transient), so no
 * extra HTTP throttling is needed here.
 *
 * Updates stay accessible even when the subscription is expired : only
 * the paid PRO features are gated by the licence. Merchants must always
 * be able to install security fixes.
 */
final class Updater {

	public static function bootstrap() : void {
		add_filter( 'update_plugins_pay4all.net', [ self::class, 'check' ], 10, 3 );
	}

	public static function check( $update, $plugin_data, $plugin_file ) {
		// Only handle our own plugin file : any other plugin declaring
		// Update URI under pay4all.net is not our business.
		if ( strpos( $plugin_file, basename( dirname( P4ALL_PRO_FILE ) ) . '/' ) !== 0 ) {
			return $update;
		}

		$api = new ApiClient();
		$res = $api->update_check();
		if ( empty( $res['ok'] ) || empty( $res['body']['version'] ) ) {
			return $update;
		}

		$b = $res['body'];

		// Defense-in-depth: refuse a payload whose `slug` isn't for our
		// plugin, so a misconfigured SaaS row can't overwrite pay4all-pro
		// with a package meant for another product by accident.
		$returned_slug = strtolower( (string) ( $b['slug'] ?? '' ) );
		$expected      = strtolower( Constants::UPDATE_PRODUCT_CODE );
		if ( $returned_slug !== '' && $returned_slug !== $expected ) {
			return $update;
		}

		$current = (string) ( $plugin_data['Version'] ?? '0' );
		$remote  = (string) $b['version'];
		if ( version_compare( $remote, $current, '<=' ) ) {
			return $update;
		}

		return [
			'slug'         => (string) ( $b['slug'] ?? Constants::UPDATE_PRODUCT_CODE ),
			'plugin'       => $plugin_file,
			'version'      => $remote,
			'url'          => (string) ( $b['url'] ?? Constants::SAAS_URL ),
			'package'      => (string) ( $b['package'] ?? '' ),
			'tested'       => (string) ( $b['tested'] ?? '' ),
			'requires_php' => (string) ( $b['requires_php'] ?? '' ),
			'autoupdate'   => (bool)   ( $b['autoupdate'] ?? false ),
		];
	}
}
