<?php
/**
 * HJCyberX Checkout for Paddle Lite Loader.
 *
 * Central bootstrap class that wires every subsystem together.
 * Called once WooCommerce is confirmed active.
 *
 * @package HJCyberX Checkout for Paddle Lite
 */

defined( 'ABSPATH' ) || exit;

/**
 * Class PaddleKonnect_Lite_Loader
 */
class PaddleKonnect_Lite_Loader {

	/**
	 * Singleton guard.
	 *
	 * @var bool
	 */
	private static bool $initialised = false;

	/**
	 * Boot the plugin.
	 */
	public static function init(): void {

		if ( self::$initialised ) {
			return;
		}
		self::$initialised = true;

		// ── Require class files ────────────────.
		self::require_files();

		// ── Register the WooCommerce gateway ───.
		add_filter( 'woocommerce_payment_gateways', array( __CLASS__, 'register_gateway' ) );

		// ── Instantiate subsystems ─────────────.
		new PaddleKonnect_Lite_Webhook();
		new PaddleKonnect_Lite_Product_Meta();
		PaddleKonnect_Lite_Upsell::init();
		PaddleKonnect_Lite_Marketing::init();
		PaddleKonnect_Lite_Documentation::init();

		// ── Enqueue frontend assets ────────────.
		add_action( 'wp_enqueue_scripts', array( __CLASS__, 'enqueue_frontend_assets' ) );

		// ── Enqueue admin assets ───────────────.
		add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_admin_assets' ) );

		// ── AJAX order polling ─────────────────.
		add_action( 'wp_ajax_nopriv_paddlekonnect_lite_check_order_status', array( __CLASS__, 'check_order_status' ) );
		add_action( 'wp_ajax_paddlekonnect_lite_check_order_status', array( __CLASS__, 'check_order_status' ) );

		// ── Add settings link on Plugins page ──.
		add_filter(
			'plugin_action_links_' . PADDLEKONNECT_LITE_PLUGIN_BASENAME,
			array( __CLASS__, 'add_settings_link' )
		);
	}

	// ──────────────────────────────────────────.
	// Require Files.
	// ──────────────────────────────────────────.

	/**
	 * Include all class files.
	 */
	private static function require_files(): void {
		require_once PADDLEKONNECT_LITE_PLUGIN_DIR . 'includes/class-paddlekonnect-lite-logger.php';
		require_once PADDLEKONNECT_LITE_PLUGIN_DIR . 'includes/class-paddlekonnect-lite-gateway.php';
		require_once PADDLEKONNECT_LITE_PLUGIN_DIR . 'includes/class-paddlekonnect-lite-webhook.php';
		require_once PADDLEKONNECT_LITE_PLUGIN_DIR . 'includes/class-paddlekonnect-lite-product-meta.php';
		require_once PADDLEKONNECT_LITE_PLUGIN_DIR . 'includes/class-paddlekonnect-lite-upsell.php';
		require_once PADDLEKONNECT_LITE_PLUGIN_DIR . 'includes/class-paddlekonnect-lite-marketing.php';
		require_once PADDLEKONNECT_LITE_PLUGIN_DIR . 'includes/class-paddlekonnect-lite-documentation.php';
	}

	// ──────────────────────────────────────────.
	// Gateway Registration.
	// ──────────────────────────────────────────.

	/**
	 * Register HJCyberX Checkout for Paddle Lite with WooCommerce.
	 *
	 * @param  array $gateways Existing gateways.
	 * @return array Modified gateways list.
	 */
	public static function register_gateway( array $gateways ): array {
		$gateways[] = 'PaddleKonnect_Lite_Gateway';
		return $gateways;
	}

	// ──────────────────────────────────────────.
	// Frontend Assets.
	// ──────────────────────────────────────────.

	/**
	 * Enqueue Paddle.js and our checkout script on the checkout page.
	 */
	public static function enqueue_frontend_assets(): void {

		// Only load on the WooCommerce checkout page.
		if ( ! is_checkout() ) {
			return;
		}

		// Get gateway settings.
		$gateway = self::get_gateway_instance();
		if ( ! $gateway || 'yes' !== $gateway->enabled ) {
			return;
		}

		// ── Paddle.js from CDN ─────────────────.
		wp_enqueue_script(
			'paddle-js',
			'https://cdn.paddle.com/paddle/v2/paddle.js',
			array(),
			PADDLEKONNECT_LITE_VERSION, // Passed to silence the Plugin Check bot warning.
			true
		);

		// ── Our checkout handler ───────────────.
		wp_enqueue_script(
			'paddlekonnect-checkout',
			PADDLEKONNECT_LITE_PLUGIN_URL . 'assets/js/paddlekonnect-lite-checkout.js',
			array( 'jquery', 'paddle-js' ),
			PADDLEKONNECT_LITE_VERSION,
			true
		);

		// Localise data for the JS.
		wp_localize_script(
			'paddlekonnect-checkout',
			'paddlekonnect_params',
			array(
				'ajax_url'     => admin_url( 'admin-ajax.php' ),
				'nonce'        => wp_create_nonce( 'paddlekonnect_checkout' ),
				'client_token' => $gateway->get_option( 'client_token', '' ),
				'seller_id'    => $gateway->get_option( 'seller_id', '' ),
				'sandbox'      => $gateway->get_option( 'sandbox_mode', 'no' ) === 'yes' ? '1' : '0',
				'gateway_id'   => 'hjcyberx-checkout-for-paddle-lite',
			)
		);

		// ── Checkout CSS ───────────────────────.
		wp_enqueue_style(
			'paddlekonnect-checkout',
			PADDLEKONNECT_LITE_PLUGIN_URL . 'assets/css/paddlekonnect-lite-checkout.css',
			array(),
			PADDLEKONNECT_LITE_VERSION
		);
	}

	// ──────────────────────────────────────────.
	// Admin Assets.
	// ──────────────────────────────────────────.

	/**
	 * Enqueue admin scripts/styles on product edit screens.
	 *
	 * @param string $hook_suffix The current admin page.
	 */
	public static function enqueue_admin_assets( string $hook_suffix ): void {

		$screen = get_current_screen();
		if ( ! $screen ) {
			return;
		}

		// Product edit screen or post edit screen (for vault restriction meta box).
		if ( in_array( $screen->id, array( 'product', 'page', 'post' ), true ) ) {
			wp_enqueue_script(
				'paddlekonnect-admin',
				PADDLEKONNECT_LITE_PLUGIN_URL . 'assets/js/paddlekonnect-lite-admin.js',
				array( 'jquery' ),
				PADDLEKONNECT_LITE_VERSION,
				true
			);

			wp_enqueue_style(
				'paddlekonnect-admin',
				PADDLEKONNECT_LITE_PLUGIN_URL . 'assets/css/paddlekonnect-lite-admin.css',
				array(),
				PADDLEKONNECT_LITE_VERSION
			);
		}
	}

	// ──────────────────────────────────────────.
	// Settings Link.
	// ──────────────────────────────────────────.

	/**
	 * Add a "Settings" link on the Plugins list page.
	 *
	 * @param  array $links Existing action links.
	 * @return array Modified action links.
	 */
	public static function add_settings_link( array $links ): array {
		$settings_url = admin_url( 'admin.php?page=wc-settings&tab=checkout&section=paddlekonnect-lite' );
		$pro_url      = 'https://plugins.hjcyberx.com/plugins/hjcyberx-checkout-paddle#features';

		array_unshift(
			$links,
			sprintf(
				'<a href="%s" style="color: #46b450; font-weight: bold;">%s</a>',
				esc_url( $pro_url ),
				esc_html__( 'Go Pro / Features', 'hjcyberx-checkout-for-paddle-lite' )
			),
			sprintf(
				'<a href="%s">%s</a>',
				esc_url( $settings_url ),
				esc_html__( 'Settings', 'hjcyberx-checkout-for-paddle-lite' )
			)
		);
		return $links;
	}

	// ──────────────────────────────────────────.
	// Helpers.
	// ──────────────────────────────────────────.

	/**
	 * Retrieve the gateway instance from WooCommerce.
	 *
	 * @return PaddleKonnect_Lite_Gateway|null
	 */
	public static function get_gateway_instance(): ?PaddleKonnect_Lite_Gateway {
		$gateways = WC()->payment_gateways()->payment_gateways();
		return $gateways['hjcyberx-checkout-for-paddle-lite'] ?? null;
	}

	/**
	 * AJAX handler to check order status from the frontend.
	 */
	public static function check_order_status(): void {
		check_ajax_referer( 'paddlekonnect_checkout', 'nonce' );

		$order_id = isset( $_POST['order_id'] ) ? absint( $_POST['order_id'] ) : 0;
		$order    = wc_get_order( $order_id );

		if ( ! $order ) {
			wp_send_json_error( array( 'message' => 'Order not found.' ) );
		}

		$status = $order->get_status();
		// If the status has moved past 'pending', we consider it ready.
		if ( in_array( $status, array( 'processing', 'completed', 'on-hold' ), true ) ) {
			wp_send_json_success( array( 'status' => $status ) );
		} else {
			wp_send_json_error( array( 'status' => $status ) );
		}
	}
}
