<?php
/**
 * Customize WP Emails - Template Design Page
 * PowerSuite style: header row, card panels.
 *
 * @var array $template
 * @var string $preview_html
 * @var array $default_colors
 */
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use WP_PowerSuite\Admin\PageHero;
use WP_PowerSuite\Core\NetworkScope;

$list_url = NetworkScope::adminUrl( 'admin.php', [ 'page' => 'powersuite-custom-wp-emails' ] );
$default_colors = $default_colors ?? [
	'body_bg'              => '#f3f4f6',
	'content_bg'           => '#ffffff',
	'content_color'        => '#374151',
	'footer_content_color' => '#6b7280',
	'highlight_bg'         => '#f9fafb',
	'highlight_color'      => '#374151',
];
// Normalize color for native input (must be #rrggbb).
$normalize_color = function ( $val ) {
	if ( empty( $val ) ) {
		return '#f3f4f6';
	}
	if ( preg_match( '/^#([a-fA-F0-9]{3}|[a-fA-F0-9]{6}|[a-fA-F0-9]{8})$/', $val ) ) {
		return strlen( $val ) > 7 ? substr( $val, 0, 7 ) : $val;
	}
	if ( preg_match( '/^rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/', $val, $m ) ) {
		return sprintf( '#%02x%02x%02x', (int) $m[1], (int) $m[2], (int) $m[3] );
	}
	return $val;
};
?>
<div class="wrap wpps-cwe-wrap">
	<hr class="wp-header-end" style="margin:0;padding:0;border:none;height:0;overflow:hidden;">

	<?php if ( isset( $_GET['saved'] ) ) : ?>
		<div class="notice notice-success is-dismissible"><p><?php esc_html_e( 'Template settings saved.', 'wp-powersuite' ); ?></p></div>
	<?php endif; ?>

	<?php
	PageHero::render_for_module(
		[
			'icon'    => 'dashicons-admin-appearance',
			'title'   => __( 'Email Template Design', 'wp-powersuite' ),
			'tagline' => __( 'Set colors, footer text, and sender fields. These apply to emails set to Customized Content—not to System Default emails.', 'wp-powersuite' ),
			'actions' => [
				[
					'label' => __( 'All emails', 'wp-powersuite' ),
					'url'   => $list_url,
					'icon'  => 'dashicons-arrow-left-alt',
				],
			],
		]
	);
	?>

	<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" id="wpps-template-design-form" data-wpps-unsaved-form="1">
		<input type="hidden" name="action" value="wpps_custom_wp_emails_save_template" />
		<input type="hidden" name="return_to" value="template" />
		<?php wp_nonce_field( 'wpps_custom_wp_emails_template' ); ?>

		<!-- Template Design - Logo, Colors, Font -->
		<div class="wpps-cwe-panel">
			<h2 class="wpps-cwe-section-title"><?php esc_html_e( 'Template Design', 'wp-powersuite' ); ?></h2>
			<table class="form-table">
				<tr>
					<td colspan="2">
						<div class="wpps-cwe-logo-font-row">
							<div class="wpps-cwe-field-cell">
								<label for="cwe_logo" class="wpps-cwe-color-label"><?php esc_html_e( 'Logo', 'wp-powersuite' ); ?></label>
								<div class="wpps-cwe-logo-wrap">
									<div class="wpps-cwe-logo-preview" style="<?php echo ! empty( $template['logo'] ) ? 'display:block;' : 'display:none;'; ?>">
										<img id="cwe_logo_preview" src="<?php echo esc_url( $template['logo'] ?? '' ); ?>" alt="" style="max-width:200px;max-height:60px;display:block;" />
									</div>
									<input type="hidden" name="logo" id="cwe_logo" value="<?php echo esc_attr( $template['logo'] ?? '' ); ?>" />
									<button type="button" class="button button-secondary wpps-cwe-upload-logo"><?php esc_html_e( 'Select Logo', 'wp-powersuite' ); ?></button>
									<button type="button" class="button button-secondary wpps-cwe-remove-logo" style="<?php echo empty( $template['logo'] ) ? 'display:none;' : ''; ?>"><?php esc_html_e( 'Remove', 'wp-powersuite' ); ?></button>
								</div>
								<p class="description" style="margin-top:6px;"><?php esc_html_e( 'Optional. Displayed at the top of emails.', 'wp-powersuite' ); ?></p>
							</div>
							<div class="wpps-cwe-field-cell">
								<label for="font_family" class="wpps-cwe-color-label"><?php esc_html_e( 'Font Family', 'wp-powersuite' ); ?></label>
								<select name="font_family" id="font_family" class="wpps-cwe-input" style="max-width:280px;">
									<option value=""><?php esc_html_e( 'Default (system fonts)', 'wp-powersuite' ); ?></option>
									<option value="Arial, sans-serif" <?php selected( $template['font_family'] ?? '', 'Arial, sans-serif' ); ?>>Arial</option>
									<option value="Georgia, serif" <?php selected( $template['font_family'] ?? '', 'Georgia, serif' ); ?>>Georgia</option>
									<option value="'Times New Roman', serif" <?php selected( $template['font_family'] ?? '', "'Times New Roman', serif" ); ?>>Times New Roman</option>
									<option value="Verdana, sans-serif" <?php selected( $template['font_family'] ?? '', 'Verdana, sans-serif' ); ?>>Verdana</option>
									<option value="'Helvetica Neue', Helvetica, sans-serif" <?php selected( $template['font_family'] ?? '', "'Helvetica Neue', Helvetica, sans-serif" ); ?>>Helvetica</option>
									<option value="Tahoma, sans-serif" <?php selected( $template['font_family'] ?? '', 'Tahoma, sans-serif' ); ?>>Tahoma</option>
								</select>
							</div>
						</div>
					</td>
				</tr>
				<?php
				$color_fields = [
					'body_bg'              => __( 'Body Background Color', 'wp-powersuite' ),
					'content_bg'           => __( 'Content Background Color', 'wp-powersuite' ),
					'content_color'        => __( 'Content Text Color', 'wp-powersuite' ),
					'highlight_bg'         => __( 'Highlight Background', 'wp-powersuite' ),
					'highlight_color'      => __( 'Highlight Text Color', 'wp-powersuite' ),
					'footer_content_color' => __( 'Footer Text Color', 'wp-powersuite' ),
				];
				?>
				<tr>
					<td colspan="2">
						<div class="wpps-cwe-color-grid">
						<?php foreach ( $color_fields as $key => $label ) :
							$val     = $template[ $key ] ?? $default_colors[ $key ];
							$hex_val = $normalize_color( $val );
							$def     = $normalize_color( $default_colors[ $key ] );
							?>
							<div class="wpps-cwe-color-cell">
								<label for="cwe_<?php echo esc_attr( $key ); ?>" class="wpps-cwe-color-label"><?php echo esc_html( $label ); ?></label>
								<div class="wpps-color-field-row">
									<input type="color" id="cwe_<?php echo esc_attr( $key ); ?>" name="<?php echo esc_attr( $key ); ?>" value="<?php echo esc_attr( $hex_val ); ?>" class="wpps-color-picker-circle wpps-cwe-color" data-default-color="<?php echo esc_attr( $def ); ?>" aria-label="<?php echo esc_attr( $label ); ?>" />
									<div class="wpps-color-code-wrap">
										<input type="text" class="wpps-color-code-input wpps-cwe-input" data-color-input="cwe_<?php echo esc_attr( $key ); ?>" data-default-color="<?php echo esc_attr( $def ); ?>" value="<?php echo esc_attr( $hex_val ); ?>" style="width: 100px; padding-right: 25px;" placeholder="<?php echo esc_attr( $def ); ?>" maxlength="9" />
										<button type="button" class="wpps-color-reset button-link" data-default-color="<?php echo esc_attr( $def ); ?>" aria-label="<?php esc_attr_e( 'Reset to default', 'wp-powersuite' ); ?>"><span class="dashicons dashicons-undo" style="font-size: 16px; width: 16px; height: 16px;"></span></button>
									</div>
								</div>
							</div>
						<?php endforeach; ?>
						</div>
					</td>
				</tr>
			</table>
			<div class="wpps-cwe-actions">
				<button type="submit" class="button button-primary"><?php esc_html_e( 'Save Settings', 'wp-powersuite' ); ?></button>
			</div>
		</div>

		<!-- Preview Section -->
		<div class="wpps-cwe-panel">
			<div class="wpps-cwe-preview-toolbar">
				<h2 class="wpps-cwe-section-title">
					<?php esc_html_e( 'Preview', 'wp-powersuite' ); ?>
					<button type="button" class="button button-secondary wpps-preview-toggle" style="margin-left:10px;">
						<span class="wpps-preview-toggle-text"><?php esc_html_e( 'Hide Preview', 'wp-powersuite' ); ?></span>
					</button>
				</h2>
				<div class="wpps-cwe-preview-toolbar-actions">
					<button type="button" class="button button-secondary wpps-set-default-template"><?php esc_html_e( 'Set Default', 'wp-powersuite' ); ?></button>
					<button type="button" class="button button-secondary wpps-refresh-preview"><?php esc_html_e( 'Refresh Preview', 'wp-powersuite' ); ?></button>
				</div>
			</div>
			<div class="wpps-preview-container">
				<iframe id="wpps-email-preview" class="wpps-cwe-preview-frame" title="<?php esc_attr_e( 'Email preview', 'wp-powersuite' ); ?>"></iframe>
			</div>
			<script>
			(function(){var f=document.getElementById('wpps-email-preview');if(f)f.srcdoc=<?php echo wp_json_encode( $preview_html ); ?>;})();
			</script>
		</div>

		<!-- Footer Text -->
		<div class="wpps-cwe-panel">
			<h2 class="wpps-cwe-section-title"><?php esc_html_e( 'Footer Text', 'wp-powersuite' ); ?></h2>
			<?php
			wp_editor(
				$template['footer_text'] ?? '',
				'footer_text',
				[
					'textarea_name' => 'footer_text',
					'textarea_rows' => 8,
					'media_buttons' => true,
					'teeny'         => false,
					'quicktags'     => true,
					'tinymce'       => [
						'toolbar1' => 'formatselect,fontselect,fontsizeselect,bold,italic,underline,strikethrough,bullist,numlist,blockquote,alignleft,aligncenter,alignright,link,unlink,forecolor,removeformat',
					],
				]
			);
			?>
			<div class="wpps-cwe-actions">
				<button type="submit" class="button button-primary"><?php esc_html_e( 'Save Settings', 'wp-powersuite' ); ?></button>
			</div>
		</div>

		<!-- Email Sender Settings -->
		<div class="wpps-cwe-panel">
			<h2 class="wpps-cwe-section-title"><?php esc_html_e( 'Email Sender', 'wp-powersuite' ); ?></h2>
			<div class="wpps-cwe-sender-grid">
				<div class="wpps-cwe-sender-cell">
					<label for="from_email" class="wpps-cwe-sender-label"><?php esc_html_e( 'Send from email (optional)', 'wp-powersuite' ); ?></label>
					<input type="email" name="from_email" id="from_email" value="<?php echo esc_attr( $template['from_email'] ?? '' ); ?>" class="regular-text wpps-cwe-input" placeholder="<?php esc_attr_e( 'Enter email address', 'wp-powersuite' ); ?>" />
				</div>
				<div class="wpps-cwe-sender-cell">
					<label for="from_name" class="wpps-cwe-sender-label"><?php esc_html_e( 'Send from name (optional)', 'wp-powersuite' ); ?></label>
					<input type="text" name="from_name" id="from_name" value="<?php echo esc_attr( $template['from_name'] ?? '' ); ?>" class="regular-text wpps-cwe-input" placeholder="<?php esc_attr_e( 'Enter from name', 'wp-powersuite' ); ?>" />
				</div>
				<div class="wpps-cwe-sender-cell">
					<label for="reply_to_email" class="wpps-cwe-sender-label"><?php esc_html_e( 'Reply to email (optional)', 'wp-powersuite' ); ?></label>
					<input type="email" name="reply_to_email" id="reply_to_email" value="<?php echo esc_attr( $template['reply_to_email'] ?? '' ); ?>" class="regular-text wpps-cwe-input" placeholder="<?php esc_attr_e( 'Enter reply email address', 'wp-powersuite' ); ?>" />
				</div>
				<div class="wpps-cwe-sender-cell">
					<label for="reply_to_name" class="wpps-cwe-sender-label"><?php esc_html_e( 'Reply to name (optional)', 'wp-powersuite' ); ?></label>
					<input type="text" name="reply_to_name" id="reply_to_name" value="<?php echo esc_attr( $template['reply_to_name'] ?? '' ); ?>" class="regular-text wpps-cwe-input" placeholder="<?php esc_attr_e( 'Enter reply to name', 'wp-powersuite' ); ?>" />
				</div>
			</div>
			<div class="wpps-cwe-actions">
				<button type="submit" class="button button-primary"><?php esc_html_e( 'Save Settings', 'wp-powersuite' ); ?></button>
			</div>
		</div>
	</form>
</div>

<script>
(function() {
	var nonce = '<?php echo esc_js( wp_create_nonce( 'wpps_custom_wp_emails' ) ); ?>';
	var previewVisible = true;

	// Unsaved changes warning
	var form = document.getElementById('wpps-template-design-form');
	if (form) {
		var dirty = false;
		form.addEventListener('input', function() { dirty = true; });
		form.addEventListener('change', function() { dirty = true; });
		form.addEventListener('submit', function() { dirty = false; });
		window.addEventListener('beforeunload', function(e) {
			if (dirty) {
				e.preventDefault();
				e.returnValue = '';
			}
		});
	}

	document.querySelectorAll('.wpps-color-reset').forEach(function(btn) {
		btn.addEventListener('click', function() {
			var def = this.getAttribute('data-default-color');
			var row = this.closest('.wpps-color-field-row');
			if (!row) return;
			var circle = row.querySelector('.wpps-color-picker-circle');
			var hex = row.querySelector('.wpps-color-code-input');
			if (circle) circle.value = def;
			if (hex) hex.value = def;
			refreshPreview();
		});
	});

	// Preview toggle
	document.querySelector('.wpps-preview-toggle')?.addEventListener('click', function() {
		previewVisible = !previewVisible;
		var container = document.querySelector('.wpps-preview-container');
		var btn = document.querySelector('.wpps-preview-toggle-text');
		if (container && btn) {
			container.style.display = previewVisible ? '' : 'none';
			btn.textContent = previewVisible ? '<?php echo esc_js( __( 'Hide Preview', 'wp-powersuite' ) ); ?>' : '<?php echo esc_js( __( 'Show Preview', 'wp-powersuite' ) ); ?>';
		}
	});

	document.querySelector('.wpps-set-default-template')?.addEventListener('click', function() {
		var defaults = <?php echo wp_json_encode( array_map( function ( $v ) use ( $normalize_color ) { return $normalize_color( $v ); }, $default_colors ) ); ?>;
		var keys = ['body_bg','content_bg','content_color','highlight_bg','highlight_color','footer_content_color'];
		keys.forEach(function(key) {
			var def = defaults[key];
			if (!def) return;
			var circle = document.getElementById('cwe_' + key);
			var hex = document.querySelector('.wpps-color-code-input[data-color-input="cwe_' + key + '"]');
			if (circle) circle.value = def;
			if (hex) hex.value = def;
		});
		if (typeof tinymce !== 'undefined') {
			var ed = tinymce.get('footer_text');
			if (ed) ed.setContent('');
		}
		var logoInp = document.getElementById('cwe_logo');
		if (logoInp) logoInp.value = '';
		var logoPrev = document.querySelector('.wpps-cwe-logo-preview');
		if (logoPrev) logoPrev.style.display = 'none';
		var removeBtn = document.querySelector('.wpps-cwe-remove-logo');
		if (removeBtn) removeBtn.style.display = 'none';
		document.getElementById('font_family').value = '';
		document.querySelector('input[name="from_name"]').value = '';
		document.querySelector('input[name="from_email"]').value = '';
		document.querySelector('input[name="reply_to_name"]').value = '';
		document.querySelector('input[name="reply_to_email"]').value = '';
		refreshPreview();
	});

	// Logo upload
	var cweMediaFrame;
	document.querySelector('.wpps-cwe-upload-logo')?.addEventListener('click', function() {
		if (cweMediaFrame) { cweMediaFrame.open(); return; }
		cweMediaFrame = wp.media({
			title: '<?php echo esc_js( __( 'Select Logo', 'wp-powersuite' ) ); ?>',
			library: { type: 'image' },
			button: { text: '<?php echo esc_js( __( 'Use this image', 'wp-powersuite' ) ); ?>' },
			multiple: false
		});
		cweMediaFrame.on('select', function() {
			var att = cweMediaFrame.state().get('selection').first().toJSON();
			document.getElementById('cwe_logo').value = att.url;
			var prev = document.getElementById('cwe_logo_preview');
			if (prev) { prev.src = att.url; prev.closest('.wpps-cwe-logo-preview').style.display = 'block'; }
			document.querySelector('.wpps-cwe-remove-logo').style.display = '';
			refreshPreview();
		});
		cweMediaFrame.open();
	});
	document.querySelector('.wpps-cwe-remove-logo')?.addEventListener('click', function() {
		document.getElementById('cwe_logo').value = '';
		var prev = document.getElementById('cwe_logo_preview');
		if (prev) prev.closest('.wpps-cwe-logo-preview').style.display = 'none';
		this.style.display = 'none';
		refreshPreview();
	});

	function refreshPreview() {
		var form = document.getElementById('wpps-template-design-form');
		var previewEl = document.getElementById('wpps-email-preview');
		if (!form || !previewEl) return;
		if (typeof tinymce !== 'undefined') {
			tinymce.triggerSave();
		}
		form.querySelectorAll('.wpps-color-code-input').forEach(function(hexInp) {
			var hex = (hexInp.value || '').trim();
			if (hex.indexOf('#') !== 0) hex = '#' + hex;
			if (/^#([A-Fa-f0-9]{3}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{8})$/.test(hex)) {
				var colorId = hexInp.getAttribute('data-color-input');
				var circle = colorId ? document.getElementById(colorId) : null;
				if (circle) circle.value = hex.length > 7 ? hex.substring(0, 7) : hex;
			}
		});
		var data = new FormData(form);
		data.append('action', 'wpps_custom_wp_emails_template_preview');
		data.append('nonce', nonce);
		var loadingHtml = '<p style="padding:20px;text-align:center;color:#666;"><em><?php echo esc_js( __( 'Loading preview...', 'wp-powersuite' ) ); ?></em></p>';
		previewEl.srcdoc = loadingHtml;
		fetch(ajaxurl, { method: 'POST', body: data })
			.then(function(r) { return r.json(); })
			.then(function(res) {
				if (res.success && res.data && res.data.body) {
					previewEl.srcdoc = res.data.body;
				} else {
					previewEl.srcdoc = '<p style="padding:20px;color:#c00;">' + (res.data && res.data.message ? res.data.message : '<?php echo esc_js( __( 'Preview failed.', 'wp-powersuite' ) ); ?>') + '</p>';
				}
			})
			.catch(function() {
				previewEl.srcdoc = '<p style="padding:20px;color:#c00;"><?php echo esc_js( __( 'Preview failed.', 'wp-powersuite' ) ); ?></p>';
			});
	}

	document.querySelector('.wpps-refresh-preview')?.addEventListener('click', refreshPreview);

	// Footer text change -> debounced preview refresh
	var footerPreviewTimeout;
	function attachFooterPreviewListener() {
		var ed = typeof tinymce !== 'undefined' ? tinymce.get('footer_text') : null;
		if (!ed || ed._cwePreviewAttached) return;
		ed._cwePreviewAttached = true;
		ed.on('change keyup', function() {
			clearTimeout(footerPreviewTimeout);
			footerPreviewTimeout = setTimeout(refreshPreview, 500);
		});
	}
	if (typeof tinymce !== 'undefined') {
		tinymce.on('AddEditor', function(evt) {
			if (evt.editor.id === 'footer_text') attachFooterPreviewListener();
		});
		setTimeout(attachFooterPreviewListener, 800);
	}
})();
</script>
