<?php
namespace Pay4All\Pro\Integrations\Age;

use Pay4All\Age\Services\Kyc;

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

/**
 * Re-wires the WooCommerce-specific hooks that used to live inside
 * pay4all-age's Services\Kyc::register(). The Kyc class itself keeps
 * the target methods (migrate_session_to_order, on_order_deleted,
 * handle_admin_view_user) — this bridge just re-binds them to the
 * WC lifecycle from pay4all-pro's side.
 *
 * It also owns the WooCommerce-flavoured extensions of the three
 * generic action / filter hooks pay4all-age exposes for companion
 * plugins :
 *   - `pay4all_age_token_ensured`  → mirror the token into WC session
 *   - `pay4all_age_recover_token`  → fallback token lookup from WC session
 *   - `pay4all_age_order_exists`   → resolve a WC shop_order id
 */
final class WooBridge {

	public const WC_SESSION_KEY = 'p4all_age_kyc_token';

	public static function register() : void {
		// WC order lifecycle → pay4all-age's static entry points.
		add_action( 'woocommerce_checkout_order_created',            [ Kyc::class, 'migrate_session_to_order' ], 10, 1 );
		add_action( 'woocommerce_store_api_checkout_order_processed', [ Kyc::class, 'migrate_session_to_order' ], 10, 1 );
		add_action( 'woocommerce_delete_order',                      [ Kyc::class, 'on_order_deleted' ] );
		// The `admin_post_p4all_age_view_user` handler stays in Kyc.php
		// so that the UserProfile screen (which lives in pay4all-age)
		// still resolves its shield URLs on a pay4all-form-only install.

		// pay4all-age hooks : WC-flavoured contributions.
		add_action( 'pay4all_age_token_ensured', [ self::class, 'sync_token_to_wc_session' ], 10, 1 );
		add_filter( 'pay4all_age_recover_token', [ self::class, 'recover_token_from_wc_session' ], 10, 1 );
		add_filter( 'pay4all_age_order_exists',  [ self::class, 'wc_order_exists' ], 10, 2 );
		// Grant WC shop-managers access to the KYC-photo lightbox on the
		// order edit screen. Without this, the modal HTML never renders
		// on a shop-manager account and the shield button is unclickable.
		add_filter( 'pay4all_age_lightbox_capabilities', [ self::class, 'add_wc_capability' ], 10, 1 );
	}

	/**
	 * Mirror the current KYC token into the WC session so `locate_token()`
	 * still has a durable channel when the browser cookie failed to set
	 * (headers-sent race) or wasn't sent back (SameSite, secure-only).
	 * Called from `Kyc::ensure_session_token()` after every server-side
	 * confirmation via the `pay4all_age_token_ensured` action.
	 */
	public static function sync_token_to_wc_session( string $token ) : void {
		if ( ! preg_match( '/^[a-f0-9]{12}$/', $token ) ) { return; }
		if ( ! function_exists( 'WC' ) || ! WC()->session ) { return; }
		$current = (string) WC()->session->get( self::WC_SESSION_KEY, '' );
		if ( $current === $token ) { return; }
		WC()->session->set( self::WC_SESSION_KEY, $token );
	}

	/**
	 * Fallback token lookup used when both the POST body and the cookie
	 * failed to yield a valid token. Reads the KYC token from the WC
	 * session bucket populated by `sync_token_to_wc_session()`.
	 */
	public static function recover_token_from_wc_session( string $token ) : string {
		if ( preg_match( '/^[a-f0-9]{12}$/', $token ) ) { return $token; }
		if ( ! function_exists( 'WC' ) || ! WC()->session ) { return $token; }
		return (string) WC()->session->get( self::WC_SESSION_KEY, '' );
	}

	/**
	 * WC order existence filter used by `Kyc::order_exists()` to decide
	 * whether an id belongs to a shop_order without pay4all-age itself
	 * calling `wc_get_order()`.
	 */
	public static function wc_order_exists( bool $exists, int $order_id ) : bool {
		if ( $exists ) { return true; }
		if ( ! function_exists( 'wc_get_order' ) ) { return false; }
		return (bool) wc_get_order( $order_id );
	}

	/**
	 * Adds `manage_woocommerce` to the capabilities allowed to open the
	 * KYC-photo lightbox. Registered on the `p4all_age_lightbox_
	 * capabilities` filter so pay4all-age itself doesn't need to know
	 * about any WC-specific capability string.
	 *
	 * @param string[] $caps Current capability list.
	 * @return string[]
	 */
	public static function add_wc_capability( array $caps ) : array {
		$caps[] = 'manage_woocommerce';
		return $caps;
	}
}
