<?php
/**
 * Cart recovery email template editor + live preview.
 *
 * @package SuiteMkt3k
 */
defined( 'ABSPATH' ) || exit;
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound

use SuiteMkt3k\Admin\Email_Preview_Renderer;
use SuiteMkt3k\Utils\Sanitizer;

$tpl         = \SuiteMkt3k\Modules\Cart_Recovery\Cart_Recovery_Manager::get_template_for_editor();
$test_status = Sanitizer::get( 'test', 'key' );
$updated     = Sanitizer::flag( INPUT_GET, 'updated' );
$design      = \SuiteMkt3k\Modules\Cart_Recovery\Cart_Recovery_Manager::merge_design( (array) ( $tpl['design'] ?? array() ) );

$cart_settings     = (array) \SuiteMkt3k\Modules\Settings\Settings_Manager::get( 'cart', '', array() );
$attached_coupon   = isset( $cart_settings['recovery_coupon_id'] ) ? (int) $cart_settings['recovery_coupon_id'] : 0;
$available_coupons = \SuiteMkt3k\Modules\Coupons\Coupon_Manager::list( 200 );

$attached_meta = null;
if ( $attached_coupon ) {
	foreach ( (array) $available_coupons as $cp ) {
		if ( (int) $cp['id'] === $attached_coupon ) {
			$attached_meta = $cp;
			break;
		}
	}
}
$attached_label = '';
if ( $attached_meta ) {
	$attached_label = 'percent' === $attached_meta['discount_type']
		? ( $attached_meta['discount_value'] . '%' )
		: ( $attached_meta['discount_value'] . ' ' . ( function_exists( 'get_woocommerce_currency_symbol' ) ? html_entity_decode( get_woocommerce_currency_symbol() ) : '€' ) );
}

$company  = (array) \SuiteMkt3k\Modules\Settings\Settings_Manager::get( 'company', '', array() );
$logo_id  = isset( $company['logo_id'] ) ? (int) $company['logo_id'] : 0;
$logo_url = $logo_id ? (string) ( wp_get_attachment_image_url( $logo_id, 'medium' ) ?: '' ) : '';
$brand    = (string) ( $company['name'] ?? get_bloginfo( 'name' ) );

$validity_default = __( 'This discount is valid for {{hours}} hours after the email is sent.', 'suitemkt3k' );
$validity_text    = (string) ( $design['validity_text'] ?? $validity_default );

$state = array(
	'name'                    => (string) ( $tpl['name'] ?? '' ),
	'subject'                 => (string) ( $tpl['subject'] ?? '' ),
	'heading'                 => (string) ( $design['heading'] ?? '' ),
	'preheader'               => (string) ( $design['preheader'] ?? '' ),
	'body'                    => (string) ( $design['body'] ?? '' ),
	'cta_label'               => (string) ( $design['cta_label'] ?? '' ),
	'accent'                  => (string) ( $design['accent'] ?? '#2AB2E5' ),
	'validity_text'           => $validity_text,
	'discount_percent'        => ( null !== ( $tpl['discount_percent'] ?? null ) && '' !== ( $tpl['discount_percent'] ?? '' ) ) ? (string) (float) $tpl['discount_percent'] : '',
	'discount_validity_hours' => (string) ( $tpl['discount_validity_hours'] ?? 24 ),
	'attached_coupon_id'      => (int) $attached_coupon,
	'attached_coupon_label'   => $attached_label,
	'attached_coupon_name'    => $attached_meta ? (string) $attached_meta['name'] : '',
	'unsubscribe_text'        => (string) ( $design['unsubscribe_text'] ?? '' ),
	'unsubscribe_cta'         => (string) ( $design['unsubscribe_cta'] ?? '' ),
	'cta_radius'              => (string) ( $design['cta_radius'] ?? '10' ),
	'logo_url'                => $logo_url,
	'brand'                   => $brand,
);

$alpine_payload = wp_json_encode( $state );

$preview_data = array_merge(
	$state,
	\SuiteMkt3k\Email\Email_Renderer::footer_context(),
	array(
		'sample_name'   => __( 'there', 'suitemkt3k' ),
		'body_fallback' => __( 'Your email body will appear here.', 'suitemkt3k' ),
	)
);
?>
<?php if ( $updated ) : ?><div class="wmk-flash wmk-flash-success"><?php esc_html_e( 'Template saved.', 'suitemkt3k' ); ?></div><?php endif; ?>
<?php if ( 'sent' === $test_status ) : ?><div class="wmk-flash wmk-flash-success"><?php esc_html_e( 'Test email sent.', 'suitemkt3k' ); ?></div><?php endif; ?>
<?php if ( 'failed' === $test_status ) : ?><div class="wmk-flash wmk-flash-error"><?php esc_html_e( 'Test email failed. Verify SMTP settings.', 'suitemkt3k' ); ?></div><?php endif; ?>

<div class="wmk-designer-grid" data-wmk-designer="cart" data-wmk-initial="<?php echo esc_attr( wp_json_encode( $state ) ); ?>">
	<div class="wmk-designer-main wmk-alpine-pending"
		x-data="<?php echo esc_attr( $alpine_payload ); ?>"
		x-init="$el.classList.remove('wmk-alpine-pending')">
	<form class="wmk-card" method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
		<input type="hidden" name="action" value="suitemkt3k_cart_template_save">
		<input type="hidden" name="id" value="<?php echo esc_attr( (string) (int) ( $tpl['id'] ?? 0 ) ); ?>">
		<input type="hidden" name="is_default" value="1">
		<?php wp_nonce_field( \SuiteMkt3k\Security\Nonces::ADMIN_ACTION ); ?>

		<h3><?php esc_html_e( 'Edit recovery email template', 'suitemkt3k' ); ?></h3>
		<p class="wmk-help"><?php esc_html_e( 'Recover lost sales with personalised emails and discount coupons', 'suitemkt3k' ); ?></p>

		<div class="wmk-grid wmk-grid-2">
			<label class="wmk-field"><span><?php esc_html_e( 'Template name', 'suitemkt3k' ); ?></span>
				<input class="wmk-input" name="name" x-model="name"></label>
			<label class="wmk-field"><span><?php esc_html_e( 'Subject', 'suitemkt3k' ); ?></span>
				<input class="wmk-input" name="subject" required x-model="subject"></label>
			<label class="wmk-field"><span><?php esc_html_e( 'Heading', 'suitemkt3k' ); ?></span>
				<input class="wmk-input" name="design[heading]" x-model="heading"></label>
			<label class="wmk-field wmk-field-full"><span><?php esc_html_e( 'Body (you can use {{name}})', 'suitemkt3k' ); ?></span>
				<textarea class="wmk-input" name="design[body]" rows="6" x-model="body"></textarea></label>
			<label class="wmk-field"><span><?php esc_html_e( 'CTA label', 'suitemkt3k' ); ?></span>
				<input class="wmk-input" name="design[cta_label]" x-model="cta_label"></label>
			<label class="wmk-field"><span><?php esc_html_e( 'Accent color', 'suitemkt3k' ); ?></span>
				<?php \SuiteMkt3k\Admin\UI::color_input( 'design[accent]', (string) ( $design['accent'] ?? '#2AB2E5' ), 'x-model="accent"' ); ?>
			</label>
			<label class="wmk-field wmk-field-narrow"><span><?php esc_html_e( 'CTA border radius', 'suitemkt3k' ); ?></span>
				<input class="wmk-input" type="number" min="0" max="99" name="design[cta_radius]" x-model="cta_radius"></label>
			<label class="wmk-field wmk-field-full"><span><?php esc_html_e( 'Intro line', 'suitemkt3k' ); ?></span>
				<input class="wmk-input" name="design[preheader]" x-model="preheader">
				<small class="wmk-help"><?php esc_html_e( 'Short line shown below the CTA button (e.g. “Your cart is waiting for you”).', 'suitemkt3k' ); ?></small>
			</label>
			<label class="wmk-field wmk-field-full"><span><?php esc_html_e( 'Unsubscribe sentence', 'suitemkt3k' ); ?></span>
				<input class="wmk-input" name="design[unsubscribe_text]" x-model="unsubscribe_text"></label>
			<label class="wmk-field"><span><?php esc_html_e( 'Unsubscribe link text', 'suitemkt3k' ); ?></span>
				<input class="wmk-input" name="design[unsubscribe_cta]" x-model="unsubscribe_cta"></label>
		</div>

		<h4 style="margin-top:18px;"><?php esc_html_e( 'Coupon attached to recovery emails', 'suitemkt3k' ); ?></h4>
		<label class="wmk-field wmk-field-full">
			<span><?php esc_html_e( 'Coupon to attach (optional)', 'suitemkt3k' ); ?></span>
			<select class="wmk-input" name="recovery_coupon_id" x-model.number="attached_coupon_id"
				@change="attached_coupon_name = $event.target.selectedOptions[0]?.dataset.name || ''; attached_coupon_label = $event.target.selectedOptions[0]?.dataset.label || ''; if (attached_coupon_id > 0) { discount_percent = ''; } if (typeof wmkSyncEmailPreview === 'function') { wmkSyncEmailPreview(); }">
				<option value="0" data-label="" data-name=""><?php esc_html_e( '— No coupon attached —', 'suitemkt3k' ); ?></option>
				<?php foreach ( (array) $available_coupons as $cp ) :
					if ( \SuiteMkt3k\Modules\Coupons\Coupon_Manager::STATUS_ACTIVE !== (string) ( $cp['status'] ?? '' ) ) {
						continue;
					}
					$label = 'percent' === $cp['discount_type']
						? ( $cp['discount_value'] . '%' )
						: ( $cp['discount_value'] . ' ' . ( function_exists( 'get_woocommerce_currency_symbol' ) ? html_entity_decode( get_woocommerce_currency_symbol() ) : '€' ) );
					?>
					<option value="<?php echo (int) $cp['id']; ?>"
						data-name="<?php echo esc_attr( (string) $cp['name'] ); ?>"
						data-label="<?php echo esc_attr( $label ); ?>"
						<?php selected( $attached_coupon, (int) $cp['id'] ); ?>>
						#<?php echo (int) $cp['id']; ?> · <?php echo esc_html( (string) $cp['name'] ); ?> (<?php echo esc_html( $label ); ?>)
					</option>
				<?php endforeach; ?>
			</select>
			<small class="wmk-help"><?php esc_html_e( 'When set, the coupon code, type and amount of this coupon will be used in the email and the "Optional discount %" field below will be ignored.', 'suitemkt3k' ); ?></small>
		</label>

		<div class="wmk-grid wmk-grid-2">
			<label class="wmk-field" :class="attached_coupon_id ? 'wmk-field-disabled' : ''">
				<span><?php esc_html_e( 'Optional discount % to attach', 'suitemkt3k' ); ?></span>
				<input class="wmk-input" type="number" step="0.5" min="0" max="99" name="discount_percent" x-model="discount_percent" :readonly="attached_coupon_id > 0" @input="if (discount_percent) { attached_coupon_id = 0; attached_coupon_name = ''; attached_coupon_label = ''; }">
				<small class="wmk-help" x-show="attached_coupon_id > 0" x-cloak>
					<?php esc_html_e( 'A coupon is already attached — this field will be ignored.', 'suitemkt3k' ); ?>
				</small>
			</label>
			<label class="wmk-field" :class="!discount_percent || attached_coupon_id ? 'wmk-field-disabled' : ''">
				<span><?php esc_html_e( 'Discount validity (hours)', 'suitemkt3k' ); ?></span>
				<input class="wmk-input" type="number" min="1" max="720" name="discount_validity_hours" x-model="discount_validity_hours" :readonly="!discount_percent || attached_coupon_id > 0">
				<small class="wmk-help" x-show="attached_coupon_id > 0 || !discount_percent" x-cloak>
					<?php esc_html_e( 'Only applies when using the optional discount % above (not when a coupon is attached).', 'suitemkt3k' ); ?>
				</small>
			</label>
			<label class="wmk-field wmk-field-full"><span><?php esc_html_e( 'Validity sentence shown in the email', 'suitemkt3k' ); ?></span>
				<input class="wmk-input" type="text" name="design[validity_text]" x-model="validity_text">
				<small class="wmk-help"><?php esc_html_e( 'Available placeholders: {{hours}}, {{code}}, {{amount}}.', 'suitemkt3k' ); ?></small>
			</label>
			<p class="wmk-help wmk-field-full"><?php esc_html_e( 'This template is used for all automatic cart recovery emails.', 'suitemkt3k' ); ?></p>
		</div>

		<div class="wmk-form-actions">
			<a class="wmk-btn wmk-btn-ghost" href="<?php echo esc_url( admin_url( 'admin.php?page=suitemkt3k-cart-recovery' ) ); ?>"><?php esc_html_e( 'Back to list', 'suitemkt3k' ); ?></a>
			<button class="wmk-btn wmk-btn-primary" type="submit"><?php esc_html_e( 'Save template', 'suitemkt3k' ); ?></button>
		</div>
	</form>
	</div>

	<?php Email_Preview_Renderer::cart_recovery( $preview_data ); ?>
</div>

<form class="wmk-card wmk-card-soft" method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" style="margin-top:20px;">
	<input type="hidden" name="action" value="suitemkt3k_cart_test_email">
	<?php wp_nonce_field( \SuiteMkt3k\Security\Nonces::ADMIN_ACTION ); ?>
	<h4><?php esc_html_e( 'Send a test of this template', 'suitemkt3k' ); ?></h4>
	<div class="wmk-grid wmk-grid-2">
		<label class="wmk-field"><span><?php esc_html_e( 'Recipient', 'suitemkt3k' ); ?></span>
			<input class="wmk-input" type="email" name="test_email" value="<?php echo esc_attr( get_option( 'admin_email' ) ); ?>" required></label>
	</div>
	<input type="hidden" name="payload" value="<?php echo esc_attr( wp_json_encode( $tpl ) ); ?>">
	<div class="wmk-form-actions">
		<button class="wmk-btn wmk-btn-secondary" type="submit"><?php esc_html_e( 'Send test email', 'suitemkt3k' ); ?></button>
	</div>
</form>
