<?php
/**
 * Frontend display of coupons (banner + popup) with anti-repeat cookies and tracking.
 *
 * @package SuiteMkt3k
 */

namespace SuiteMkt3k\Modules\Coupons;

use SuiteMkt3k\Frontend\Frontend;
use SuiteMkt3k\Modules\Settings\Settings_Manager;

defined( 'ABSPATH' ) || exit;

final class Coupon_Display {

	public static function register(): void {
		add_action( 'wp_body_open', array( __CLASS__, 'render_banner' ) );
		add_action( 'wp_footer', array( __CLASS__, 'render_popup' ) );
		add_action( 'wp_enqueue_scripts', array( __CLASS__, 'enqueue_assets' ) );
	}

	public static function enqueue_assets(): void {
		if ( is_admin() || empty( self::active_for_user() ) ) {
			return;
		}
		Frontend::enqueue_public_assets(
			array(
				'currency' => self::currency_meta(),
			)
		);
	}

	private static function currency_meta(): array {
		if ( function_exists( 'get_woocommerce_currency_symbol' ) ) {
			return array(
				'code'   => get_woocommerce_currency(),
				'symbol' => html_entity_decode( get_woocommerce_currency_symbol() ),
			);
		}
		return array( 'code' => 'EUR', 'symbol' => '€' );
	}

	public static function render_banner(): void {
		foreach ( self::active_for_user() as $coupon ) {
			if ( empty( $coupon['design']['banner_enabled'] ) ) {
				continue;
			}
			$d    = $coupon['design'];
			$bg   = esc_attr( $d['bg_color'] ?? '#2AB2E5' );
			$grad = esc_attr( $d['gradient_to'] ?? $d['bg_color'] ?? '#2AB2E5' );
			$fg   = esc_attr( $d['text_color'] ?? '#FFFFFF' );
			$mc   = esc_attr( $d['marketing_color'] ?? $d['text_color'] ?? '#FFFFFF' );
			$vc   = esc_attr( $d['value_color'] ?? $d['text_color'] ?? '#FFFFFF' );
			$cta_bg      = esc_attr( $d['cta_bg_color'] ?? '#FFFFFF' );
			$cta_fg      = esc_attr( $d['cta_text_color'] ?? $d['bg_color'] ?? '#2AB2E5' );
			$cta_code_fg = esc_attr( $d['cta_code_color'] ?? $cta_fg );
			$cta_icon_fg = esc_attr( $d['cta_icon_color'] ?? $cta_code_fg );
			$value       = self::format_value( $coupon );
			$cta_radius  = max( 0, min( 99, (int) ( $d['cta_radius'] ?? 10 ) ) );
			$is_classic  = Coupon_Manager::FORMAT_OPTIN !== $coupon['format_type'];
			// Opt-in always needs the CTA to open step 2 (form).
			$cta_enabled = $is_classic
				? ( ! isset( $d['cta_enabled'] ) || ! empty( $d['cta_enabled'] ) )
				: true;
			$coupon_code = $is_classic ? Coupon_Manager::get_coupon_code( $coupon ) : '';
			?>
			<div class="wmk-banner" data-coupon="<?php echo esc_attr( (string) $coupon['id'] ); ?>"
				data-coupon-code="<?php echo esc_attr( $coupon_code ); ?>"
				style="background: linear-gradient(135deg, <?php echo esc_attr( $bg ); ?> 0%, <?php echo esc_attr( $grad ); ?> 100%); color: <?php echo esc_attr( $fg ); ?>;--wmk-cta-radius:<?php echo (int) $cta_radius; ?>px;"
				role="region" aria-label="<?php esc_attr_e( 'Promotional offer', 'suitemkt3k' ); ?>">
				<div class="wmk-banner-inner">
					<span class="wmk-banner-text" style="color: <?php echo esc_attr( $mc ); ?>;"><?php echo esc_html( (string) $coupon['marketing_text'] ); ?></span>
					<?php if ( $value ) : ?>
					<span class="wmk-banner-value" style="color: <?php echo esc_attr( $vc ); ?>;"><?php echo esc_html( $value ); ?></span>
					<?php endif; ?>
					<?php if ( $cta_enabled ) : ?>
					<button type="button" class="wmk-banner-cta<?php echo $is_classic ? ' wmk-cta-copy-code' : ''; ?>"
						data-action="<?php echo $is_classic ? 'copy' : 'optin'; ?>"
						style="background: <?php echo esc_attr( $cta_bg ); ?>; color: <?php echo esc_attr( $is_classic ? $cta_code_fg : $cta_fg ); ?>; border-radius: <?php echo (int) $cta_radius; ?>px;">
						<?php if ( $is_classic && $coupon_code ) : ?>
							<span class="wmk-cta-code" style="color: <?php echo esc_attr( $cta_code_fg ); ?>;"><?php echo esc_html( $coupon_code ); ?></span>
							<svg class="wmk-cta-copy-icon" viewBox="0 0 24 24" fill="none" stroke="<?php echo esc_attr( $cta_icon_fg ); ?>" stroke-width="2" aria-hidden="true"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
						<?php else : ?>
							<?php echo esc_html( (string) ( $d['cta_optin_label'] ?? '' ) ); ?>
						<?php endif; ?>
					</button>
					<?php endif; ?>
				</div>
			</div>
			<?php
			break;
		}
	}

	public static function render_popup(): void {
		foreach ( self::active_for_user() as $coupon ) {
			if ( empty( $coupon['design']['popup_enabled'] ) ) {
				continue;
			}
			$d     = $coupon['design'];
			$bg    = esc_attr( $d['bg_color'] ?? '#2AB2E5' );
			$grad  = esc_attr( $d['gradient_to'] ?? $d['bg_color'] ?? '#2AB2E5' );
			$fg    = esc_attr( $d['text_color'] ?? '#FFFFFF' );
			$delay = (int) ( $d['popup_delay'] ?? 4 );
			$label_color = esc_attr( $d['field_label_color'] ?? $d['text_color'] ?? '#FFFFFF' );
			$ph_color    = esc_attr( $d['field_placeholder_color'] ?? '#FFFFFF' );
			$ftxt_color  = esc_attr( $d['field_text_color'] ?? '#FFFFFF' );
			$name_color    = esc_attr( $d['name_color'] ?? $d['text_color'] ?? '#FFFFFF' );
			$mkt_color     = esc_attr( $d['marketing_color'] ?? $d['text_color'] ?? '#FFFFFF' );
			$val_color     = esc_attr( $d['value_color'] ?? $d['text_color'] ?? '#FFFFFF' );
			$cta_bg        = esc_attr( $d['cta_bg_color'] ?? '#FFFFFF' );
			$cta_fg        = esc_attr( $d['cta_text_color'] ?? $d['bg_color'] ?? '#2AB2E5' );
			$cta_code_fg   = esc_attr( $d['cta_code_color'] ?? $cta_fg );
			$cta_icon_fg   = esc_attr( $d['cta_icon_color'] ?? $cta_code_fg );
			$consent_color = esc_attr( $d['consent_text_color'] ?? $label_color );
			$opacity       = max( 0, min( 1, (float) ( $d['image_opacity'] ?? 1 ) ) );
			$field_bg      = esc_attr( self::hex_rgba( (string) ( $d['field_bg_color'] ?? '#FFFFFF' ), (float) ( $d['field_bg_opacity'] ?? 0.14 ) ) );
			$field_border_on = ! isset( $d['field_border_enabled'] ) || ! empty( $d['field_border_enabled'] );
			$field_border  = $field_border_on ? esc_attr( (string) ( $d['field_border_color'] ?? '#FFFFFF' ) ) : 'transparent';
			$field_border_w = $field_border_on ? '1px' : '0';
			$field_radius  = max( 0, min( 40, (int) ( $d['field_radius'] ?? 8 ) ) );

			$popup_style  = "background: linear-gradient(135deg, {$bg} 0%, {$grad} 100%); color: {$fg};";
			$consent_text = (string) ( $d['consent_text'] ?? __( 'I agree to receive marketing emails and discounts.', 'suitemkt3k' ) );
			$cta_radius   = max( 0, min( 99, (int) ( $d['cta_radius'] ?? 10 ) ) );
			$popup_radius = max( 0, min( 99, (int) ( $d['popup_radius'] ?? 18 ) ) );
			$is_classic   = Coupon_Manager::FORMAT_OPTIN !== $coupon['format_type'];
			$cta_enabled  = $is_classic
				? ( ! isset( $d['cta_enabled'] ) || ! empty( $d['cta_enabled'] ) )
				: true;
			$coupon_code  = $is_classic ? Coupon_Manager::get_coupon_code( $coupon ) : '';
			?>
			<div class="wmk-popup-root" data-coupon="<?php echo esc_attr( (string) $coupon['id'] ); ?>"
				data-coupon-code="<?php echo esc_attr( $coupon_code ); ?>"
				data-delay="<?php echo esc_attr( (string) $delay ); ?>" data-format="<?php echo esc_attr( $coupon['format_type'] ); ?>" hidden>
				<div class="wmk-popup-backdrop" data-close></div>
				<div class="wmk-popup" data-coupon-style="<?php echo esc_attr( (string) $coupon['id'] ); ?>"
					style="<?php echo esc_attr( $popup_style ); ?>;--wmk-popup-radius:<?php echo (int) $popup_radius; ?>px;--wmk-cta-radius:<?php echo (int) $cta_radius; ?>px;--wmk-ph:<?php echo esc_attr( $ph_color ); ?>;--wmk-ftxt:<?php echo esc_attr( $ftxt_color ); ?>;--wmk-label:<?php echo esc_attr( $label_color ); ?>;--wmk-consent:<?php echo esc_attr( $consent_color ); ?>;--wmk-field-bg:<?php echo esc_attr( $field_bg ); ?>;--wmk-field-border:<?php echo esc_attr( $field_border ); ?>;--wmk-field-border-width:<?php echo esc_attr( $field_border_w ); ?>;--wmk-field-radius:<?php echo (int) $field_radius; ?>px;">
					<?php if ( ! empty( $d['image_url'] ) ) : ?>
						<div class="wmk-popup-image" aria-hidden="true" style="background-image: url('<?php echo esc_url( $d['image_url'] ); ?>'); opacity: <?php echo esc_attr( (string) $opacity ); ?>;"></div>
					<?php endif; ?>
					<button class="wmk-popup-close" type="button" data-close aria-label="<?php esc_attr_e( 'Close', 'suitemkt3k' ); ?>">&times;</button>
					<div class="wmk-popup-viewport">
						<div class="wmk-popup-track">
							<div class="wmk-popup-slide wmk-popup-step1">
								<h2 style="color: <?php echo esc_attr( $name_color ); ?>;"><?php echo esc_html( (string) $coupon['name'] ); ?></h2>
								<p style="color: <?php echo esc_attr( $mkt_color ); ?>;"><?php echo esc_html( (string) $coupon['marketing_text'] ); ?></p>
								<?php $popup_value = self::format_value( $coupon ); ?>
								<?php if ( $popup_value ) : ?>
								<div class="wmk-popup-value" style="color: <?php echo esc_attr( $val_color ); ?>;"><?php echo esc_html( $popup_value ); ?></div>
								<?php endif; ?>
								<?php if ( $cta_enabled ) : ?>
								<button type="button" class="wmk-popup-cta<?php echo $is_classic ? ' wmk-cta-copy-code' : ''; ?>"
									data-action="<?php echo $is_classic ? 'copy' : 'optin'; ?>"
									style="background: <?php echo esc_attr( $cta_bg ); ?>; color: <?php echo esc_attr( $is_classic ? $cta_code_fg : $cta_fg ); ?>; border-radius: <?php echo (int) $cta_radius; ?>px;">
									<?php if ( $is_classic && $coupon_code ) : ?>
										<span class="wmk-cta-code" style="color: <?php echo esc_attr( $cta_code_fg ); ?>;"><?php echo esc_html( $coupon_code ); ?></span>
										<svg class="wmk-cta-copy-icon" viewBox="0 0 24 24" fill="none" stroke="<?php echo esc_attr( $cta_icon_fg ); ?>" stroke-width="2" aria-hidden="true"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
									<?php else : ?>
										<?php echo esc_html( (string) ( $d['cta_optin_label'] ?? '' ) ); ?>
									<?php endif; ?>
								</button>
								<?php endif; ?>
							</div>
							<?php if ( Coupon_Manager::FORMAT_OPTIN === $coupon['format_type'] ) : ?>
							<div class="wmk-popup-slide wmk-popup-step2">
								<form class="wmk-popup-form" method="post" action="#" novalidate>
									<input type="hidden" name="coupon_id" value="<?php echo esc_attr( (string) $coupon['id'] ); ?>">
									<?php foreach ( (array) $d['form_fields'] as $field ) : ?>
										<?php
										$field_key = (string) ( $field['key'] ?? '' );
										if ( '' === $field_key ) {
											continue;
										}
										// Opt-in: Name / Birth date can be hidden from Display settings.
										if ( 'email' !== $field_key && isset( $field['enabled'] ) && empty( $field['enabled'] ) ) {
											continue;
										}
										$field_label = self::normalize_form_field_label( $field_key, (string) ( $field['label'] ?? '' ) );
										$is_required = 'email' === $field_key || ! empty( $field['required'] );
										?>
										<label>
											<span><?php echo esc_html( $field_label ); ?><?php echo $is_required ? ' *' : ''; ?></span>
											<input
												type="<?php echo 'email' === $field_key ? 'email' : ( 'birth_date' === $field_key ? 'date' : 'text' ); ?>"
												name="<?php echo esc_attr( $field_key ); ?>"
												placeholder="<?php echo esc_attr( $field_label ); ?>"
												<?php echo $is_required ? 'required' : ''; ?>>
										</label>
									<?php endforeach; ?>
									<label class="wmk-consent">
										<input type="checkbox" name="consent" required>
										<span><?php echo esc_html( $consent_text ); ?></span>
									</label>
									<button type="submit" class="wmk-popup-cta"
										style="background: <?php echo esc_attr( $cta_bg ); ?>; color: <?php echo esc_attr( $cta_fg ); ?>; border-radius: <?php echo (int) $cta_radius; ?>px;">
										<?php echo esc_html( (string) ( $d['cta_step2_label'] ?? __( 'Receive', 'suitemkt3k' ) ) ); ?>
									</button>
								</form>
							</div>
							<?php endif; ?>
						</div>
					</div>
				</div>
			</div>
			<?php
			break;
		}
	}

	/**
	 * Translate stock form labels so old campaigns saved in English still show
	 * the correct locale on the storefront (and match admin i18n).
	 */
	private static function normalize_form_field_label( string $key, string $label ): string {
		$stock = array(
			'name'       => array( '', 'Name', 'Nombre' ),
			'email'      => array( '', 'Email', 'E-mail', 'Correo electrónico' ),
			'birth_date' => array( '', 'Birth date', 'Date of birth', 'Date of bith', 'Fecha de nacimiento' ),
		);
		$defaults = array(
			'name'       => __( 'Name', 'suitemkt3k' ),
			'email'      => __( 'Email', 'suitemkt3k' ),
			'birth_date' => __( 'Birth date', 'suitemkt3k' ),
		);
		if ( isset( $stock[ $key ] ) && in_array( $label, $stock[ $key ], true ) ) {
			return $defaults[ $key ];
		}
		return '' !== $label ? $label : ( $defaults[ $key ] ?? $label );
	}

	private static function active_for_user(): array {
		static $cache = null;
		if ( null !== $cache ) {
			return $cache;
		}
		$cache = Coupon_Manager::get_active_for_display();
		return $cache;
	}

	private static function format_value( array $coupon ): string {
		$design = $coupon['design'] ?? array();
		if ( isset( $design['value_enabled'] ) && ! $design['value_enabled'] ) {
			return '';
		}
		$type      = (string) $coupon['discount_type'];
		$value     = (float) $coupon['discount_value'];
		$amount    = Coupon_Manager::format_amount( $value, $type );
		if ( 'percent' === $type ) {
			return $amount . '%';
		}
		$currencies = Coupon_Manager::currency_options();
		if ( isset( $currencies[ $type ] ) ) {
			return $amount . ' ' . $currencies[ $type ]['symbol'];
		}
		$symbol = function_exists( 'get_woocommerce_currency_symbol' ) ? html_entity_decode( get_woocommerce_currency_symbol() ) : '€';
		return $amount . ' ' . $symbol;
	}

	private static function hex_rgba( string $hex, float $alpha ): string {
		$alpha = max( 0, min( 1, $alpha ) );
		$hex   = ltrim( $hex, '#' );
		if ( 3 === strlen( $hex ) ) {
			$hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
		}
		if ( 6 !== strlen( $hex ) ) {
			return 'rgba(255,255,255,' . $alpha . ')';
		}
		$r = hexdec( substr( $hex, 0, 2 ) );
		$g = hexdec( substr( $hex, 2, 2 ) );
		$b = hexdec( substr( $hex, 4, 2 ) );
		return sprintf( 'rgba(%d,%d,%d,%s)', $r, $g, $b, $alpha );
	}
}
