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

use Pay4All\Age\Services\Config;
use Pay4All\Age\Services\Kyc;

// phpcs:disable WordPress.WP.I18n.TextDomainMismatch -- Bridge to pay4all-age :
// the « account creation with age verification » copy is the same one the free
// plugin exposes elsewhere. Reusing its text domain keeps a single source of
// translations across both plugins.

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

/**
 * Opt-in age verification during WooCommerce account creation.
 *
 * Flow:
 *   1. On the "Mon compte / Créer un compte" form, we render a checkbox
 *      « Je souhaite valider ma majorité dès maintenant ». Ticking it
 *      reveals the same KYC panel used at checkout (QR + slots + choice
 *      widget), backed by a session token created on first render.
 *   2. Photos captured via the mobile page or desktop upload go into the
 *      normal session bucket (`sess-*`), same as checkout.
 *   3. On `woocommerce_created_customer`, we migrate the session bucket
 *      into the new user's `user-{id}` bucket and stamp the user meta
 *      so subsequent checkouts skip the KYC UI entirely.
 */
final class Registration {

	public static function register() : void {
		add_action( 'wp_enqueue_scripts',            [ __CLASS__, 'enqueue_on_account_page' ] );
		add_action( 'woocommerce_register_form',     [ __CLASS__, 'render_form' ] );
		add_action( 'woocommerce_created_customer',  [ __CLASS__, 'on_customer_created' ], 20, 1 );
	}

	private static function feature_enabled() : bool {
		// The pay4all-age plugin is fully free ; the feature is always available
		// when pay4all-age itself is present.
		return class_exists( '\\Pay4All\\Age\\Services\\Kyc' );
	}

	/**
	 * Load the checkout CSS/JS on the My Account page so the KYC panel
	 * inside the register form behaves exactly like on the checkout.
	 */
	public static function enqueue_on_account_page() : void {
		if ( is_admin() || is_user_logged_in() ) { return; }
		if ( ! function_exists( 'is_account_page' ) || ! is_account_page() ) { return; }
		if ( ! self::feature_enabled() ) { return; }

		wp_enqueue_style(
			'p4all-age-checkout',
			P4ALL_AGE_URL . 'assets/public/css/checkout.css',
			[],
			P4ALL_AGE_VERSION
		);
		wp_enqueue_script(
			'p4all-age-qr',
			P4ALL_AGE_URL . 'assets/public/js/qr.js',
			[],
			P4ALL_AGE_VERSION,
			true
		);
		wp_enqueue_script(
			'p4all-age-checkout',
			P4ALL_AGE_URL . 'assets/public/js/checkout.js',
			[ 'p4all-age-qr' ],
			P4ALL_AGE_VERSION,
			true
		);
		wp_localize_script( 'p4all-age-checkout', 'p4allAgeI18n', [
			'sent'       => __( 'Envoyé', 'pay4all-age' ),
			'sending'    => __( 'Envoi en cours…', 'pay4all-age' ),
			'uploadFail' => __( 'Échec de l\'envoi. Réessayez.', 'pay4all-age' ),
			'waiting'    => Config::text( 'waiting' ),
		] );
	}

	public static function render_form() : void {
		if ( ! self::feature_enabled() ) { return; }
		if ( is_user_logged_in() ) { return; }
		?>
		<div class="p4all-age-register" style="margin:16px 0;padding:14px;border:1px solid #dcdcde;border-radius:8px;background:#fbfbfc;">
			<p style="margin:0 0 8px;">
				<label style="display:flex;gap:8px;align-items:flex-start;cursor:pointer;">
					<input type="checkbox" name="p4all_age_optin" value="1" id="p4all-age-optin"
					       onchange="document.getElementById('p4all-age-register-panel').hidden = !this.checked;">
					<span>
						<strong><?php echo esc_html( Config::text( 'register_optin_title' ) ); ?></strong><br>
						<small style="color:#555;">
							<?php echo esc_html( Config::text( 'register_optin_desc' ) ); ?>
						</small>
					</span>
				</label>
			</p>

			<div id="p4all-age-register-panel" hidden style="margin-top:12px;">
				<?php Checkout::render_main_html(); ?>
			</div>
		</div>
		<?php
	}

	/**
	 * Fired after WooCommerce creates the user account. If the customer
	 * opted-in and the session bucket has usable slots, migrate them to
	 * the user's permanent bucket.
	 *
	 * @param int $customer_id
	 */
	public static function on_customer_created( $customer_id ) : void {
		$customer_id = (int) $customer_id;
		if ( ! $customer_id ) { return; }
		if ( ! self::feature_enabled() ) { return; }

		// Opt-in only : we don't move photos silently if the customer
		// didn't tick the box (they may have uploaded on a shared
		// device by mistake).
		// Nonce : bound to `woocommerce_created_customer` fired from
		// `wc_create_new_customer()` which itself is gated by WC's own
		// registration nonce verification upstream.
		// phpcs:ignore WordPress.Security.NonceVerification.Missing -- verified by WC upstream on woocommerce_created_customer.
		$optin = isset( $_POST['p4all_age_optin'] ) && (string) $_POST['p4all_age_optin'] === '1';
		if ( ! $optin ) { return; }

		$token = Kyc::locate_token();
		if ( $token === '' ) { return; }

		Kyc::migrate_session_to_user( $customer_id, $token );
	}
}
