<?php
/**
 * Newsletter designer (Alpine.js).
 *
 * Form fields use Alpine.js; the live preview is server-rendered (PHP) and
 * synced via the enqueued wmk-email-preview.js script (WordPress-friendly).
 *
 * @var array|null $campaign
 * @var string     $nonce
 * @package SuiteMkt3k
 */
defined( 'ABSPATH' ) || exit;
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound

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

$defaults = \SuiteMkt3k\Modules\Newsletter\Newsletter_Manager::default_content();
$row      = $campaign ?? array(
	'id'           => 0,
	'name'         => '',
	'subject'      => '',
	'preheader'    => '',
	'template_key' => 'classic',
	'status'       => 'draft',
	'scheduled_at' => '',
	'content'      => $defaults,
);

$content = \SuiteMkt3k\Modules\Newsletter\Newsletter_Manager::merge_content( (array) $row['content'] );
$preset  = \SuiteMkt3k\Email\Newsletter_Template_Presets::get( (string) ( $row['template_key'] ?? 'classic' ) );

$test_status = Sanitizer::get( 'test', 'key' );
$updated     = Sanitizer::flag( INPUT_GET, 'updated' );
$queued      = Sanitizer::flag( INPUT_GET, 'queued' );
$templates   = \SuiteMkt3k\Email\Email_Renderer::public_templates();

$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' ) );

$state = array(
	'name'             => (string) $row['name'],
	'subject'          => (string) $row['subject'] ?: (string) $preset['subject'],
	'template'         => (string) $row['template_key'],
	'preheader'        => (string) $content['preheader'],
	'footer_color'     => (string) ( $content['footer_color'] ?? '#94A3B8' ),
	'heading'          => (string) $content['heading'],
	'accent'           => (string) $content['accent'],
	'header_color'     => (string) ( $content['header_color'] ?? $content['accent'] ),
	'secondary_accent' => (string) ( $content['secondary_accent'] ?? $content['accent'] ),
	'badge_label'      => (string) ( $content['badge_label'] ?? '' ),
	'cta_radius'       => (string) ( $content['cta_radius'] ?? '10' ),
	'body'             => (string) $content['body'],
	'cta_label'        => (string) $content['cta_label'],
	'cta_url'          => (string) $content['cta_url'],
	'image_id'         => (int) ( $content['image_id'] ?? 0 ),
	'image_url'        => (string) $content['image_url'],
	'unsubscribe_text' => (string) $content['unsubscribe_text'],
	'unsubscribe_cta'  => (string) $content['unsubscribe_cta'],
	'logo_url'         => (string) $logo_url,
	'brand'            => (string) $brand,
);

$blog_posts = Rest_Router::published_posts_import_list( 30 );

// Do not embed blogPosts/import payloads in x-data (apostrophes break Alpine; data lives on <option>).
$alpine_payload = wp_json_encode(
	array_merge(
		$state,
		array(
			'importPostId' => '',
		)
	)
);

$preview_data = array_merge(
	$state,
	\SuiteMkt3k\Email\Email_Renderer::footer_context(),
	array(
		'sample_name'              => __( 'there', 'suitemkt3k' ),
		'heading_fallback'         => __( 'Big news from us', 'suitemkt3k' ),
		'body_fallback'            => __( 'Your email body will appear here.', 'suitemkt3k' ),
		'cta_fallback'             => __( 'Discover more', 'suitemkt3k' ),
		'unsubscribe_cta_fallback' => __( 'Unsubscribe', 'suitemkt3k' ),
	)
);
?>

<?php if ( $updated ) : ?><div class="wmk-flash wmk-flash-success"><?php esc_html_e( 'Campaign saved.', 'suitemkt3k' ); ?></div><?php endif; ?>
<?php if ( $queued ) : ?><div class="wmk-flash wmk-flash-success"><?php esc_html_e( 'Campaign queued to send.', '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. Check SMTP settings.', 'suitemkt3k' ); ?></div><?php endif; ?>

<div class="wmk-designer-grid" data-wmk-designer="newsletter" 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'); wmkNewsletterInit($data, $el)">
	<form class="wmk-card" method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
		<input type="hidden" name="action" value="suitemkt3k_newsletter_save">
		<input type="hidden" name="id" value="<?php echo (int) $row['id']; ?>">
		<?php wp_nonce_field( \SuiteMkt3k\Security\Nonces::ADMIN_ACTION ); ?>

		<h3><?php esc_html_e( 'Newsletter designer', 'suitemkt3k' ); ?></h3>
		<p class="wmk-help"><?php esc_html_e( 'Design, schedule and send email campaigns', 'suitemkt3k' ); ?></p>

		<div class="wmk-grid wmk-grid-2">
			<label class="wmk-field"><span><?php esc_html_e( 'Campaign name (internal)', 'suitemkt3k' ); ?></span>
				<input class="wmk-input" name="name" required x-model="name"></label>
			<label class="wmk-field"><span><?php esc_html_e( 'Template', 'suitemkt3k' ); ?></span>
				<select class="wmk-input" name="template_key" x-model="template" @change="applyTemplate()">
					<?php foreach ( $templates as $key => $label ) : ?>
						<option value="<?php echo esc_attr( $key ); ?>" <?php selected( (string) $state['template'], (string) $key ); ?>><?php echo esc_html( $label ); ?></option>
					<?php endforeach; ?>
				</select></label>
			<label class="wmk-field wmk-field-full"><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="content[heading]" x-model="heading"></label>
			<label class="wmk-field"><span><?php esc_html_e( 'Accent color', 'suitemkt3k' ); ?></span>
				<?php \SuiteMkt3k\Admin\UI::color_input( 'content[accent]', (string) $content['accent'], 'x-model="accent"' ); ?>
			</label>
			<label class="wmk-field"><span><?php esc_html_e( 'Top header color', 'suitemkt3k' ); ?></span>
				<?php \SuiteMkt3k\Admin\UI::color_input( 'content[header_color]', (string) ( $content['header_color'] ?? $content['accent'] ), 'x-model="header_color"' ); ?>
				<small class="wmk-help"><?php esc_html_e( 'Background of the brand bar at the top (preview class wmk-pe-header) when no logo is set in Settings.', 'suitemkt3k' ); ?></small>
			</label>
			<label class="wmk-field" x-show="template !== 'classic'" x-cloak><span><?php esc_html_e( 'Badge / label text', 'suitemkt3k' ); ?></span>
				<input class="wmk-input" name="content[badge_label]" x-model="badge_label">
				<small class="wmk-help"><?php esc_html_e( 'Short tag shown at the top of Welcome, Reminder and Announce layouts.', 'suitemkt3k' ); ?></small>
			</label>
			<label class="wmk-field" x-show="template !== 'classic'" x-cloak><span><?php esc_html_e( 'Secondary color', 'suitemkt3k' ); ?></span>
				<?php \SuiteMkt3k\Admin\UI::color_input( 'content[secondary_accent]', (string) ( $content['secondary_accent'] ?? $content['accent'] ), 'x-model="secondary_accent"' ); ?>
				<small class="wmk-help"><?php esc_html_e( 'Badge, borders or announcement title band (not the top header bar).', 'suitemkt3k' ); ?></small>
			</label>
			<div class="wmk-field wmk-field-full wmk-blog-import">
				<span><?php esc_html_e( 'Import from blog post', 'suitemkt3k' ); ?></span>
				<div class="wmk-grid wmk-grid-2" style="align-items:end;">
					<label class="wmk-field">
						<select class="wmk-input" x-model="importPostId" data-wmk-blog-post-select @change="importPostId = $event.target.value">
							<option value=""><?php esc_html_e( '— Select a post —', 'suitemkt3k' ); ?></option>
							<?php foreach ( $blog_posts as $blog_post ) : ?>
								<option value="<?php echo (int) $blog_post['id']; ?>" data-wmk-import="<?php echo esc_attr( wp_json_encode( $blog_post['import'] ) ); ?>"><?php echo esc_html( $blog_post['title'] ); ?></option>
							<?php endforeach; ?>
						</select>
					</label>
					<button type="button" class="wmk-btn wmk-btn-secondary" data-wmk-blog-import-btn onclick="return window.wmkImportBlogPostClick(event)">
						<?php esc_html_e( 'Import title, excerpt & image', 'suitemkt3k' ); ?>
					</button>
				</div>
				<small class="wmk-help"><?php esc_html_e( 'Fills the heading, body (excerpt) and featured image from the selected WordPress post.', 'suitemkt3k' ); ?></small>
			</div>
			<label class="wmk-field wmk-field-full"><span><?php esc_html_e( 'Body (use {{name}} as merge tag)', 'suitemkt3k' ); ?></span>
				<textarea class="wmk-input" name="content[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="content[cta_label]" x-model="cta_label"></label>
			<label class="wmk-field"><span><?php esc_html_e( 'CTA URL', 'suitemkt3k' ); ?></span>
				<input class="wmk-input" type="url" name="content[cta_url]" x-model="cta_url"></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="content[cta_radius]" x-model="cta_radius"></label>
			<div class="wmk-field wmk-field-full">
				<span><?php esc_html_e( 'Image (from media library)', 'suitemkt3k' ); ?></span>
				<input type="hidden" name="content[image_id]" x-model="image_id">
				<input type="hidden" name="content[image_url]" x-model="image_url">
				<div class="wmk-media">
					<template x-if="image_url">
						<img class="wmk-media-preview" :src="image_url" alt="">
					</template>
					<button type="button" class="wmk-btn wmk-btn-ghost" @click.prevent="pickImage()"><?php esc_html_e( 'Choose image', 'suitemkt3k' ); ?></button>
					<template x-if="image_url">
						<button type="button" class="wmk-btn wmk-btn-ghost" @click.prevent="image_id=0; image_url='';"><?php esc_html_e( 'Remove', 'suitemkt3k' ); ?></button>
					</template>
				</div>
			</div>
			<label class="wmk-field wmk-field-full"><span><?php esc_html_e( 'Footer', 'suitemkt3k' ); ?></span>
				<input class="wmk-input" name="content[preheader]" x-model="preheader">
				<small class="wmk-help"><?php esc_html_e( 'Short line shown in the email footer, above the unsubscribe message.', 'suitemkt3k' ); ?></small>
			</label>
			<label class="wmk-field"><span><?php esc_html_e( 'Footer text color', 'suitemkt3k' ); ?></span>
				<?php \SuiteMkt3k\Admin\UI::color_input( 'content[footer_color]', (string) ( $content['footer_color'] ?? '#94A3B8' ), 'x-model="footer_color"' ); ?>
				<small class="wmk-help"><?php esc_html_e( 'Color of the footer line text above the unsubscribe message.', 'suitemkt3k' ); ?></small>
			</label>
			<label class="wmk-field wmk-field-full"><span><?php esc_html_e( 'Unsubscribe sentence', 'suitemkt3k' ); ?></span>
				<input class="wmk-input" name="content[unsubscribe_text]" x-model="unsubscribe_text">
				<small class="wmk-help"><?php esc_html_e( 'Sentence rendered next to the unsubscribe link in the email footer.', 'suitemkt3k' ); ?></small>
			</label>
			<label class="wmk-field"><span><?php esc_html_e( 'Unsubscribe link text', 'suitemkt3k' ); ?></span>
				<input class="wmk-input" name="content[unsubscribe_cta]" x-model="unsubscribe_cta">
				<small class="wmk-help"><?php esc_html_e( 'Clicking this link permanently removes the recipient from the list.', 'suitemkt3k' ); ?></small>
			</label>
		</div>

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

	<div class="wmk-designer-aside">
		<?php if ( $row['id'] ) : ?>
		<div class="wmk-designer-send">
			<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" class="wmk-card wmk-card-soft">
				<input type="hidden" name="action" value="suitemkt3k_newsletter_test">
				<input type="hidden" name="id" value="<?php echo (int) $row['id']; ?>">
				<?php wp_nonce_field( \SuiteMkt3k\Security\Nonces::ADMIN_ACTION ); ?>
				<h4><?php esc_html_e( 'Send a test email', 'suitemkt3k' ); ?></h4>
				<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 class="wmk-form-actions">
					<button class="wmk-btn wmk-btn-secondary" type="submit"><?php esc_html_e( 'Send test', 'suitemkt3k' ); ?></button>
				</div>
			</form>
			<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" class="wmk-card wmk-card-soft" onsubmit="return confirm('<?php echo esc_js( __( 'Queue this campaign for delivery to all active subscribers?', 'suitemkt3k' ) ); ?>')">
				<input type="hidden" name="action" value="suitemkt3k_newsletter_send">
				<input type="hidden" name="id" value="<?php echo (int) $row['id']; ?>">
				<?php wp_nonce_field( \SuiteMkt3k\Security\Nonces::ADMIN_ACTION ); ?>
				<h4><?php esc_html_e( 'Send to all active subscribers', 'suitemkt3k' ); ?></h4>
				<p class="wmk-help"><?php esc_html_e( 'Recipients are queued and dispatched in batches via WP-Cron.', 'suitemkt3k' ); ?></p>
				<div class="wmk-form-actions">
					<button class="wmk-btn wmk-btn-primary" type="submit"><?php esc_html_e( 'Queue and send', 'suitemkt3k' ); ?></button>
				</div>
			</form>
		</div>
		<?php endif; ?>
		<?php Email_Preview_Renderer::newsletter( $preview_data ); ?>
	</div>
</div>
