<?php
/**
 * Marketing consent UI on checkout and registration forms.
 *
 * @package CartCue
 */

namespace CartCue;

defined( 'ABSPATH' ) || exit;

final class CheckoutConsent {

	public static function init(): void {
		if ( MarketingConsent::is_enabled() ) {
			$s = MarketingConsent::get_settings();

			if ( '1' === (string) ( $s['consent_checkout'] ?? '0' ) ) {
				add_action( 'woocommerce_review_order_before_submit', [ __CLASS__, 'render_classic_checkbox' ], 9 );
				add_action( 'woocommerce_checkout_update_order_meta', [ __CLASS__, 'save_classic_checkout' ], 10, 1 );
			}

			if ( '1' === (string) ( $s['consent_checkout_blocks'] ?? '0' ) && self::supports_blocks_field() ) {
				add_action( 'woocommerce_init', [ __CLASS__, 'register_blocks_field' ] );
			}

			if ( '1' === (string) ( $s['consent_wp_register'] ?? '0' ) ) {
				add_action( 'register_form', [ __CLASS__, 'render_register_checkbox' ] );
			}

			if ( '1' === (string) ( $s['consent_wc_register'] ?? '0' ) ) {
				add_action( 'woocommerce_register_form', [ __CLASS__, 'render_register_checkbox' ] );
			}
		}

		self::register_sms_hooks();
	}

	private static function register_sms_hooks(): void {
		if ( ! SmsConsent::is_enabled() ) {
			return;
		}

		$s = SmsConsent::get_settings();

		if ( '1' === (string) ( $s['sms_consent_checkout'] ?? '0' ) ) {
			add_action( 'woocommerce_review_order_before_submit', [ __CLASS__, 'render_sms_classic_checkbox' ], 10 );
			add_action( 'woocommerce_checkout_update_order_meta', [ __CLASS__, 'save_sms_classic_checkout' ], 11, 1 );
		}

		if ( '1' === (string) ( $s['sms_consent_checkout_blocks'] ?? '0' ) && self::supports_blocks_field() ) {
			add_action( 'woocommerce_init', [ __CLASS__, 'register_sms_blocks_field' ] );
		}
	}

	public static function supports_blocks_field(): bool {
		return function_exists( 'woocommerce_register_additional_checkout_field' );
	}

	public static function render_classic_checkbox(): void {
		if ( ! is_checkout() ) {
			return;
		}
		echo self::checkbox_html( 'cartcue_marketing_consent' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
	}

	public static function render_register_checkbox(): void {
		echo self::checkbox_html( 'cartcue_marketing_consent' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
	}

	private static function checkbox_html( string $name ): string {
		$label = MarketingConsent::consent_label();
		return '<p class="form-row cartcue-consent-row">'
			. '<label class="woocommerce-form__label woocommerce-form__label-for-checkbox checkbox">'
			. '<input type="checkbox" class="woocommerce-form__input woocommerce-form__input-checkbox input-checkbox" name="'
			. esc_attr( $name ) . '" value="1" id="' . esc_attr( $name ) . '"> '
			. '<span>' . esc_html( $label ) . '</span>'
			. '</label></p>';
	}

	public static function save_classic_checkout( int $order_id ): void {
		// phpcs:ignore WordPress.Security.NonceVerification.Missing
		$consented = ! empty( $_POST['cartcue_marketing_consent'] );
		self::persist_order_consent( $order_id, $consented );
	}

	public static function persist_order_consent( int $order_id, bool $consented ): void {
		$order = wc_get_order( $order_id );
		if ( ! $order ) {
			return;
		}

		$order->update_meta_data( MarketingConsent::ORDER_META_KEY, $consented ? 'yes' : 'no' );
		$order->save();

		$email = $order->get_billing_email();
		if ( $consented && is_email( $email ) ) {
			MarketingConsent::grant( $email, 'checkout' );
		}
	}

	public static function render_sms_classic_checkbox(): void {
		if ( ! is_checkout() ) {
			return;
		}
		echo self::sms_checkbox_html( 'cartcue_sms_consent' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
	}

	public static function save_sms_classic_checkout( int $order_id ): void {
		// phpcs:ignore WordPress.Security.NonceVerification.Missing
		SmsConsent::persist_order_consent( $order_id, ! empty( $_POST['cartcue_sms_consent'] ) );
	}

	private static function sms_checkbox_html( string $name ): string {
		$label = SmsConsent::consent_label();
		return '<p class="form-row cartcue-sms-consent-row">'
			. '<label class="woocommerce-form__label woocommerce-form__label-for-checkbox checkbox">'
			. '<input type="checkbox" class="woocommerce-form__input woocommerce-form__input-checkbox input-checkbox" name="'
			. esc_attr( $name ) . '" value="1" id="' . esc_attr( $name ) . '"> '
			. '<span>' . esc_html( $label ) . '</span>'
			. '</label></p>';
	}

	public static function register_sms_blocks_field(): void {
		if ( ! self::supports_blocks_field() ) {
			return;
		}

		woocommerce_register_additional_checkout_field(
			[
				'id'       => 'cartcue/sms_consent',
				'label'    => SmsConsent::consent_label(),
				'location' => 'contact',
				'type'     => 'checkbox',
				'required' => false,
			]
		);

		add_action(
			'woocommerce_set_additional_field_value',
			static function ( $key, $value, $group, $wc_object ): void {
				if ( 'cartcue/sms_consent' !== $key || ! $wc_object instanceof \WC_Order ) {
					return;
				}
				SmsConsent::persist_order_consent( $wc_object->get_id(), (bool) $value );
			},
			10,
			4
		);
	}

	public static function register_blocks_field(): void {
		if ( ! self::supports_blocks_field() ) {
			return;
		}

		woocommerce_register_additional_checkout_field(
			[
				'id'       => 'cartcue/marketing_consent',
				'label'    => MarketingConsent::consent_label(),
				'location' => 'contact',
				'type'     => 'checkbox',
				'required' => false,
			]
		);

		add_action(
			'woocommerce_set_additional_field_value',
			static function ( $key, $value, $group, $wc_object ): void {
				if ( 'cartcue/marketing_consent' !== $key || ! $wc_object instanceof \WC_Order ) {
					return;
				}
				$consented = (bool) $value;
				$wc_object->update_meta_data( MarketingConsent::ORDER_META_KEY, $consented ? 'yes' : 'no' );
				$email = $wc_object->get_billing_email();
				if ( $consented && is_email( $email ) ) {
					MarketingConsent::grant( $email, 'checkout_blocks' );
				}
			},
			10,
			4
		);
	}
}
