<?php
/**
 * Opt-in coupon email template (stored in plugin settings).
 *
 * @package SuiteMkt3k
 */

namespace SuiteMkt3k\Modules\Coupons;

use SuiteMkt3k\Compat\WooCommerce_Check;
use SuiteMkt3k\Email\Email_Renderer;
use SuiteMkt3k\Email\Mailer;
use SuiteMkt3k\Modules\Settings\Settings_Manager;
use SuiteMkt3k\Modules\Subscribers\Subscriber_Manager;
use SuiteMkt3k\Security\Capabilities;
use SuiteMkt3k\Security\Nonces;
use SuiteMkt3k\Utils\Sanitizer;
use SuiteMkt3k\Utils\Validator;

defined( 'ABSPATH' ) || exit;

final class Coupon_Email_Template_Manager {

	public const SETTINGS_KEY = 'coupon_email';

	public static function register(): void {
		add_action( 'admin_post_suitemkt3k_coupon_email_template_save', array( __CLASS__, 'handle_save' ) );
		add_action( 'admin_post_suitemkt3k_coupon_email_test', array( __CLASS__, 'handle_test_email' ) );
	}

	/**
	 * @return array<string, mixed>
	 */
	public static function default_design(): array {
		return array(
			'heading'          => __( 'Here is your coupon: {{coupon_name}}', 'suitemkt3k' ),
			'preheader'        => __( 'Your discount is ready', 'suitemkt3k' ),
			'inbox_preview'    => __( 'Your discount is ready', 'suitemkt3k' ),
			'body'             => "{{marketing}}\n\n" . __( 'Use the code: <strong>{{code}}</strong>', 'suitemkt3k' ),
			'cta_label'        => __( 'Shop now', 'suitemkt3k' ),
			'accent'           => '#2AB2E5',
			'cta_radius'       => '10',
			'unsubscribe_text' => __( 'You no longer want to receive emails like this?', 'suitemkt3k' ),
			'unsubscribe_cta'  => __( 'Unsubscribe', 'suitemkt3k' ),
		);
	}

	/**
	 * @return array<string, mixed>
	 */
	public static function get_template(): array {
		$stored = (array) Settings_Manager::get( self::SETTINGS_KEY, '', array() );
		$design = self::merge_design( (array) ( $stored['design'] ?? array() ) );
		return array(
			'subject' => (string) ( $stored['subject'] ?? self::default_subject() ),
			'design'  => $design,
		);
	}

	public static function default_subject(): string {
		/* translators: %s: site name. */
		return sprintf( __( 'Your coupon — %s', 'suitemkt3k' ), get_bloginfo( 'name' ) );
	}

	/**
	 * @param array<string, mixed> $saved
	 * @return array<string, mixed>
	 */
	public static function merge_design( array $saved ): array {
		$design = self::default_design();
		foreach ( $saved as $key => $value ) {
			if ( is_string( $value ) && '' === trim( $value ) ) {
				continue;
			}
			$design[ $key ] = $value;
		}
		return $design;
	}

	/**
	 * @param array<string, mixed> $data
	 */
	public static function save_template( array $data ): void {
		$design = isset( $data['design'] ) && is_array( $data['design'] )
			? self::merge_design( Sanitizer::recursive_text( $data['design'] ) )
			: self::default_design();

		$all = Settings_Manager::all();
		$all[ self::SETTINGS_KEY ] = array(
			'subject' => Sanitizer::text( $data['subject'] ?? self::default_subject(), 255 ),
			'design'  => $design,
		);
		update_option( Settings_Manager::OPTION, $all, false );
	}

	/**
	 * @param array<string, mixed>      $coupon
	 * @param array<string, mixed>|null $subscriber
	 */
	public static function render_html( array $coupon, ?array $subscriber = null, bool $is_test = false ): string {
		$tpl    = self::get_template();
		$design = $tpl['design'];

		$wc_post = get_post( (int) ( $coupon['wc_coupon_id'] ?? 0 ) );
		$code    = $wc_post ? (string) $wc_post->post_title : (string) ( $coupon['name'] ?? 'SAMPLE' );
		if ( $is_test && '' === $code ) {
			$code = 'SAMPLE10';
		}

		$coupon_design = (array) ( $coupon['design'] ?? array() );
		$accent        = (string) ( $design['accent'] ?? ( $coupon_design['bg_color'] ?? '#2AB2E5' ) );

		$name = '';
		if ( $subscriber ) {
			$name = trim( (string) ( $subscriber['name'] ?? '' ) );
		}
		if ( '' === $name ) {
			$name = __( 'there', 'suitemkt3k' );
		}

		$marketing = trim( (string) ( $coupon['marketing_text'] ?? '' ) );
		if ( $is_test && '' === $marketing ) {
			$marketing = __( 'Thanks for signing up! Here is your exclusive discount.', 'suitemkt3k' );
		}

		$replacements = array(
			'{{name}}'        => $name,
			'{{first_name}}'  => $name,
			'{{code}}'        => esc_html( $code ),
			'{{coupon_name}}' => esc_html( (string) ( $coupon['name'] ?? __( 'Sample campaign', 'suitemkt3k' ) ) ),
			'{{marketing}}'   => $marketing,
		);

		$heading = strtr( (string) ( $design['heading'] ?? '' ), $replacements );
		$body    = strtr( (string) ( $design['body'] ?? '' ), $replacements );
		$body    = preg_replace( "/\n{3,}/", "\n\n", (string) $body ) ?? $body;

		$intro = (string) ( $design['preheader'] ?? '' );
		$inbox = (string) ( $design['inbox_preview'] ?? $intro );

		$unsub_url = '';
		if ( $subscriber && ! empty( $subscriber['unsubscribe_token'] ) ) {
			$unsub_url = Subscriber_Manager::unsubscribe_url( (string) $subscriber['unsubscribe_token'] );
		}

		return Email_Renderer::render(
			'classic',
			array_merge(
				Email_Renderer::footer_context(),
				array(
					'heading'          => $heading,
					'intro_line'       => $intro,
					'inbox_preview'    => $inbox,
					'body'             => $body,
					'cta_label'        => (string) ( $design['cta_label'] ?? __( 'Shop now', 'suitemkt3k' ) ),
					'cta_url'          => WooCommerce_Check::shop_url(),
					'accent'           => $accent,
					'header_color'     => $accent,
					'cta_radius'       => (int) ( $design['cta_radius'] ?? 10 ),
					'unsubscribe_url'  => $unsub_url,
					'unsubscribe_text' => (string) ( $design['unsubscribe_text'] ?? '' ),
					'unsubscribe_cta'  => (string) ( $design['unsubscribe_cta'] ?? __( 'Unsubscribe', 'suitemkt3k' ) ),
				)
			)
		);
	}

	public static function handle_save(): void {
		Capabilities::ensure( Capabilities::EDIT_CAMPAIGN );
		check_admin_referer( Nonces::ADMIN_ACTION, '_wpnonce' );

		$design = Sanitizer::post_array( 'design' );

		self::save_template(
			array(
				'subject' => Sanitizer::post( 'subject', 'text' ),
				'design'  => $design,
			)
		);

		wp_safe_redirect(
			add_query_arg(
				array(
					'page'    => 'suitemkt3k-coupons',
					'view'    => 'email_template',
					'updated' => '1',
				),
				admin_url( 'admin.php' )
			)
		);
		exit;
	}

	public static function handle_test_email(): void {
		Capabilities::ensure( Capabilities::EDIT_CAMPAIGN );
		check_admin_referer( Nonces::ADMIN_ACTION, '_wpnonce' );

		$to = Sanitizer::email( Sanitizer::post( 'test_email', 'email' ) );
		if ( '' === $to || ! Validator::is_valid_email( $to ) ) {
			wp_safe_redirect(
				add_query_arg(
					array(
						'page' => 'suitemkt3k-coupons',
						'view' => 'email_template',
						'test' => 'failed',
					),
					admin_url( 'admin.php' )
				)
			);
			exit;
		}

		$tpl    = self::get_template();
		$sample = array(
			'name'            => __( 'Sample campaign', 'suitemkt3k' ),
			'marketing_text'  => __( 'Thanks for signing up! Here is your exclusive discount.', 'suitemkt3k' ),
			'wc_coupon_id'    => 0,
			'design'          => array( 'bg_color' => $tpl['design']['accent'] ?? '#2AB2E5' ),
		);

		$html = self::render_html( $sample, null, true );
		$ok   = ( new Mailer() )->send(
			array(
				'to'      => $to,
				'subject' => '[TEST] ' . (string) ( $tpl['subject'] ?? self::default_subject() ),
				'html'    => $html,
				'context' => 'coupon_email_test',
			)
		);

		wp_safe_redirect(
			add_query_arg(
				array(
					'page' => 'suitemkt3k-coupons',
					'view' => 'email_template',
					'test' => $ok ? 'sent' : 'failed',
				),
				admin_url( 'admin.php' )
			)
		);
		exit;
	}
}
