<?php
/**
 * Optional commercial bridge.
 *
 * The WordPress.org build remains fully functional without a payment SDK. A
 * verified merchant integration can provide an upgrade URL through the filter.
 *
 * @package CertaCart_EU_Product_Readiness
 */

namespace CertaCart\EU_Product_Readiness;

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

final class Commercial {
	public static function register(): void {
		self::disable_inactive_premium_jobs();
		add_action( 'ccpr_after_dashboard', array( __CLASS__, 'dashboard_card' ), 20 );
	}

	/**
	 * Stop recurring Premium work after a downgrade or license expiry.
	 *
	 * Premium data remains intact. Only jobs whose callbacks are no longer
	 * available are removed so they cannot accumulate as orphaned cron events.
	 */
	private static function disable_inactive_premium_jobs(): void {
		if ( defined( 'CCPR_PREMIUM_VERSION' ) ) {
			return;
		}

		$scan_id = absint( get_option( 'ccpr_pro_active_scheduled_scan', 0 ) );
		if ( ! $scan_id && ! wp_next_scheduled( 'ccpr_pro_scheduled_scan' ) ) {
			return;
		}
		wp_clear_scheduled_hook( 'ccpr_pro_scheduled_scan' );
		if ( $scan_id ) {
			wp_clear_scheduled_hook( 'ccpr_pro_process_scan', array( $scan_id ) );
		}
		wp_clear_scheduled_hook( 'ccpr_pro_process_scan' );
		if ( $scan_id && function_exists( 'as_unschedule_all_actions' ) ) {
			as_unschedule_all_actions( 'ccpr_pro_process_scan', array( $scan_id ), 'certacart' );
		}
		delete_option( 'ccpr_pro_active_scheduled_scan' );
	}

	public static function upgrade_url(): string {
		if ( defined( 'CCPR_PREMIUM_VERSION' ) ) {
			return '';
		}
		if ( function_exists( '\\ccpr_fs' ) ) {
			$freemius = \ccpr_fs();
			if ( is_object( $freemius ) && method_exists( $freemius, 'get_upgrade_url' ) ) {
				return esc_url_raw( (string) $freemius->get_upgrade_url(), array( 'https' ) );
			}
		}
		$url = apply_filters( 'ccpr_upgrade_url', '' );
		return is_string( $url ) ? esc_url_raw( $url, array( 'https' ) ) : '';
	}

	public static function dashboard_card(): void {
		$url = self::upgrade_url();
		if ( '' === $url || ! current_user_can( 'manage_woocommerce' ) ) {
			return;
		}
		?>
		<div class="ccpr-settings-section ccpr-upgrade-card">
			<h2><?php esc_html_e( 'Repeatable catalog operations', 'certacart-eu-product-readiness' ); ?></h2>
			<p><?php esc_html_e( 'CertaCart Pro adds reusable manufacturer and responsible-person profiles, CSV dry runs and imports, bulk application, and scheduled scan summaries.', 'certacart-eu-product-readiness' ); ?></p>
			<p><a class="button button-primary" href="<?php echo esc_url( $url ); ?>"><?php esc_html_e( 'View Pro plans', 'certacart-eu-product-readiness' ); ?></a></p>
		</div>
		<?php
	}
}
