<?php
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals
// phpcs:disable WordPress.Security.NonceVerification
// phpcs:disable WordPress.Security.ValidatedSanitizedInput
// phpcs:disable WordPress.DB.PreparedSQL
// phpcs:disable WordPress.DB.DirectDatabaseQuery
/**
 * GT BOGO Engine — Email Management (Enterprise)
 * Full email template manager with test send, preview, stats and theme selector.
 *
 * @package GT_BOGO_Engine
 * @since   3.17.0
 */

if ( ! function_exists( 'gt_bogo_has_pro' ) || ! gt_bogo_has_pro() ) {
	gtbogo_upgrade_card( 'Email Automation — 23 Lifecycle Emails', 'Fully automated email sequences for every customer lifecycle event — welcome, tier upgrade, streak bonus, birthday deal, win-back, cart nudge, VIP unlock, referral reward, and more. All 23 email types are pre-built and run on autopilot. No third-party ESP required.' );
	return;
}
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
if ( ! current_user_can( 'manage_options' ) ) {
	return;
}

$message      = '';
$message_type = '';

$email_types = array(
	'lifecycle' => array(
		'label'  => 'Lifecycle',
		'icon'   => '👤',
		'emails' => array(
			'new_customer_welcome' => array(
				'label' => 'New Customer Welcome',
				'desc'  => 'Sent on first purchase. Introduce the brand and upcoming deals.',
			),
			'post_purchase'        => array(
				'label' => 'Post-Purchase Follow-Up',
				'desc'  => 'Sent 3 days after order completion. Upsell and collect reviews.',
			),
			'lapsed_reactivation'  => array(
				'label' => 'Lapsed Customer Reactivation',
				'desc'  => 'Sent to customers inactive 90+ days. Win them back with a deal.',
			),
			'winback'              => array(
				'label' => 'Win-Back',
				'desc'  => 'Aggressive win-back for customers at-risk of churning.',
			),
			'anniversary'          => array(
				'label' => 'Anniversary',
				'desc'  => 'Sent on the anniversary of first purchase.',
			),
			'birthday_deal'        => array(
				'label' => 'Birthday Deal',
				'desc'  => 'Sent on customer birthday if DOB is on file.',
			),
		),
	),
	'deals'     => array(
		'label'  => 'Deals & Savings',
		'icon'   => '🎁',
		'emails' => array(
			'bogo_confirmation' => array(
				'label' => 'Order Savings Confirmation',
				'desc'  => 'Sent after a BOGO deal is applied at checkout.',
			),
			'deal_expiry'       => array(
				'label' => 'Deal Expiring Soon',
				'desc'  => 'Reminder that an active deal expires within 24 hours.',
			),
			'deal_unlocked'     => array(
				'label' => 'Deal Unlocked',
				'desc'  => 'Sent when a customer qualifies for a new deal.',
			),
			'free_gift'         => array(
				'label' => 'Free Gift Added',
				'desc'  => 'Confirmation that a free gift was added to their order.',
			),
			'flash_sale_alert'  => array(
				'label' => 'Flash Sale Alert',
				'desc'  => 'Announce a time-limited flash sale to active customers.',
			),
			'cart_nudge'        => array(
				'label' => 'Cart Nudge',
				'desc'  => 'Sent when cart abandoned with an active BOGO deal.',
			),
			'threshold_nudge'   => array(
				'label' => 'Threshold Nudge',
				'desc'  => 'Nudge when customer is close to unlocking a threshold deal.',
			),
		),
	),
	'loyalty'   => array(
		'label'  => 'Loyalty & VIP',
		'icon'   => '🏆',
		'emails' => array(
			'tier_upgrade'       => array(
				'label' => 'Loyalty Tier Upgrade',
				'desc'  => 'Sent when customer reaches a new loyalty tier.',
			),
			'streak_bonus'       => array(
				'label' => 'Streak Bonus',
				'desc'  => 'Reward for consecutive purchase streaks.',
			),
			'streak_at_risk'     => array(
				'label' => 'Streak At Risk',
				'desc'  => 'Warning that a purchase streak is about to break.',
			),
			'vip_unlocked'       => array(
				'label' => 'VIP Unlocked',
				'desc'  => 'Notification that VIP status has been achieved.',
			),
			'order_milestone'    => array(
				'label' => 'Order Milestone',
				'desc'  => 'Celebrate 5th, 10th, 25th order milestones.',
			),
			'subscriber_at_risk' => array(
				'label' => 'Subscriber At Risk',
				'desc'  => 'Alert when a high-value subscriber shows disengagement signals.',
			),
			'b2b_tier_reached'   => array(
				'label' => 'B2B Tier Reached',
				'desc'  => 'Sent when a wholesale buyer reaches a new B2B discount tier.',
			),
		),
	),
	'referrals' => array(
		'label'  => 'Referrals',
		'icon'   => '🔗',
		'emails' => array(
			'referral_reward'   => array(
				'label' => 'Referral Reward',
				'desc'  => 'Sent when a referral results in a completed purchase.',
			),
			'referral_progress' => array(
				'label' => 'Referral Progress',
				'desc'  => 'Update on referral milestone progress.',
			),
		),
	),
);

// All email type keys flat
$all_type_keys = array();
foreach ( $email_types as $group ) {
	foreach ( $group['emails'] as $key => $meta ) {
		$all_type_keys[] = $key;
	}
}

// ── Handle save templates ─────────────────────────────────────────────────
if ( isset( $_POST['gtbogo_save_emails'] ) && check_admin_referer( 'gtbogo_save_emails', 'gtbogo_emails_nonce' ) ) {
	foreach ( $all_type_keys as $type ) {
		$subj = sanitize_text_field( wp_unslash( $_POST[ 'gtbogo_email_' . $type . '_subject' ] ?? '' ) );
		$body = wp_kses_post( wp_unslash( $_POST[ 'gtbogo_email_' . $type . '_body' ] ?? '' ) );
		if ( $subj !== '' ) {
			update_option( 'gtbogo_email_' . $type . '_subject', $subj );
		} else {
			delete_option( 'gtbogo_email_' . $type . '_subject' );
		}
		if ( $body !== '' ) {
			update_option( 'gtbogo_email_' . $type . '_body', $body );
		} else {
			delete_option( 'gtbogo_email_' . $type . '_body' );
		}
	}
	// Global settings
	update_option( 'gtbogo_email_theme', sanitize_text_field( $_POST['gtbogo_global_theme'] ?? 'midnight' ) );
	update_option( 'gtbogo_customer_emails_enabled', isset( $_POST['gtbogo_emails_enabled'] ) ? '1' : '0' );
	update_option( 'gt_bogo_email_from_address', sanitize_email( $_POST['gtbogo_from_email'] ?? '' ) );
	update_option( 'gt_bogo_email_from_name', sanitize_text_field( $_POST['gtbogo_from_name'] ?? '' ) );
	if ( function_exists( 'gt_bogo_log' ) ) {
		gt_bogo_log( 'Email templates saved', count( $all_type_keys ) . ' templates', 'success' );
	}
	$message      = 'Email settings saved.';
	$message_type = 'success';
}

// ── Handle test send ──────────────────────────────────────────────────────
if ( isset( $_POST['gtbogo_send_test'] ) && check_admin_referer( 'gtbogo_send_test', 'gtbogo_test_nonce' ) ) {
	$test_type  = sanitize_text_field( $_POST['test_email_type'] ?? 'bogo_confirmation' );
	$test_email = sanitize_email( $_POST['test_email_address'] ?? get_option( 'admin_email' ) );
	if ( class_exists( 'GT_BOGO_Email_System' ) && is_email( $test_email ) ) {
		$sent         = GT_BOGO_Email_System::instance()->send_email(
			$test_email,
			$test_type,
			array(
				'store'    => get_bloginfo( 'name' ),
				'customer' => 'Test Customer',
				'amount'   => '$25.00',
				'discount' => '50% BOGO Deal',
				'order_id' => '#TEST-001',
			)
		);
		$message      = $sent ? "Test email sent to {$test_email}" : 'Test email failed — check SMTP settings';
		$message_type = $sent ? 'success' : 'error';
		if ( function_exists( 'gt_bogo_log' ) ) {
			gt_bogo_log( 'Test email', $test_type . ' → ' . $test_email, $sent ? 'success' : 'error' );
		}
	} else {
		$message      = 'Invalid email address or email system not available.';
		$message_type = 'error';
	}
}

// Load settings
$current_theme  = get_option( 'gtbogo_email_theme', 'midnight' );
$emails_enabled = get_option( 'gtbogo_customer_emails_enabled', '1' );
$from_email     = get_option( 'gt_bogo_email_from_address', get_option( 'admin_email' ) );
$from_name      = get_option( 'gt_bogo_email_from_name', get_bloginfo( 'name' ) );

// Email stats
global $wpdb;
$email_stats = get_option( 'gtbogo_email_stats', array() );
$total_sent  = array_sum( $email_stats );

// Available themes
$themes = array(
	'midnight' => 'Midnight (Dark Navy)',
	'onyx'     => 'Onyx (Pure Black)',
	'slate'    => 'Slate (Dark Grey)',
	'crimson'  => 'Crimson (Dark Red)',
	'forest'   => 'Forest (Dark Green)',
	'ocean'    => 'Ocean (Dark Blue)',
	'dusk'     => 'Dusk (Purple Dark)',
	'ember'    => 'Ember (Warm Dark)',
);

// Placeholder variables
$placeholders = array(
	'{store}'        => 'Store name',
	'{customer}'     => 'Customer first name',
	'{amount}'       => 'Order total',
	'{discount}'     => 'Discount applied',
	'{order_id}'     => 'Order number',
	'{product}'      => 'Product name',
	'{tier}'         => 'Loyalty tier name',
	'{streak}'       => 'Current streak count',
	'{referral_url}' => 'Unique referral link',
	'{deal_name}'    => 'Deal or rule name',
	'{expiry}'       => 'Offer expiry date/time',
	'{savings}'      => 'Amount saved',
);

require_once __DIR__ . '/../ui-system/wrapper-start.php';
?>
<div class="gt-page-header gt-animate-in">
	<div>
		<h1 class="gt-page-title">✉️ Email Management</h1>
		<p class="gt-page-subtitle">23 automated customer lifecycle emails — configure templates, themes, and delivery settings</p>
	</div>
	<div style="display:flex;gap:8px;align-items:center">
		<span class="gt-badge <?php echo $emails_enabled ? 'gt-badge-active' : 'gt-badge-warn'; ?>"><?php echo $emails_enabled ? '● Emails Active' : '⚠ Emails Off'; ?></span>
		<span class="gt-badge gt-badge-active"><?php echo esc_html( $total_sent ); ?> sent total</span>
	</div>
</div>

<?php if ( $message ) : ?>
<div class="gt-notice gt-notice-<?php echo esc_attr( $message_type ); ?> gt-animate-in">
	<?php echo $message_type === 'success' ? '✓' : '✕'; ?> <?php echo esc_html( $message ); ?>
</div>
<?php endif; ?>

<!-- KPI STRIP -->
<div class="gt-metrics gt-animate-in" style="margin-bottom:24px">
	<div class="gt-metric" style="--gt-metric-c:#acfe01">
		<span class="gt-metric-icon">📤</span>
		<div class="gt-metric-label">Total Sent</div>
		<div class="gt-metric-value"><?php echo number_format( $total_sent ); ?></div>
		<div class="gt-metric-trend">All time</div>
	</div>
	<?php
	$custom_count = 0;
	foreach ( $all_type_keys as $k ) {
		if ( get_option( 'gtbogo_email_' . $k . '_subject', '' ) || get_option( 'gtbogo_email_' . $k . '_body', '' ) ) {
			++$custom_count;
		}
	}
	?>
	<div class="gt-metric" style="--gt-metric-c:#3b82f6">
		<span class="gt-metric-icon">✏️</span>
		<div class="gt-metric-label">Custom Templates</div>
		<div class="gt-metric-value"><?php echo esc_html( $custom_count ); ?></div>
		<div class="gt-metric-trend"><?php echo count( $all_type_keys ) - $custom_count; ?> using defaults</div>
	</div>
	<div class="gt-metric" style="--gt-metric-c:#8b5cf6">
		<span class="gt-metric-icon">🎨</span>
		<div class="gt-metric-label">Active Theme</div>
		<div class="gt-metric-value" style="font-size:14px"><?php echo esc_html( $themes[ $current_theme ] ?? $current_theme ); ?></div>
		<div class="gt-metric-trend">8 themes available</div>
	</div>
	<div class="gt-metric" style="--gt-metric-c:#22c55e">
		<span class="gt-metric-icon">📧</span>
		<div class="gt-metric-label">From Address</div>
		<div class="gt-metric-value" style="font-size:12px;word-break:break-all"><?php echo esc_html( $from_email ); ?></div>
		<div class="gt-metric-trend">SMTP configured</div>
	</div>
</div>

<form method="post" action="">
<?php wp_nonce_field( 'gtbogo_save_emails', 'gtbogo_emails_nonce' ); ?>

<!-- GLOBAL SETTINGS -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header"><h2 class="gt-card-title">⚙️ Global Email Settings</h2></div>
	<div class="gt-setting-row">
		<div><div class="gt-setting-label">Enable Customer Emails</div><div class="gt-setting-desc">Master switch — disabling stops all automated GT BOGO emails</div></div>
		<label class="gt-toggle"><input type="checkbox" name="gtbogo_emails_enabled" value="1" <?php checked( $emails_enabled, '1' ); ?> data-option="gtbogo_customer_emails_enabled" data-nonce="<?php echo esc_attr( wp_create_nonce( 'gtbogo_system_toggle' ) ); ?>"><span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span></label>
	</div>
	<div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:16px;padding:16px 0 0">
		<div class="gt-form-group" style="margin:0">
			<label class="gt-form-label">From Name</label>
			<input type="text" name="gtbogo_from_name" class="gt-input" value="<?php echo esc_attr( $from_name ); ?>" id="gtbogo_gtbogo_from_name" aria-label="Gtbogo From Name">
		</div>
		<div class="gt-form-group" style="margin:0">
			<label class="gt-form-label">From Email Address</label>
			<input type="email" name="gtbogo_from_email" class="gt-input" value="<?php echo esc_attr( $from_email ); ?>" id="gtbogo_gtbogo_from_email" aria-label="Gtbogo From Email">
		</div>
		<div class="gt-form-group" style="margin:0">
			<label class="gt-form-label">Email Theme</label>
			<select name="gtbogo_global_theme" class="gt-select">
				<?php foreach ( $themes as $key => $label ) : ?>
				<option value="<?php echo esc_attr( $key ); ?>" <?php selected( $current_theme, $key ); ?>><?php echo esc_html( $label ); ?></option>
				<?php endforeach; ?>
			</select>
			<div class="gt-form-hint">Applied to all email templates sitewide</div>
		</div>
	</div>
</div>

<!-- PLACEHOLDER REFERENCE -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px;background:rgba(172,254.3.0.03);border-color:rgba(172,254,1,0.1)">
	<div class="gt-card-header"><h2 class="gt-card-title">🔤 Available Placeholders</h2><span class="gt-text-soft" style="font-size:13px">Use in subject line and body</span></div>
	<div style="display:grid;grid-template-columns:repeat(4,1fr);gap:8px;padding:4px 0">
		<?php foreach ( $placeholders as $var => $desc ) : ?>
		<div style="display:flex;align-items:center;gap:8px;padding:8px;background:rgba(255,255,255,0.03);border-radius:6px">
			<code style="background:rgba(172,254,1,0.1);color:#acfe01;padding:2px 6px;border-radius:4px;font-size:11px;flex-shrink:0"><?php echo esc_html( $var ); ?></code>
			<span style="font-size:11px;color:var(--gt-subtle)"><?php echo esc_html( $desc ); ?></span>
		</div>
		<?php endforeach; ?>
	</div>
</div>

<!-- EMAIL TEMPLATES BY GROUP -->
<?php foreach ( $email_types as $group_key => $group ) : ?>
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header">
		<h2 class="gt-card-title"><?php echo esc_html( $group['icon'] ); ?> <?php echo esc_html( $group['label'] ); ?></h2>
		<span class="gt-text-soft" style="font-size:13px"><?php echo count( $group['emails'] ); ?> email types</span>
	</div>
	<div style="display:flex;flex-direction:column;gap:0">
	<?php
	foreach ( $group['emails'] as $type => $meta ) :
		$subject    = get_option( 'gtbogo_email_' . $type . '_subject', '' );
		$body       = get_option( 'gtbogo_email_' . $type . '_body', '' );
		$active     = $subject !== '' || $body !== '';
		$sent_count = $email_stats[ $type ] ?? 0;
		?>
	<div style="border-bottom:1px solid var(--gt-border);last-child:border:none">
		<div style="display:flex;align-items:center;justify-content:space-between;padding:14px 0;cursor:pointer;user-select:none"
			onclick="var p=document.getElementById('email-<?php echo esc_attr( $type ); ?>');p.style.display=p.style.display==='none'?'block':'none'">
			<div style="display:flex;align-items:center;gap:10px">
				<span style="width:8px;height:8px;border-radius:50%;background:<?php echo $active ? '#22c55e' : 'rgba(255,255,255,0.15)'; ?>;flex-shrink:0;display:inline-block"></span>
				<span style="font-size:14px;font-weight:700;color:var(--gt-white)"><?php echo esc_html( $meta['label'] ); ?></span>
				<span style="font-size:12px;color:var(--gt-subtle)"><?php echo esc_html( $meta['desc'] ); ?></span>
			</div>
			<div style="display:flex;align-items:center;gap:12px;flex-shrink:0">
				<?php if ( $sent_count > 0 ) : ?>
				<span style="font-size:12px;color:#22c55e;background:rgba(34,197,94,0.1);padding:2px 8px;border-radius:20px"><?php echo number_format( $sent_count ); ?> sent</span>
				<?php endif; ?>
				<span style="font-size:12px;color:<?php echo $active ? '#acfe01' : 'var(--gt-subtle)'; ?>"><?php echo $active ? 'Custom' : 'Default'; ?></span>
				<span style="font-size:16px;color:var(--gt-subtle)">▾</span>
			</div>
		</div>
		<div id="email-<?php echo esc_attr( $type ); ?>" style="display:<?php echo $active ? 'block' : 'none'; ?>;padding-bottom:16px">
			<div style="display:grid;grid-template-columns:1fr;gap:12px">
				<div class="gt-form-group" style="margin:0">
					<label class="gt-form-label">Subject Line <span style="font-weight:400;color:var(--gt-subtle)">(blank = use built-in English default)</span></label>
					<input type="text" name="gtbogo_email_<?php echo esc_attr( $type ); ?>_subject"
							class="gt-input" value="<?php echo esc_attr( $subject ); ?>"
							placeholder="Leave blank to use the default subject" id="gtbogo_leave_blank_to_use_the_default" aria-label="Leave blank to use the default subject">
				</div>
				<div class="gt-form-group" style="margin:0">
					<label class="gt-form-label">Email Body <span style="font-weight:400;color:var(--gt-subtle)">(plain text or basic HTML, blank = default)</span></label>
					<textarea name="gtbogo_email_<?php echo esc_attr( $type ); ?>_body"
								class="gt-input" rows="4"
								placeholder="Leave blank to use the built-in default body."><?php echo esc_textarea( $body ); ?></textarea>
				</div>
			</div>
		</div>
	</div>
	<?php endforeach; ?>
	</div>
</div>
<?php endforeach; ?>

<div style="text-align:right;margin-bottom:32px">
	<button type="submit" name="gtbogo_save_emails" class="gt-btn gt-btn-primary" style="padding:14px 40px;font-size:15px">💾 Save All Email Settings</button>
</div>
</form>

<!-- TEST EMAIL SENDER -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px;border-color:rgba(59,130,246,0.2)">
	<div class="gt-card-header"><h2 class="gt-card-title">🧪 Send Test Email</h2></div>
	<form method="post" action="">
		<?php wp_nonce_field( 'gtbogo_send_test', 'gtbogo_test_nonce' ); ?>
		<div style="display:grid;grid-template-columns:1fr 1fr auto;gap:16px;align-items:end">
			<div class="gt-form-group" style="margin:0">
				<label class="gt-form-label">Email Type</label>
				<select name="test_email_type" class="gt-select">
					<?php foreach ( $email_types as $group ) : ?>
						<?php foreach ( $group['emails'] as $key => $meta ) : ?>
					<option value="<?php echo esc_attr( $key ); ?>"><?php echo esc_html( $group['icon'] . ' ' . $meta['label'] ); ?></option>
					<?php endforeach; ?>
					<?php endforeach; ?>
				</select>
			</div>
			<div class="gt-form-group" style="margin:0">
				<label class="gt-form-label">Send To</label>
				<input type="email" name="test_email_address" class="gt-input"
						value="<?php echo esc_attr( get_option( 'admin_email' ) ); ?>"
						placeholder="test@example.com" id="gtbogo_test_email_address" aria-label="Test Email Address">
			</div>
			<button type="submit" name="gtbogo_send_test" class="gt-btn gt-btn-primary" style="padding:12px 24px;white-space:nowrap">📤 Send Test</button>
		</div>
		<div class="gt-form-hint" style="margin-top:8px">Sends a test email using sample data to verify your SMTP and template rendering</div>
	</form>
</div>

<!-- EMAIL STATS TABLE -->
<?php if ( ! empty( $email_stats ) ) : ?>
<div class="gt-card gt-animate-in">
	<div class="gt-card-header"><h2 class="gt-card-title">📊 Email Performance</h2></div>
	<table style="width:100%;border-collapse:collapse;font-size:13px">
		<thead>
			<tr>
				<th style="text-align:left;color:var(--gt-soft);padding:8px 0;border-bottom:1px solid var(--gt-border);font-size:11px;text-transform:uppercase;letter-spacing:.06em">Email Type</th>
				<th style="text-align:right;color:var(--gt-soft);padding:8px 0;border-bottom:1px solid var(--gt-border);font-size:11px;text-transform:uppercase;letter-spacing:.06em">Sent</th>
				<th style="text-align:right;color:var(--gt-soft);padding:8px 0;border-bottom:1px solid var(--gt-border);font-size:11px;text-transform:uppercase;letter-spacing:.06em">Template</th>
			</tr>
		</thead>
		<tbody>
		<?php
		$flat_emails = array();
		foreach ( $email_types as $group ) {
			foreach ( $group['emails'] as $key => $meta ) {
				$flat_emails[ $key ] = $meta;
			}
		}
		arsort( $email_stats );
		foreach ( $email_stats as $type => $count ) :
			$label  = $flat_emails[ $type ]['label'] ?? $type;
			$custom = get_option( 'gtbogo_email_' . $type . '_subject', '' ) !== '';
			?>
		<tr>
			<td style="padding:10px 0;border-bottom:1px solid rgba(255,255,255,0.04);color:var(--gt-white)"><?php echo esc_html( $label ); ?></td>
			<td style="padding:10px 0;border-bottom:1px solid rgba(255,255,255,0.04);color:#acfe01;text-align:right;font-weight:700"><?php echo number_format( $count ); ?></td>
			<td style="padding:10px 0;border-bottom:1px solid rgba(255,255,255,0.04);text-align:right">
				<span style="font-size:11px;color:<?php echo $custom ? '#acfe01' : 'var(--gt-subtle)'; ?>"><?php echo $custom ? 'Custom' : 'Default'; ?></span>
			</td>
		</tr>
		<?php endforeach; ?>
		</tbody>
	</table>
</div>
<?php endif; ?>

<?php require_once __DIR__ . '/../ui-system/wrapper-end.php'; ?>
