<?php
/**
 * View template for the email templates admin screen.
 *
 * @package MailDoctor
 *
 * @var bool   $embedded
 * @var array  $tabs
 * @var string $view
 * @var array  $email_types
 * @var string $email_type
 * @var string $selected_label
 * @var array  $current_template
 * @var array  $defaults
 * @var string $context_value
 * @var string $notices_html
 * @var string $add_link_url
 * @var string $editor_mode
 * @var array  $locale_options
 * @var string $selected_locale
 * @var array  $status_options
 * @var array  $merge_tags
 * @var string $active_panel
 * @var array  $history_entries
 * @var bool   $history_has_more
 * @var int    $history_limit
 */

use MailDoctor\Admin;
use MailDoctor\Email\CacheService;
use MailDoctor\WPMD_Email_Templates;

defined( 'ABSPATH' ) || exit;

$mail_doctor_docs_base_url       = trailingslashit( MAIL_DOCTOR_URL . 'docs/guides' );
$mail_doctor_email_templates_doc = $mail_doctor_docs_base_url . 'email-templates.html';
$mail_doctor_support_email_link  = 'mailto:sarfrajyusufji@gmail.com';

$mail_doctor_is_active           = ! empty( $current_template['is_active'] );
$mail_doctor_last_saved          = ! empty( $current_template['modified'] ) ? esc_html( $current_template['modified'] ) : esc_html__( '—', 'mail-doctor' );
$mail_doctor_template_id         = isset( $current_template['id'] ) ? (string) $current_template['id'] : '0';
$mail_doctor_subject             = $current_template['subject'] ?? '';
$mail_doctor_heading             = $current_template['heading'] ?? '';
$mail_doctor_html                = $current_template['html'] ?? '';
$mail_doctor_css                 = $current_template['css'] ?? '';
$mail_doctor_visual_active_class = 'visual' === $editor_mode ? ' is-active' : '';
$mail_doctor_code_active_class   = 'visual' === $editor_mode ? '' : ' is-active';
$mail_doctor_history_entries     = isset( $history_entries ) && is_array( $history_entries ) ? $history_entries : array();
$mail_doctor_history_has_more    = ! empty( $history_has_more );
$mail_doctor_history_limit       = isset( $history_limit ) ? (int) $history_limit : 20;
$mail_doctor_active_panel        = isset( $active_panel ) ? $active_panel : 'editor';
$mail_doctor_panel_base_url      = remove_query_arg( array( 'mail_doctor_panel', 'mail_doctor_notice', 'mail_doctor_version' ) );
$mail_doctor_editor_panel_url    = add_query_arg( 'mail_doctor_panel', 'editor', $mail_doctor_panel_base_url );
$mail_doctor_history_panel_url   = add_query_arg( 'mail_doctor_panel', 'history', $mail_doctor_panel_base_url );
$mail_doctor_is_history_panel    = ( 'history' === $mail_doctor_active_panel );

?>
<div class="wrap maildoctor-admin-wrap maildoctor-screen wpmd-email-templates-wrap">
	<?php if ( $embedded ) : ?>

		<?php settings_errors( 'maildoctor' ); ?>
		<h2 class="screen-reader-text"><?php esc_html_e( 'Email Templates', 'mail-doctor' ); ?></h2>
	<?php else : ?>
		<h1><?php esc_html_e( 'WooCommerce Email Templates', 'mail-doctor' ); ?></h1>
		<?php settings_errors(); ?>
	<?php endif; ?>

	<?php echo wp_kses_post( $notices_html ); ?>

	<div class="wpmd-editor-grid">
		<div class="wpmd-editor-grid__sidebar">
			<aside class="wpmd-editor-grid__settings wpmd-card"
				aria-label="<?php esc_attr_e( 'Template settings', 'mail-doctor' ); ?>">
				<form class="wpmd-toggle-card" method="post"
					action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
					<?php wp_nonce_field( 'mail_doctor_toggle_templates', 'mail_doctor_toggle_nonce' ); ?>
					<input type="hidden" name="action" value="mail_doctor_toggle_templates" />
					<input type="hidden" name="mail_doctor_context" value="<?php echo esc_attr( $context_value ); ?>" />
					<header class="wpmd-toggle-card__header">
						<h2><?php esc_html_e( 'Mail Doctor templates', 'mail-doctor' ); ?></h2>
						<p><?php esc_html_e( 'Replace WooCommerce emails with customised layouts managed here.', 'mail-doctor' ); ?>
						</p>
					</header>
					<label class="toggle-control">
						<input type="checkbox" name="enabled" value="1" <?php checked( WPMD_Email_Templates::is_enabled() ); ?> />
						<span><?php esc_html_e( 'Enable Mail Doctor templates', 'mail-doctor' ); ?></span>
					</label>
					<button type="submit"
						class="button button-primary"><?php esc_html_e( 'Save settings', 'mail-doctor' ); ?></button>
				</form>

				<form class="wpmd-template-list" method="get" action="<?php echo esc_url( admin_url( 'admin.php' ) ); ?>">
					<input type="hidden" name="page" value="<?php echo esc_attr( $view ); ?>" />
					<input type="hidden" name="mail_doctor_context" value="<?php echo esc_attr( $context_value ); ?>" />
					<nav class="wpmd-template-list__nav"
						aria-label="<?php esc_attr_e( 'Email template types', 'mail-doctor' ); ?>">
						<ul>
							<?php foreach ( $email_types as $mail_doctor_type_slug => $mail_doctor_type_label ) : ?>
								<?php
								$mail_doctor_is_current   = ( $mail_doctor_type_slug === $email_type );
								$mail_doctor_item_classes = array( 'wpmd-template-list__item' );
								if ( $mail_doctor_is_current ) {
									$mail_doctor_item_classes[] = 'is-active';
								}
								?>
								<li>
									<a class="<?php echo esc_attr( implode( ' ', $mail_doctor_item_classes ) ); ?>"
										href="<?php echo esc_url( add_query_arg( 'email_type', $mail_doctor_type_slug ) ); ?>" <?php echo $mail_doctor_is_current ? ' aria-current="page"' : ''; ?>>
										<span class="wpmd-template-list__label"><?php echo esc_html( $mail_doctor_type_label ); ?></span>
										<?php if ( ! empty( $current_template['is_active'] ) && $mail_doctor_is_current ) : ?>
											<span class="wpmd-template-list__status"
												aria-hidden="true"><?php esc_html_e( 'Active', 'mail-doctor' ); ?></span>
										<?php endif; ?>
									</a>
								</li>
							<?php endforeach; ?>
						</ul>
					</nav>
					<p class="wpmd-template-list__description">
						<?php esc_html_e( 'Select an email type to customise the subject, HTML, and CSS. Changes apply instantly across WooCommerce notifications.', 'mail-doctor' ); ?>
					</p>
				</form>

			</aside>

			<section class="wpmd-editor-grid__help wpmd-card"
				aria-label="<?php esc_attr_e( 'Support resources', 'mail-doctor' ); ?>">
				<h2><?php esc_html_e( 'Need help?', 'mail-doctor' ); ?></h2>
				<ul>
					<li><a href="<?php echo esc_url( $mail_doctor_email_templates_doc ); ?>" target="_blank"
							rel="noopener noreferrer"><?php esc_html_e( 'Read the documentation', 'mail-doctor' ); ?></a>
					</li>
					<li><a
							href="<?php echo esc_url( $mail_doctor_support_email_link ); ?>"><?php esc_html_e( 'Email support', 'mail-doctor' ); ?></a>
					</li>
				</ul>
			</section>
		</div>

		<div class="wpmd-editor-grid__main">
			<section class="wpmd-editor-grid__merge-tags wpmd-card"
				aria-label="<?php esc_attr_e( 'Merge tags', 'mail-doctor' ); ?>">
				<div class="wpmd-merge-tags-panel">
					<header class="wpmd-merge-tags-panel__header">
						<h2><?php esc_html_e( 'Merge tags', 'mail-doctor' ); ?></h2>
						<label class="screen-reader-text"
							for="wpmd-merge-tag-search"><?php esc_html_e( 'Search merge tags', 'mail-doctor' ); ?></label>
						<input type="search" id="wpmd-merge-tag-search"
							placeholder="<?php esc_attr_e( 'Search merge tags…', 'mail-doctor' ); ?>" />
					</header>
					<div class="wpmd-merge-tags-panel__body" id="wpmd-merge-tags">
						<?php foreach ( $merge_tags as $mail_doctor_group ) : ?>
							<section class="wpmd-merge-tag-group" data-group="<?php echo esc_attr( $mail_doctor_group['key'] ); ?>">
								<h3><?php echo esc_html( $mail_doctor_group['label'] ); ?></h3>
								<ul>
									<?php foreach ( $mail_doctor_group['tags'] as $tag ) : ?>
										<li>
											<button type="button" class="wpmd-merge-tag"
												data-tag="<?php echo esc_attr( $tag['tag'] ); ?>"
												title="<?php echo esc_attr( $tag['description'] ?: $tag['tag'] ); ?>">
												<?php echo esc_html( '{{ ' . $tag['tag'] . ' }}' ); ?>
											</button>
										</li>
									<?php endforeach; ?>
								</ul>
							</section>
						<?php endforeach; ?>
					</div>
					<p class="helper-text">
						<?php esc_html_e( 'Click a merge tag to copy it. Paste into the visual or code editor at the desired location.', 'mail-doctor' ); ?>
					</p>
				</div>
			</section>

			<section class="wpmd-editor-grid__workspace wpmd-card" id="wpmd-editor-workspace"
				data-initial-mode="<?php echo esc_attr( $editor_mode ); ?>">
				<form id="wpmd-email-template-form" class="wpmd-editor-form" method="post"
					action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
					<?php wp_nonce_field( 'mail_doctor_save_template', 'mail_doctor_nonce' ); ?>
					<input type="hidden" name="action" value="mail_doctor_save_template" />
					<input type="hidden" id="wpmd-email-type" name="email_type"
						value="<?php echo esc_attr( $email_type ); ?>" />
					<input type="hidden" name="mail_doctor_context" value="<?php echo esc_attr( $context_value ); ?>" />
					<input type="hidden" id="wpmd-template-id" name="template_id"
						value="<?php echo esc_attr( $mail_doctor_template_id ); ?>" />
					<input type="hidden" id="wpmd-editor-mode" name="editor_mode"
						value="<?php echo esc_attr( $editor_mode ); ?>" />

					<header class="wpmd-editor-header">
						<div class="wpmd-editor-header__titles">
							<h2><?php echo esc_html( $selected_label ); ?></h2>
							<p><?php esc_html_e( 'Adjust the subject, HTML, and CSS for this WooCommerce email. Save changes when you are ready, then preview or send a test instantly.', 'mail-doctor' ); ?>
							</p>
						</div>
						<div class="wpmd-editor-header__toggle">
							<label class="toggle-control">
								<input type="checkbox" id="wpmd-template-active" name="is_active" value="1" <?php checked( $mail_doctor_is_active ); ?> />
								<span><?php esc_html_e( 'Use this template for WooCommerce emails', 'mail-doctor' ); ?></span>
							</label>
						</div>
					</header>

					<div class="wpmd-editor-meta">
						<span
							class="status-indicator <?php echo $mail_doctor_is_active ? 'status-indicator--active' : 'status-indicator--inactive'; ?>">
							<?php echo $mail_doctor_is_active ? esc_html__( 'Active', 'mail-doctor' ) : esc_html__( 'Inactive', 'mail-doctor' ); ?>
						</span>
						<span class="wpmd-editor-meta__saved">
							<?php
							printf(
								/* translators: %s: last saved datetime. */
								esc_html__( 'Last saved: %s', 'mail-doctor' ),
								esc_html( $mail_doctor_last_saved )
							);
							?>
						</span>
						<a class="button button-link wpmd-add-template" href="<?php echo esc_url( $add_link_url ); ?>">
							<?php esc_html_e( 'Start new template', 'mail-doctor' ); ?>
						</a>
					</div>

					<h2 class="nav-tab-wrapper wpmd-editor-subnav">
						<a href="<?php echo esc_url( $mail_doctor_editor_panel_url ); ?>"
							class="nav-tab <?php echo $mail_doctor_is_history_panel ? '' : 'nav-tab-active'; ?>">
							<?php esc_html_e( 'Editor', 'mail-doctor' ); ?>
						</a>
						<a href="<?php echo esc_url( $mail_doctor_history_panel_url ); ?>"
							class="nav-tab <?php echo $mail_doctor_is_history_panel ? 'nav-tab-active' : ''; ?>">
							<?php esc_html_e( 'History', 'mail-doctor' ); ?>
						</a>
					</h2>

					<div class="wpmd-editor-stage">
						<div class="wpmd-editor-stage__left">
							<div class="wpmd-editor-tabs" role="tablist">
								<button type="button" id="wpmd-editor-tab-visual"
									class="wpmd-editor-tab<?php echo 'visual' === $editor_mode ? ' is-active' : ''; ?>"
									data-mode="visual" role="tab"
									aria-selected="<?php echo 'visual' === $editor_mode ? 'true' : 'false'; ?>"
									aria-controls="wpmd-editor-panel-visual">
									<?php esc_html_e( 'Visual', 'mail-doctor' ); ?>
								</button>
								<button type="button" id="wpmd-editor-tab-code"
									class="wpmd-editor-tab<?php echo 'code' === $editor_mode || 'visual' !== $editor_mode ? ' is-active' : ''; ?>"
									data-mode="code" role="tab"
									aria-selected="<?php echo 'code' === $editor_mode || 'visual' !== $editor_mode ? 'true' : 'false'; ?>"
									aria-controls="wpmd-editor-panel-code">
									<?php esc_html_e( 'Code (HTML)', 'mail-doctor' ); ?>
								</button>
							</div>

							<div class="wpmd-field">
								<label
									for="wpmd-template-subject"><?php esc_html_e( 'Email subject', 'mail-doctor' ); ?></label>
								<input type="text" class="regular-text" id="wpmd-template-subject" name="subject"
									value="<?php echo esc_attr( $mail_doctor_subject ); ?>" />
							</div>

							<div class="wpmd-field">
								<label
									for="wpmd-template-heading"><?php esc_html_e( 'Email heading', 'mail-doctor' ); ?></label>
								<input type="text" class="regular-text" id="wpmd-template-heading" name="heading"
									value="<?php echo esc_attr( $mail_doctor_heading ); ?>" />
							</div>

							<div class="wpmd-editor-mode wpmd-editor-mode--visual<?php echo esc_attr( $mail_doctor_visual_active_class ); ?>"
								data-mode="visual" id="wpmd-editor-panel-visual" role="tabpanel"
								aria-labelledby="wpmd-editor-tab-visual" <?php echo 'visual' === $editor_mode ? '' : ' aria-hidden="true"'; ?>>
								<label class="screen-reader-text"
									for="wpmd-template-html-visual"><?php esc_html_e( 'Visual email body editor', 'mail-doctor' ); ?></label>
								<textarea id="wpmd-template-html-visual"
									rows="18"><?php echo esc_textarea( $mail_doctor_html ); ?></textarea>
								<p class="helper-text">
									<?php esc_html_e( 'The visual editor provides a WYSIWYG surface. Switch to Code mode to fine-tune HTML or CSS.', 'mail-doctor' ); ?>
								</p>
							</div>

							<div class="wpmd-editor-mode wpmd-editor-mode--code<?php echo esc_attr( $mail_doctor_code_active_class ); ?>"
								data-mode="code" id="wpmd-editor-panel-code" role="tabpanel"
								aria-labelledby="wpmd-editor-tab-code" <?php echo 'visual' === $editor_mode ? ' aria-hidden="true"' : ''; ?>>
								<div class="wpmd-field">
									<label
										for="wpmd-template-html"><?php esc_html_e( 'Body HTML', 'mail-doctor' ); ?></label>
									<textarea id="wpmd-template-html" class="code-editor html-editor" name="body_html"
										rows="18"><?php echo esc_textarea( $mail_doctor_html ); ?></textarea>
								</div>
								<div class="wpmd-field">
									<label
										for="wpmd-template-css"><?php esc_html_e( 'Inline CSS', 'mail-doctor' ); ?></label>
									<textarea id="wpmd-template-css" class="code-editor css-editor" name="css"
										rows="12"><?php echo esc_textarea( $mail_doctor_css ); ?></textarea>
									<p class="helper-text">
										<?php esc_html_e( 'Keep styles lightweight. Mail Doctor automatically inlines CSS for better deliverability.', 'mail-doctor' ); ?>
									</p>
								</div>
							</div>
						</div>

					</div>

					<footer class="wpmd-editor-footer">
						<button type="submit"
							class="button button-primary"><?php esc_html_e( 'Save template', 'mail-doctor' ); ?></button>
						<button type="button"
							class="button wpmd-validate-button"><?php esc_html_e( 'Validate', 'mail-doctor' ); ?></button>
						<button type="button"
							class="button wpmd-send-test-button"><?php esc_html_e( 'Send test', 'mail-doctor' ); ?></button>
						<button type="submit" name="reset_template" value="1"
							class="button-link button-link-delete wpmd-reset-template">
							<?php esc_html_e( 'Reset to plugin defaults', 'mail-doctor' ); ?>
						</button>
					</footer>
				</form>
			</section>

			<section class="wpmd-editor-grid__preview wpmd-card"
				aria-label="<?php esc_attr_e( 'Email preview', 'mail-doctor' ); ?>">
				<header class="wpmd-preview-header">
					<h2><?php esc_html_e( 'Live preview', 'mail-doctor' ); ?></h2>
					<p><?php esc_html_e( 'Adjust the preview controls and refresh to render the latest template output.', 'mail-doctor' ); ?>
					</p>
				</header>
				<div class="wpmd-preview-controls">
					<div class="wpmd-control">
						<label for="wpmd-preview-locale"><?php esc_html_e( 'Locale', 'mail-doctor' ); ?></label>
						<select id="wpmd-preview-locale">
							<?php foreach ( $locale_options as $mail_doctor_option ) : ?>
								<option value="<?php echo esc_attr( $mail_doctor_option['value'] ); ?>" <?php selected( $selected_locale, $mail_doctor_option['value'] ); ?>>
									<?php echo esc_html( $mail_doctor_option['label'] ); ?>
								</option>
							<?php endforeach; ?>
						</select>
					</div>
					<div class="wpmd-control">
						<label for="wpmd-preview-status"><?php esc_html_e( 'Order status', 'mail-doctor' ); ?></label>
						<select id="wpmd-preview-status">
							<?php foreach ( $status_options as $mail_doctor_option ) : ?>
								<option value="<?php echo esc_attr( $mail_doctor_option['value'] ); ?>" <?php selected( 'processing', $mail_doctor_option['value'] ); ?>>
									<?php echo esc_html( $mail_doctor_option['label'] ); ?>
								</option>
							<?php endforeach; ?>
						</select>
					</div>
					<div class="wpmd-control">
						<label
							for="wpmd-preview-order"><?php esc_html_e( 'Order ID (optional)', 'mail-doctor' ); ?></label>
						<input type="number" id="wpmd-preview-order" min="0"
							placeholder="<?php esc_attr_e( 'Sample order ID', 'mail-doctor' ); ?>" />
					</div>
					<button type="button"
						class="button wpmd-preview-refresh"><?php esc_html_e( 'Refresh preview', 'mail-doctor' ); ?></button>
				</div>
				<div class="wpmd-preview-frame">
					<iframe id="wpmd-live-preview-frame" title="<?php esc_attr_e( 'Email preview', 'mail-doctor' ); ?>"
						loading="lazy"></iframe>
					<div class="wpmd-preview-overlay" aria-live="polite"></div>
				</div>
				<div class="wpmd-preview-diagnostics">
					<strong><?php esc_html_e( 'HTML cache', 'mail-doctor' ); ?>:</strong>
					<span id="wpmd-cache-diagnostics" data-version="<?php echo esc_attr( CacheService::version() ); ?>">
						<?php
						printf(
							/* translators: %s: cache version identifier. */
							esc_html__( 'Version %s — hits 0 / misses 0', 'mail-doctor' ),
							esc_html( CacheService::version() )
						);
						?>
					</span>
				</div>
				<div class="wpmd-preview-warnings" id="wpmd-preview-warnings" aria-live="assertive"></div>
			</section>
		</div>
	</div>

	<div id="wpmd-send-test-modal" class="maildoctor-modal" hidden>
		<div class="modal-backdrop wpmd-modal__backdrop"></div>
		<div class="modal-dialog wpmd-modal__dialog">
			<header class="modal-header">
				<h2 id="wpmd-send-test-modal-title"><?php esc_html_e( 'Send test email', 'mail-doctor' ); ?></h2>
				<button type="button" class="button-link wpmd-modal-close wpmd-modal__close"
					aria-label="<?php esc_attr_e( 'Close modal', 'mail-doctor' ); ?>">×</button>
			</header>
			<div class="modal-content">
				<form id="wpmd-send-test-form">
					<label class="field-group" for="wpmd-send-test-recipient">
						<span class="field-label"><?php esc_html_e( 'Recipient email', 'mail-doctor' ); ?></span>
						<input type="email" id="wpmd-send-test-recipient" name="recipient" class="regular-text"
							required />
					</label>
					<label class="field-group" for="wpmd-send-test-order">
						<span class="field-label"><?php esc_html_e( 'Order ID (optional)', 'mail-doctor' ); ?></span>
						<input type="text" id="wpmd-send-test-order" name="order_id" class="small-text" />
					</label>
					<p class="helper-text">
						<?php esc_html_e( 'If an order ID is provided, the template uses that order for merge tags.', 'mail-doctor' ); ?>
					</p>
					<button type="submit"
						class="button button-primary"><?php esc_html_e( 'Send test email', 'mail-doctor' ); ?></button>
				</form>
			</div>
		</div>
	</div>