<?php
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals
// phpcs:disable WordPress.Security.NonceVerification
// phpcs:disable WordPress.Security.ValidatedSanitizedInput
// phpcs:disable WordPress.WP.EnqueuedResourceParameters
// phpcs:disable WordPress.DB.PreparedSQL
// phpcs:disable WordPress.DB.PreparedSQLPlaceholders
// phpcs:disable WordPress.DB.DirectDatabaseQuery
// phpcs:disable WordPress.DB.SlowDBQuery
// phpcs:disable PluginCheck.Security.DirectDB
// phpcs:disable PluginCheck.CodeAnalysis
// phpcs:disable WordPressVIPMinimum

// ── Email readiness notice ─────────────────────────────────────────────────────
$_gtbogo_s = get_option( 'gtbogo_settings', array() );
if ( ! empty( $_gtbogo_s['customer_emails_enabled'] ) && class_exists( 'GT_BOGO_Email_System' ) ) {
	$_gtbogo_ready = GT_BOGO_Email_System::instance()->get_readiness_status();
	if ( ! $_gtbogo_ready['ready'] ) {
		echo '<div style="background:#1a0a08;border:1px solid #7f1d1d;border-left:4px solid #ef4444;border-radius:8px;padding:16px 20px;margin-bottom:24px;">';
		echo '<p style="margin:0 0 8px;font-size:13px;font-weight:700;color:#ef4444;text-transform:uppercase;letter-spacing:.08em;">Customer emails enabled — store not ready</p>';
		echo '<ul style="margin:0;padding-left:20px;">';
		foreach ( $_gtbogo_ready['issues'] as $_gtbogo_issue ) {
			echo '<li style="font-size:13px;color:#fca5a5;margin-bottom:6px;">' . esc_html( $_gtbogo_issue ) . '</li>';
		}
		echo '</ul></div>';
	}
}
/**
 * GT BOGO Engine — Settings (Enterprise)
 *
 * @package GT_BOGO_Engine
 * @since   3.11.0
 */
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
if ( ! current_user_can( 'manage_options' ) ) {
	return;
}

$is_pro            = function_exists( 'gt_bogo_has_pro' ) ? gt_bogo_has_pro() : false;
$message           = '';
$message_type      = '';
$version           = defined( 'GT_BOGO_VERSION' ) ? GT_BOGO_VERSION : GT_BOGO_VERSION;
$_gtbogo_sys_nonce = wp_create_nonce( 'gtbogo_system_toggle' );

// ── Save ──────────────────────────────────────────────────────────────────────
if ( isset( $_POST['gtbogo_save_settings'] ) && check_admin_referer( 'gtbogo_save_settings' ) ) {
	// Cart & Checkout
	update_option( 'gtbogo_auto_add', isset( $_POST['auto_add'] ) );
	update_option( 'gtbogo_auto_remove', isset( $_POST['auto_remove'] ) );
	update_option( 'gtbogo_show_discount_label', isset( $_POST['show_discount_label'] ) );
	update_option( 'gtbogo_discount_label_text', sanitize_text_field( $_POST['discount_label_text'] ?? 'Free' ) );
	update_option( 'gtbogo_cart_notice', isset( $_POST['cart_notice'] ) );
	update_option( 'gtbogo_cart_notice_pos', sanitize_text_field( $_POST['cart_notice_pos'] ?? 'before_cart' ) );
	update_option( 'gtbogo_conflict_strategy', sanitize_text_field( $_POST['conflict_strategy'] ?? 'highest_priority' ) );
	update_option( 'gtbogo_max_discount_pct', intval( $_POST['max_discount_pct'] ?? 0 ) );
	update_option( 'gtbogo_exclude_roles', array_map( 'sanitize_text_field', (array) ( $_POST['exclude_roles'] ?? array() ) ) );
	// Display
	update_option( 'gtbogo_show_badge', isset( $_POST['show_badge'] ) );
	update_option( 'gtbogo_badge_position', sanitize_text_field( $_POST['badge_position'] ?? 'top_left' ) );
	update_option( 'gtbogo_badge_inherit_theme', isset( $_POST['badge_inherit_theme'] ) );
	update_option( 'gtbogo_progress_bar', isset( $_POST['progress_bar'] ) );
	update_option( 'gtbogo_progress_bar_pos', sanitize_text_field( $_POST['progress_bar_pos'] ?? 'before_cart' ) );
	// Performance
	update_option( 'gtbogo_cache_rules', isset( $_POST['cache_rules'] ) );
	update_option( 'gtbogo_cache_ttl', intval( $_POST['cache_ttl'] ?? 300 ) );
	update_option( 'gtbogo_ajax_cart', isset( $_POST['ajax_cart'] ) );
	// Analytics
	update_option( 'gtbogo_analytics_enabled', isset( $_POST['analytics_enabled'] ) );
	update_option( 'gtbogo_analytics_retention_days', intval( $_POST['analytics_retention'] ?? 90 ) );
	update_option( 'gtbogo_analytics_exclude_roles', array_map( 'sanitize_text_field', (array) ( $_POST['analytics_exclude_roles'] ?? array() ) ) );
	// Audit Log
	update_option( 'gtbogo_log_enabled', isset( $_POST['log_enabled'] ) );
	update_option( 'gtbogo_log_max_entries', intval( $_POST['log_max_entries'] ?? 1000 ) );
	update_option( 'gtbogo_log_min_level', sanitize_text_field( $_POST['log_min_level'] ?? 'info' ) );
	update_option( 'gtbogo_log_alert_on_error', isset( $_POST['log_alert_on_error'] ) );
	update_option( 'gtbogo_log_alert_email', sanitize_email( $_POST['log_alert_email'] ?? '' ) );
	// Referral
	update_option( 'gtbogo_referral_enabled', isset( $_POST['referral_enabled'] ) );
	update_option( 'gtbogo_referral_reward_count', intval( $_POST['referral_reward_count'] ?? 3 ) );
	update_option( 'gtbogo_referral_reward_type', sanitize_text_field( $_POST['referral_reward_type'] ?? 'percent' ) );
	update_option( 'gtbogo_referral_reward_value', floatval( $_POST['referral_reward_value'] ?? 20 ) );
	update_option( 'gtbogo_referral_reward_label', sanitize_text_field( $_POST['referral_reward_label'] ?? '' ) );
	// Guest & Opt-In
	update_option( 'gtbogo_require_account_for_deals', isset( $_POST['require_account_for_deals'] ) );
	update_option( 'gtbogo_registration_prompt_message', sanitize_text_field( $_POST['registration_prompt_message'] ?? '' ) );
	update_option( 'gtbogo_double_optin_enabled', isset( $_POST['double_optin_enabled'] ) );
	update_option( 'gtbogo_optin_on_registration', isset( $_POST['optin_on_registration'] ) );
	update_option( 'gtbogo_gdpr_strict_mode', isset( $_POST['gdpr_strict_mode'] ) ? 1 : 0 );
	update_option( 'gtbogo_optin_checkbox_label', sanitize_text_field( $_POST['optin_checkbox_label'] ?? '' ) );
	// Customer Emails
	update_option( 'gtbogo_customer_emails_enabled', isset( $_POST['customer_emails_enabled'] ) );
	update_option( 'gtbogo_email_theme', sanitize_key( $_POST['email_theme'] ?? 'midnight' ) );
	update_option( 'gtbogo_email_accent_color', sanitize_hex_color( $_POST['email_accent_color_override'] ?? '' ) );
	update_option( 'gtbogo_sp_accent_color', sanitize_hex_color( $_POST['sp_accent_color'] ?? '#E10000' ) );
	update_option( 'gtbogo_email_logo_url', esc_url_raw( $_POST['email_logo_url'] ?? '' ) );
	// Advanced
	update_option( 'gtbogo_debug_mode', isset( $_POST['debug_mode'] ) );
	update_option( 'gtbogo_uninstall_data', isset( $_POST['uninstall_data'] ) );
	// Storefront Appearance — CSS variables
	update_option( 'gtbogo_css_accent', sanitize_hex_color( $_POST['gtbogo_css_accent'] ?? '#acfe01' ) );
	update_option( 'gtbogo_css_accent_dark', sanitize_hex_color( $_POST['gtbogo_css_accent_dark'] ?? '#8acc00' ) );
	update_option( 'gtbogo_css_danger', sanitize_hex_color( $_POST['gtbogo_css_danger'] ?? '#ff4444' ) );
	update_option( 'gtbogo_css_bg', sanitize_hex_color( $_POST['gtbogo_css_bg'] ?? '#0f172a' ) );
	update_option( 'gtbogo_css_card_bg', sanitize_text_field( $_POST['gtbogo_css_card_bg'] ?? 'rgba(255,255,255,0.05)' ) );
	update_option( 'gtbogo_css_text', sanitize_hex_color( $_POST['gtbogo_css_text'] ?? '#ffffff' ) );
	update_option( 'gtbogo_css_radius', sanitize_text_field( $_POST['gtbogo_css_radius'] ?? '10px' ) );

	if ( function_exists( 'gt_bogo_log' ) ) {
		gt_bogo_log( 'Settings updated', 'Admin settings saved', 'success' );
	}
	delete_transient( 'gtbogo_active_rules' );
	delete_transient( 'gtbogo_active_rules_summary' );

	// Write theme config for server-side email-sender.php (no WP context there)
	$themes_map = array(
		'midnight' => array(
			'bg1'    => '#070C1C',
			'bg2'    => '#050a16',
			'bg3'    => '#03060f',
			'accent' => '#E10000',
			'border' => '#0f1a30',
			'muted'  => '#4a6a8a',
		),
		'ocean'    => array(
			'bg1'    => '#040d1a',
			'bg2'    => '#030b16',
			'bg3'    => '#020810',
			'accent' => '#0ea5e9',
			'border' => '#0a2040',
			'muted'  => '#3a6080',
		),
		'forest'   => array(
			'bg1'    => '#04100a',
			'bg2'    => '#030d08',
			'bg3'    => '#020905',
			'accent' => '#16a34a',
			'border' => '#0a2814',
			'muted'  => '#2a5a3a',
		),
		'royal'    => array(
			'bg1'    => '#0a0714',
			'bg2'    => '#080510',
			'bg3'    => '#05030c',
			'accent' => '#7c3aed',
			'border' => '#1a0d40',
			'muted'  => '#4a3070',
		),
		'obsidian' => array(
			'bg1'    => '#0a0a08',
			'bg2'    => '#070706',
			'bg3'    => '#040403',
			'accent' => '#d97706',
			'border' => '#1a1a14',
			'muted'  => '#4a4a38',
		),
		'ember'    => array(
			'bg1'    => '#110804',
			'bg2'    => '#0d0603',
			'bg3'    => '#090402',
			'accent' => '#ea580c',
			'border' => '#301408',
			'muted'  => '#5a3020',
		),
		'slate'    => array(
			'bg1'    => '#080d14',
			'bg2'    => '#060a10',
			'bg3'    => '#04070c',
			'accent' => '#06b6d4',
			'border' => '#0d2030',
			'muted'  => '#2a4a5a',
		),
		'rose'     => array(
			'bg1'    => '#120608',
			'bg2'    => '#0e0406',
			'bg3'    => '#0a0304',
			'accent' => '#e11d48',
			'border' => '#300a14',
			'muted'  => '#5a2030',
		),
	);
	$_theme_key = sanitize_key( $_POST['email_theme'] ?? 'midnight' );
	$_theme_cfg = $themes_map[ $_theme_key ] ?? $themes_map['midnight'];
	$_accent_ov = sanitize_hex_color( $_POST['email_accent_color_override'] ?? '' );
	if ( $_accent_ov ) {
		$_theme_cfg['accent'] = $_accent_ov;
	}
	$_theme_cfg['logo_url']  = esc_url_raw( $_POST['email_logo_url'] ?? '' );
	$_theme_cfg['theme_key'] = $_theme_key;
	file_put_contents( '/home/glorszmt/gtbogo-private/email-theme-config.json', wp_json_encode( $_theme_cfg, JSON_PRETTY_PRINT ) ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents

	$message      = 'Settings saved.';
	$message_type = 'success';
}

// ── Fetch current ─────────────────────────────────────────────────────────────
$s = array(
	'auto_add'                    => get_option( 'gtbogo_auto_add', true ),
	'auto_remove'                 => get_option( 'gtbogo_auto_remove', true ),
	'show_discount_label'         => get_option( 'gtbogo_show_discount_label', true ),
	'discount_label_text'         => get_option( 'gtbogo_discount_label_text', 'Free' ),
	'cart_notice'                 => get_option( 'gtbogo_cart_notice', true ),
	'cart_notice_pos'             => get_option( 'gtbogo_cart_notice_pos', 'before_cart' ),
	'conflict_strategy'           => get_option( 'gtbogo_conflict_strategy', 'highest_priority' ),
	'max_discount_pct'            => get_option( 'gtbogo_max_discount_pct', 0 ),
	'exclude_roles'               => (array) get_option( 'gtbogo_exclude_roles', array() ),
	'show_badge'                  => get_option( 'gtbogo_show_badge', true ),
	'badge_position'              => get_option( 'gtbogo_badge_position', 'top_left' ),
	'badge_inherit_theme'         => get_option( 'gtbogo_badge_inherit_theme', true ),
	'progress_bar'                => get_option( 'gtbogo_progress_bar', true ),
	'progress_bar_pos'            => get_option( 'gtbogo_progress_bar_pos', 'before_cart' ),
	'cache_rules'                 => get_option( 'gtbogo_cache_rules', true ),
	'cache_ttl'                   => get_option( 'gtbogo_cache_ttl', 300 ),
	'ajax_cart'                   => get_option( 'gtbogo_ajax_cart', true ),
	'analytics_enabled'           => get_option( 'gtbogo_analytics_enabled', true ),
	'analytics_retention'         => get_option( 'gtbogo_analytics_retention_days', 90 ),
	'analytics_excl'              => (array) get_option( 'gtbogo_analytics_exclude_roles', array() ),
	'log_enabled'                 => get_option( 'gtbogo_log_enabled', true ),
	'log_max_entries'             => get_option( 'gtbogo_log_max_entries', 1000 ),
	'log_min_level'               => get_option( 'gtbogo_log_min_level', 'info' ),
	'log_alert_on_error'          => get_option( 'gtbogo_log_alert_on_error', false ),
	'log_alert_email'             => get_option( 'gtbogo_log_alert_email', get_option( 'admin_email' ) ),
	'referral_enabled'            => get_option( 'gtbogo_referral_enabled', false ),
	'referral_reward_count'       => get_option( 'gtbogo_referral_reward_count', 3 ),
	'referral_reward_type'        => get_option( 'gtbogo_referral_reward_type', 'percent' ),
	'referral_reward_value'       => get_option( 'gtbogo_referral_reward_value', 20 ),
	'referral_reward_label'       => get_option( 'gtbogo_referral_reward_label', '' ),
	'require_account_for_deals'   => get_option( 'gtbogo_require_account_for_deals', false ),
	'registration_prompt_message' => get_option( 'gtbogo_registration_prompt_message', '' ),
	'double_optin_enabled'        => get_option( 'gtbogo_double_optin_enabled', false ),
	'optin_on_registration'       => get_option( 'gtbogo_optin_on_registration', false ),
	'optin_checkbox_label'        => get_option( 'gtbogo_optin_checkbox_label', '' ),
	'customer_emails_enabled'     => get_option( 'gtbogo_customer_emails_enabled', false ),
	'email_theme'                 => get_option( 'gtbogo_email_theme', 'midnight' ),
	'email_accent_override'       => get_option( 'gtbogo_email_accent_color', '' ),
	'email_logo_url'              => get_option( 'gtbogo_email_logo_url', '' ),
	'debug_mode'                  => get_option( 'gtbogo_debug_mode', false ),
	'uninstall_data'              => get_option( 'gtbogo_uninstall_data', false ),
);

$wp_roles = wp_roles()->get_names();

// ── Email themes definition ───────────────────────────────────────────────────
$email_themes = array(
	'midnight' => array(
		'name'   => 'Midnight',
		'accent' => '#E10000',
		'bg'     => '#070C1C',
		'desc'   => 'Deep navy, red accent. The GT BOGO default.',
	),
	'ocean'    => array(
		'name'   => 'Ocean',
		'accent' => '#0ea5e9',
		'bg'     => '#040d1a',
		'desc'   => 'Deep blue. Suits tech, electronics, software.',
	),
	'forest'   => array(
		'name'   => 'Forest',
		'accent' => '#16a34a',
		'bg'     => '#04100a',
		'desc'   => 'Deep green. Suits health, organic, outdoors.',
	),
	'royal'    => array(
		'name'   => 'Royal',
		'accent' => '#7c3aed',
		'bg'     => '#0a0714',
		'desc'   => 'Deep violet. Suits luxury, beauty, fashion.',
	),
	'obsidian' => array(
		'name'   => 'Obsidian',
		'accent' => '#d97706',
		'bg'     => '#0a0a08',
		'desc'   => 'Black and amber. Suits premium, artisan goods.',
	),
	'ember'    => array(
		'name'   => 'Ember',
		'accent' => '#ea580c',
		'bg'     => '#110804',
		'desc'   => 'Deep ember. Suits food, lifestyle, sports.',
	),
	'slate'    => array(
		'name'   => 'Slate',
		'accent' => '#06b6d4',
		'bg'     => '#080d14',
		'desc'   => 'Dark slate, cyan. Suits SaaS and services.',
	),
	'rose'     => array(
		'name'   => 'Rose',
		'accent' => '#e11d48',
		'bg'     => '#120608',
		'desc'   => 'Deep rose. Suits fashion, gifts, cosmetics.',
	),
	'gold'     => array(
		'name'   => 'Gold',
		'accent' => '#f59e0b',
		'bg'     => '#0a0800',
		'desc'   => 'Black and gold. Suits luxury, jewellery, premium.',
	),
	'coral'    => array(
		'name'   => 'Coral',
		'accent' => '#f43f5e',
		'bg'     => '#120409',
		'desc'   => 'Dark coral. Suits beauty, wellness, lifestyle.',
	),
	'indigo'   => array(
		'name'   => 'Indigo',
		'accent' => '#6366f1',
		'bg'     => '#06060f',
		'desc'   => 'Deep indigo. Suits creative, digital, agency.',
	),
	'mint'     => array(
		'name'   => 'Mint',
		'accent' => '#10b981',
		'bg'     => '#030e08',
		'desc'   => 'Dark mint. Suits eco, organic, wellness brands.',
	),
	'crimson'  => array(
		'name'   => 'Crimson',
		'accent' => '#dc2626',
		'bg'     => '#0f0303',
		'desc'   => 'Pure crimson. High urgency, flash sales, sports.',
	),
	'steel'    => array(
		'name'   => 'Steel',
		'accent' => '#64748b',
		'bg'     => '#080a0c',
		'desc'   => 'Dark steel. Suits B2B, industrial, automotive.',
	),
);

require_once __DIR__ . '/../ui-system/wrapper-start.php';
?>
<div class="gt-page-header gt-animate-in">
	<div>
		<h1 class="gt-page-title">&#9881;&#65039; Settings</h1>
		<p class="gt-page-subtitle">Global plugin configuration — cart behaviour, display, performance, analytics, and advanced options</p>
	</div>
	<span class="gt-badge gt-badge-free">v<?php echo esc_html( $version ); ?></span>
</div>
<?php
if ( $message ) :
	?>
	<div class="gt-notice gt-notice-<?php echo esc_attr( $message_type ); ?> gt-animate-in">&#10003; <?php echo esc_html( $message ); ?></div><?php endif; ?>

<form method="post" action="">
<?php wp_nonce_field( 'gtbogo_save_settings' ); ?>

<!-- ── CART & CHECKOUT ──────────────────────────────────────────────────── -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header">
		<h2 class="gt-card-title">&#128717; Cart &amp; Checkout Behaviour</h2>
	</div>
	<div class="gt-setting-row">
		<div><div class="gt-setting-label">Auto-Add Free Item</div><div class="gt-setting-desc">When a customer qualifies for a BOGO deal, automatically add the complimentary item to their cart. If disabled, customers must add the item manually.</div></div>
		<label class="gt-toggle"><input type="checkbox" name="auto_add" value="1" <?php checked( $s['auto_add'] ); ?>><span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span></label>
	</div>
	<div class="gt-setting-row">
		<div><div class="gt-setting-label">Auto-Remove When Unqualified</div><div class="gt-setting-desc">If the customer removes items and no longer qualifies, automatically remove the auto-added complimentary item from the cart.</div></div>
		<label class="gt-toggle"><input type="checkbox" name="auto_remove" value="1" <?php checked( $s['auto_remove'] ); ?>><span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span></label>
	</div>
	<div class="gt-setting-row">
		<div><div class="gt-setting-label">Show Discount Line Label</div><div class="gt-setting-desc">Display a label next to discounted items in the cart (e.g. "Complimentary"). Inherits your theme's cart line styling.</div></div>
		<label class="gt-toggle"><input type="checkbox" name="show_discount_label" value="1" <?php checked( $s['show_discount_label'] ); ?>><span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span></label>
	</div>
	<div class="gt-setting-row">
		<div><div class="gt-setting-label">Discount Label Text</div><div class="gt-setting-desc">Short label shown next to the discounted cart line. No exclamation marks.</div></div>
		<input type="text" name="discount_label_text" class="gt-input" style="max-width:220px" value="<?php echo esc_attr( $s['discount_label_text'] ); ?>" placeholder="Complimentary" maxlength="32" id="gtbogo_discount_label_text" aria-label="Discount Label Text">
	</div>
	<div class="gt-setting-row">
		<div><div class="gt-setting-label">Show Cart Progress Notice</div><div class="gt-setting-desc">Display a message in the cart when the customer is close to qualifying for a deal. Encourages them to add another item.</div></div>
		<label class="gt-toggle"><input type="checkbox" name="cart_notice" value="1" <?php checked( $s['cart_notice'] ); ?>><span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span></label>
	</div>
	<div class="gt-setting-row">
		<div><div class="gt-setting-label">Cart Notice Position</div></div>
		<select name="cart_notice_pos" class="gt-select" style="width:220px">
			<option value="before_cart" <?php selected( $s['cart_notice_pos'], 'before_cart' ); ?>>Before cart table</option>
			<option value="after_cart"  <?php selected( $s['cart_notice_pos'], 'after_cart' ); ?>>After cart table</option>
			<option value="cart_totals" <?php selected( $s['cart_notice_pos'], 'cart_totals' ); ?>>Above cart totals</option>
		</select>
	</div>
	<div class="gt-setting-row">
		<div><div class="gt-setting-label">Rule Conflict Strategy</div><div class="gt-setting-desc">When multiple PRO rules are eligible for the same cart, this determines which rule fires.</div></div>
		<select name="conflict_strategy" class="gt-select" style="width:220px">
			<option value="highest_priority"  <?php selected( $s['conflict_strategy'], 'highest_priority' ); ?>>Highest priority rule wins</option>
			<option value="best_for_customer" <?php selected( $s['conflict_strategy'], 'best_for_customer' ); ?>>Best deal for customer</option>
			<option value="all_eligible"      <?php selected( $s['conflict_strategy'], 'all_eligible' ); ?>>All eligible rules stack</option>
			<option value="first_match"       <?php selected( $s['conflict_strategy'], 'first_match' ); ?>>First match only</option>
		</select>
	</div>
	<div class="gt-setting-row">
		<div><div class="gt-setting-label">Maximum Discount Per Order (%)</div><div class="gt-setting-desc">Cap the total BOGO discount as a percentage of the cart subtotal. 0 = no cap. Use to protect against stacking that pushes orders into negative margin.</div></div>
		<input type="number" name="max_discount_pct" class="gt-input" style="width:100px" value="<?php echo esc_attr( $s['max_discount_pct'] ); ?>" min="0" max="100" id="gtbogo_max_discount_pct" aria-label="Max Discount Pct">
	</div>
	<div style="padding:16px 20px 20px;border-top:1px solid var(--gt-border)">
		<div class="gt-form-label" style="margin-bottom:10px">Exclude User Roles from All BOGO Rules</div>
		<div style="display:flex;flex-wrap:wrap;gap:8px">
			<?php
			foreach ( $wp_roles as $slug => $name ) :
				$sel = in_array( $slug, $s['exclude_roles'] );
				?>
			<label style="display:flex;align-items:center;gap:6px;cursor:pointer;padding:6px 12px;border-radius:8px;border:1px solid <?php echo $sel ? 'var(--gt-red)' : ' var(--gt-border)'; ?>;background:<?php echo $sel ? 'rgba(225,0,0,0.08)' : ' rgba(255,255,255,0.02)'; ?>;font-size:13px;color:var(--gt-soft)">
				<input type="checkbox" name="exclude_roles[]" value="<?php echo esc_attr( $slug ); ?>" <?php checked( $sel ); ?> style="accent-color:var(--gt-red)">
				<?php echo esc_html( $name ); ?>
			</label>
			<?php endforeach; ?>
		</div>
		<div class="gt-form-hint" style="margin-top:8px">Checked roles are never shown BOGO deals. Use for wholesale, admin, or staff accounts.</div>
	</div>
</div>

<!-- ── DISPLAY ──────────────────────────────────────────────────────────── -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header"><h2 class="gt-card-title">&#127912; Display Settings</h2></div>
	<div class="gt-setting-row">
		<div><div class="gt-setting-label">Show Product Badge</div><div class="gt-setting-desc">Display a badge on eligible product images. The badge inherits your active theme's styling — no hardcoded colours or fonts.</div></div>
		<label class="gt-toggle"><input type="checkbox" name="show_badge" value="1" <?php checked( $s['show_badge'] ); ?>><span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span></label>
	</div>
	<div class="gt-setting-row">
		<div><div class="gt-setting-label">Badge Position</div></div>
		<select name="badge_position" class="gt-select" style="width:220px">
			<option value="top_left"     <?php selected( $s['badge_position'], 'top_left' ); ?>>Top left</option>
			<option value="top_right"    <?php selected( $s['badge_position'], 'top_right' ); ?>>Top right</option>
			<option value="bottom_left"  <?php selected( $s['badge_position'], 'bottom_left' ); ?>>Bottom left</option>
			<option value="bottom_right" <?php selected( $s['badge_position'], 'bottom_right' ); ?>>Bottom right</option>
		</select>
	</div>
	<div class="gt-setting-row">
		<div><div class="gt-setting-label">Badge Inherits Theme Styling</div><div class="gt-setting-desc">When enabled, the badge uses your theme's colours and font. When disabled, it uses the plugin default (navy + white). Luxury brand safe — recommended on.</div></div>
		<label class="gt-toggle"><input type="checkbox" name="badge_inherit_theme" value="1" <?php checked( $s['badge_inherit_theme'] ); ?>><span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span></label>
	</div>
	<div class="gt-setting-row">
		<div><div class="gt-setting-label">Show Cart Progress Bar</div><div class="gt-setting-desc">Display a progress bar in the cart showing how close the customer is to qualifying. Uses the Cart Progress Bar superpower when available.</div></div>
		<label class="gt-toggle"><input type="checkbox" name="progress_bar" value="1" <?php checked( $s['progress_bar'] ); ?>><span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span></label>
	</div>
	<div class="gt-setting-row" style="border:none">
		<div><div class="gt-setting-label">Progress Bar Position</div></div>
		<select name="progress_bar_pos" class="gt-select" style="width:220px">
			<option value="before_cart" <?php selected( $s['progress_bar_pos'], 'before_cart' ); ?>>Before cart table</option>
			<option value="after_cart"  <?php selected( $s['progress_bar_pos'], 'after_cart' ); ?>>After cart table</option>
			<option value="cart_totals" <?php selected( $s['progress_bar_pos'], 'cart_totals' ); ?>>Above cart totals</option>
		</select>
	</div>
</div>

<!-- ── PERFORMANCE ──────────────────────────────────────────────────────── -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header"><h2 class="gt-card-title">&#9889; Performance</h2></div>
	<div class="gt-setting-row">
		<div><div class="gt-setting-label">Cache Active Rules</div><div class="gt-setting-desc">Cache the active rule set using WordPress transients. Dramatically reduces database queries on high-traffic stores. The cache is automatically cleared when rules are saved.</div></div>
		<label class="gt-toggle"><input type="checkbox" name="cache_rules" data-option="gtbogo_cache_rules" value="1" <?php checked( $s['cache_rules'] ); ?>><span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span></label>
	</div>
	<div class="gt-setting-row">
		<div><div class="gt-setting-label">Cache TTL (seconds)</div><div class="gt-setting-desc">How long to cache the active rule set before refreshing from the database. 300 seconds (5 minutes) is recommended.</div></div>
		<input type="number" name="cache_ttl" class="gt-input" style="width:120px" value="<?php echo esc_attr( $s['cache_ttl'] ); ?>" min="30" max="3600" id="gtbogo_cache_ttl" aria-label="Cache Ttl">
	</div>
	<div class="gt-setting-row" style="border:none">
		<div><div class="gt-setting-label">AJAX Cart Compatibility</div><div class="gt-setting-desc">Enable compatibility with AJAX-based cart plugins (e.g. CartFlows, SureCart). Triggers rule evaluation on AJAX cart update events. Disable if you experience double-discount issues with custom cart plugins.</div></div>
		<label class="gt-toggle"><input type="checkbox" name="ajax_cart" value="1" <?php checked( $s['ajax_cart'] ); ?>><span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span></label>
	</div>
</div>

<!-- ── ANALYTICS ────────────────────────────────────────────────────────── -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header"><h2 class="gt-card-title">&#128202; Analytics</h2></div>
	<div class="gt-setting-row">
		<div><div class="gt-setting-label">Enable Analytics Tracking</div><div class="gt-setting-desc">Record order-level BOGO data (rule triggered, order total, discount amount) for the Analytics dashboard. Data is stored locally — no external services.</div></div>
		<label class="gt-toggle"><input type="checkbox" name="analytics_enabled" data-option="gtbogo_analytics_enabled" value="1" <?php checked( $s['analytics_enabled'] ); ?>><span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span></label>
	</div>
	<div class="gt-setting-row">
		<div><div class="gt-setting-label">Data Retention (days)</div><div class="gt-setting-desc">Analytics records older than this are automatically purged. 90 days is recommended. Set 0 to retain indefinitely (not recommended on high-volume stores).</div></div>
		<input type="number" name="analytics_retention" class="gt-input" style="width:120px" value="<?php echo esc_attr( $s['analytics_retention'] ); ?>" min="0" max="730" id="gtbogo_analytics_retention" aria-label="Analytics Retention">
	</div>
	<div style="padding:16px 20px 20px;border-top:1px solid var(--gt-border)">
		<div class="gt-form-label" style="margin-bottom:10px">Exclude Roles from Analytics</div>
		<div style="display:flex;flex-wrap:wrap;gap:8px">
			<?php
			foreach ( $wp_roles as $slug => $name ) :
				$sel = in_array( $slug, $s['analytics_excl'] );
				?>
			<label style="display:flex;align-items:center;gap:6px;cursor:pointer;padding:6px 12px;border-radius:8px;border:1px solid <?php echo $sel ? 'var(--gt-red)' : ' var(--gt-border)'; ?>;background:<?php echo $sel ? 'rgba(225,0,0,0.08)' : ' rgba(255,255,255,0.02)'; ?>;font-size:13px;color:var(--gt-soft)">
				<input type="checkbox" name="analytics_exclude_roles[]" value="<?php echo esc_attr( $slug ); ?>" <?php checked( $sel ); ?> style="accent-color:var(--gt-red)">
				<?php echo esc_html( $name ); ?>
			</label>
			<?php endforeach; ?>
		</div>
		<div class="gt-form-hint" style="margin-top:8px">Orders from excluded roles are not recorded in analytics. Exclude administrator to keep internal test orders out of your data.</div>
	</div>
</div>

<!-- ── AUDIT LOG ─────────────────────────────────────────────────────────── -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header"><h2 class="gt-card-title">&#128203; Audit Log</h2></div>
	<div class="gt-setting-row">
		<div><div class="gt-setting-label">Enable Audit Logging</div><div class="gt-setting-desc">Log all plugin events — rule saves, activations, deactivations, imports, and errors. Essential for compliance and troubleshooting.</div></div>
		<label class="gt-toggle"><input type="checkbox" name="log_enabled" value="1" <?php checked( $s['log_enabled'] ); ?>><span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span></label>
	</div>
	<div class="gt-setting-row">
		<div><div class="gt-setting-label">Maximum Log Entries</div><div class="gt-setting-desc">Auto-purge oldest entries when this limit is reached. Recommended: 1000 for most stores.</div></div>
		<input type="number" name="log_max_entries" class="gt-input" style="width:120px" value="<?php echo esc_attr( $s['log_max_entries'] ); ?>" min="100" max="10000" id="gtbogo_log_max_entries" aria-label="Log Max Entries">
	</div>
	<div class="gt-setting-row">
		<div><div class="gt-setting-label">Minimum Log Level</div><div class="gt-setting-desc">Only events at or above this level are recorded. "Info" captures everything; "Error" captures only failures.</div></div>
		<select name="log_min_level" class="gt-select" style="width:180px">
			<option value="info"  <?php selected( $s['log_min_level'], 'info' ); ?>>Info (all events)</option>
			<option value="warn"  <?php selected( $s['log_min_level'], 'warn' ); ?>>Warn and Error only</option>
			<option value="error" <?php selected( $s['log_min_level'], 'error' ); ?>>Error only</option>
		</select>
	</div>
	<div class="gt-setting-row">
		<div><div class="gt-setting-label">Email Alert on Error</div><div class="gt-setting-desc">Send an email when an error-level event is logged. Useful for catching license failures, import errors, or rule execution exceptions immediately.</div></div>
		<label class="gt-toggle"><input type="checkbox" name="log_alert_on_error" value="1" <?php checked( $s['log_alert_on_error'] ); ?>><span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span></label>
	</div>
	<div class="gt-setting-row" style="border:none">
		<div><div class="gt-setting-label">Alert Email Address</div><div class="gt-setting-desc">Email address to notify when an error-level event is logged.</div></div>
		<input type="email" name="log_alert_email" class="gt-input" style="width:280px" value="<?php echo esc_attr( $s['log_alert_email'] ); ?>" id="gtbogo_log_alert_email" aria-label="Log Alert Email">
	</div>
</div>

<!-- ── REFERRAL REWARDS ──────────────────────────────────────────────────── -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header">
		<h2 class="gt-card-title">&#128279; Referral Rewards</h2>
		<span class="gt-text-soft" style="font-size:13px">Reward customers who refer new buyers — automated, tracked, zero manual work</span>
	</div>
	<div class="gt-setting-row">
		<div><div class="gt-setting-label">Enable Referral Rewards</div><div class="gt-setting-desc">Generates a unique referral link for each logged-in customer. When a referred friend completes a purchase, the referrer earns progress toward a reward. Email updates sent automatically at each milestone.</div></div>
		<label class="gt-toggle"><input type="checkbox" name="referral_enabled" value="1" <?php checked( ! empty( $s['referral_enabled'] ) ); ?>><span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span></label>
	</div>
	<div class="gt-setting-row">
		<div><div class="gt-setting-label">Referrals Needed for Reward</div><div class="gt-setting-desc">How many successful referrals a customer must make before their reward is applied. A referral counts when the referred customer completes their first order.</div></div>
		<input type="number" name="referral_reward_count" class="gt-input" style="max-width:80px" min="1" max="50" value="<?php echo esc_attr( $s['referral_reward_count'] ); ?>" id="gtbogo_referral_reward_count" aria-label="Referral Reward Count">
	</div>
	<div class="gt-setting-row">
		<div><div class="gt-setting-label">Reward Type</div><div class="gt-setting-desc">How the reward is applied to the referrer's next order.</div></div>
		<select name="referral_reward_type" class="gt-select" style="max-width:200px">
			<option value="percent"   <?php selected( $s['referral_reward_type'], 'percent' ); ?>>Percentage Discount</option>
			<option value="fixed"     <?php selected( $s['referral_reward_type'], 'fixed' ); ?>>Fixed Amount Off</option>
			<option value="free_item" <?php selected( $s['referral_reward_type'], 'free_item' ); ?>>Free Item (BOGO)</option>
		</select>
	</div>
	<div class="gt-setting-row">
		<div><div class="gt-setting-label">Reward Value</div><div class="gt-setting-desc">Percentage (e.g. 20 for 20% off) or fixed amount (e.g. 10 for $10 off). Not used for Free Item type.</div></div>
		<input type="number" name="referral_reward_value" class="gt-input" style="max-width:100px" min="1" max="100" step="0.01" value="<?php echo esc_attr( $s['referral_reward_value'] ); ?>" id="gtbogo_referral_reward_value" aria-label="Referral Reward Value">
	</div>
	<div class="gt-setting-row" style="border:none">
		<div><div class="gt-setting-label">Reward Label</div><div class="gt-setting-desc">What the customer sees as their reward description in emails and the referral widget. e.g. "20% off your next order".</div></div>
		<input type="text" name="referral_reward_label" class="gt-input" style="max-width:260px" value="<?php echo esc_attr( $s['referral_reward_label'] ); ?>" placeholder="e.g. 20% off your next order" id="gtbogo_referral_reward_label" aria-label="Referral Reward Label">
	</div>
	<div class="gt-setting-row">
		<div><div class="gt-setting-label">Strict GDPR Mode — Consent-Gated Intelligence</div><div class="gt-setting-desc">When enabled, visitor intelligence signals are only collected after explicit tracking consent. Anonymous visitors receive standard deals with no personalisation. Recommended for EU, UK, and Swiss stores under strict GDPR interpretation.</div></div>
		<label class="gt-toggle"><input type="checkbox" name="gdpr_strict_mode" value="1" <?php checked( (bool) get_option( 'gtbogo_gdpr_strict_mode', 0 ) ); ?>><span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span></label>
	</div>
	<div style="padding:14px 20px;background:rgba(34,197,94,0.05);border-top:1px solid var(--gt-border);border-radius:0 0 12px 12px">
		<p style="margin:0;font-size:13px;color:var(--gt-subtle)">&#128231; Customers receive an email after every referral showing their progress toward the reward. When the threshold is reached a coupon is generated automatically and emailed to them. Requires Customer Emails to be enabled.</p>
	</div>
</div>

<!-- ── GUEST & OPT-IN ────────────────────────────────────────────────────── -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header">
		<h2 class="gt-card-title">&#128100; Guest Customers &amp; Opt-In</h2>
		<span class="gt-text-soft" style="font-size:13px">Control how guest shoppers interact with deals and manage marketing consent</span>
	</div>
	<div class="gt-setting-row">
		<div><div class="gt-setting-label">Show Registration Prompt to Guests with Deals</div><div class="gt-setting-desc">When a guest has a BOGO deal in their cart, show a gentle prompt above checkout encouraging them to create a free account to earn loyalty rewards. Does not block checkout.</div></div>
		<label class="gt-toggle"><input type="checkbox" name="require_account_for_deals" value="1" <?php checked( ! empty( $s['require_account_for_deals'] ) ); ?>><span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span></label>
	</div>
	<div class="gt-setting-row">
		<div><div class="gt-setting-label">Registration Prompt Message</div><div class="gt-setting-desc">The message shown to guests above checkout when they have a deal active. Encourage account creation without blocking the purchase.</div></div>
		<textarea name="registration_prompt_message" class="gt-input" style="max-width:320px;height:68px;resize:vertical" placeholder="Create a free account to keep your deal and track future orders."><?php echo esc_textarea( $s['registration_prompt_message'] ); ?></textarea>
	</div>
	<div class="gt-setting-row">
		<div><div class="gt-setting-label">Enable Email Double Opt-In</div><div class="gt-setting-desc">When enabled, customers who check the marketing email box at checkout receive a verification email. Only confirmed subscribers receive deal emails. Fully GDPR and CAN-SPAM compliant.</div></div>
		<label class="gt-toggle"><input type="checkbox" name="double_optin_enabled" value="1" <?php checked( ! empty( $s['double_optin_enabled'] ) ); ?>><span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span></label>
	</div>
	<div class="gt-setting-row">
		<div><div class="gt-setting-label">Also Verify New Account Registrations</div><div class="gt-setting-desc">Send a verification email when a new customer creates an account, not just at checkout. Ensures your email list only contains verified addresses.</div></div>
		<label class="gt-toggle"><input type="checkbox" name="optin_on_registration" value="1" <?php checked( ! empty( $s['optin_on_registration'] ) ); ?>><span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span></label>
	</div>
	<div class="gt-setting-row" style="border:none">
		<div><div class="gt-setting-label">Opt-In Checkbox Label</div><div class="gt-setting-desc">The label shown next to the marketing consent checkbox at checkout. Be clear and specific — customers must know what they are signing up for.</div></div>
		<input type="text" name="optin_checkbox_label" class="gt-input" style="max-width:360px" value="<?php echo esc_attr( $s['optin_checkbox_label'] ); ?>" placeholder="Yes — email me exclusive deals and early access. I can unsubscribe anytime." id="gtbogo_optin_checkbox_label" aria-label="Optin Checkbox Label">
	</div>
	<div style="padding:14px 20px;background:rgba(34,197,94,0.05);border-top:1px solid var(--gt-border);border-radius:0 0 12px 12px">
		<p style="margin:0;font-size:13px;color:var(--gt-subtle)">&#128274; Double opt-in verification links expire after 24 hours. Verified subscribers are automatically assigned the subscriber role for deal access. Guest deals apply to all visitors — only role-gated deals (VIP, loyalty) require login.</p>
	</div>
</div>

<!-- ── CUSTOMER EMAILS ───────────────────────────────────────────────────── -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header">
		<h2 class="gt-card-title">&#9993;&#65039; Customer Emails</h2>
		<span class="gt-text-soft" style="font-size:13px">White-labelled transactional emails sent to your customers — uses your store name and logo</span>
	</div>
	<div class="gt-setting-row">
		<div><div class="gt-setting-label">Enable Customer Emails</div><div class="gt-setting-desc">Sends branded transactional emails to customers for BOGO confirmations, tier upgrades, streak rewards, referrals, free gifts, deal expiry, cart nudges and winback campaigns. Uses your store name and logo — GT BOGO Engine is never visible to your customers.</div></div>
		<label class="gt-toggle"><input type="checkbox" name="customer_emails_enabled" data-option="gtbogo_customer_emails_enabled" value="1" <?php checked( ! empty( $s['customer_emails_enabled'] ) ); ?>><span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span></label>
	</div>

	<!-- Email Theme Picker -->
	<div style="padding:20px 20px 0;border-top:1px solid var(--gt-border)">
		<div class="gt-form-label" style="margin-bottom:6px">Email Theme</div>
		<div class="gt-form-hint" style="margin-bottom:16px">Choose a dark email theme for all customer-facing emails. Each theme is a complete coordinated colour palette — backgrounds, borders, accents, and text all designed together.</div>
		<div style="display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px;margin-bottom:24px">
			<?php
			foreach ( $email_themes as $key => $t ) :
				$active = ( $s['email_theme'] === $key );
				?>
			<label style="cursor:pointer;display:block;">
				<input type="radio" name="email_theme" value="<?php echo esc_attr( $key ); ?>" <?php checked( $s['email_theme'], $key ); ?> style="position:absolute;opacity:0;width:0;height:0" onchange="gtUpdateThemeSwatch('<?php echo esc_attr( $key ); ?>')">
				<div class="gt-email-swatch" data-theme="<?php echo esc_attr( $key ); ?>" style="border-radius:8px;overflow:hidden;border:2px solid <?php echo $active ? 'var(--gt-red)' : ' var(--gt-border)'; ?>;transition:border-color 0.15s;cursor:pointer" onclick="this.previousElementSibling.click()">
					<div style="height:4px;background:<?php echo esc_attr( $t['accent'] ); ?>"></div>
					<div style="background:<?php echo esc_attr( $t['bg'] ); ?>;padding:10px 12px;">
						<div style="display:flex;align-items:center;gap:7px;margin-bottom:7px">
							<div style="width:18px;height:18px;border-radius:3px;background:<?php echo esc_attr( $t['accent'] ); ?>22;border:1px solid <?php echo esc_attr( $t['accent'] ); ?>44;flex-shrink:0"></div>
							<span style="font-size:13px;font-weight:700;color:#fff;font-family:sans-serif"><?php echo esc_html( $t['name'] ); ?></span>
						</div>
						<div style="height:1px;background:<?php echo esc_attr( $t['accent'] ); ?>;margin-bottom:7px;opacity:0.8"></div>
						<div style="font-size:13px;color:<?php echo esc_attr( $t['accent'] ); ?>;font-family:sans-serif;letter-spacing:1.5px;text-transform:uppercase;margin-bottom:4px">Purchase confirmed</div>
						<div style="font-size:13px;font-weight:700;color:#fff;font-family:Georgia,serif;line-height:1.3;margin-bottom:7px">Your order<br>is ready.</div>
						<div style="background:<?php echo esc_attr( $t['accent'] ); ?>;border-radius:3px;padding:5px 0;text-align:center;font-size:13px;font-weight:700;color:#fff;font-family:sans-serif;letter-spacing:1px">VIEW ORDER</div>
					</div>
					<div style="height:4px;background:<?php echo esc_attr( $t['accent'] ); ?>"></div>
					<div style="background:#1a1a1a;padding:5px 10px;text-align:center">
						<span style="font-size:13px;color:#999;font-family:sans-serif"><?php echo esc_html( $t['desc'] ); ?></span>
					</div>
				</div>
			</label>
			<?php endforeach; ?>
		</div>

		<div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;padding-bottom:20px">
			<div>
				<div class="gt-form-label" style="margin-bottom:6px">Accent Color Override <span style="font-weight:400;font-size:13px;color:var(--gt-subtle)">— optional</span></div>
				<div style="display:flex;align-items:center;gap:10px">
					<input type="color" id="gtEmailAccentPicker" value="<?php echo esc_attr( $s['email_accent_override'] ?: '#E10000' ); ?>" style="width:44px;height:36px;border:1px solid var(--gt-border);border-radius:6px;background:transparent;cursor:pointer;padding:2px" oninput="document.getElementById('gtEmailAccentText').value=this.value;document.getElementById('gtEmailAccentHidden').value=this.value">
					<input type="text" id="gtEmailAccentText" value="<?php echo esc_attr( $s['email_accent_override'] ); ?>" class="gt-input" style="max-width:120px;font-family:monospace" placeholder="Leave blank for theme default" maxlength="7" oninput="document.getElementById('gtEmailAccentPicker').value=this.value;document.getElementById('gtEmailAccentHidden').value=this.value">
					<input type="hidden" name="email_accent_color_override" id="gtEmailAccentHidden" value="<?php echo esc_attr( $s['email_accent_override'] ); ?>">
				</div>
			</div>
			<div class="gt-setting-row">
				<div>
					<div class="gt-setting-label">Superpower Accent Color</div>
					<div class="gt-setting-desc">Color used by frontend superpowers — announcement bar, progress bar, badges, nudges, social proof. Independent from email. Use your store brand color.</div>
				</div>
				<div style="display:flex;align-items:center;gap:8px">
					<input type="color" id="gtSpAccentPicker" name="sp_accent_color"
							value="<?php echo esc_attr( get_option( 'gtbogo_sp_accent_color', '#E10000' ) ); ?>"
							style="width:44px;height:36px;border:1px solid var(--gt-border);border-radius:6px;background:transparent;cursor:pointer;padding:2px"
							oninput="document.getElementById('gtSpAccentText').value=this.value">
					<input type="text" id="gtSpAccentText"
							value="<?php echo esc_attr( get_option( 'gtbogo_sp_accent_color', '#E10000' ) ); ?>"
							class="gt-input" style="max-width:120px;font-family:monospace" placeholder="#E10000" maxlength="7"
							oninput="document.getElementById('gtSpAccentPicker').value=this.value">
					<span style="font-size:12px;color:var(--gt-subtle)">Hex color for store-facing superpowers</span>
					<button type="button" onclick="document.getElementById('gtEmailAccentPicker').value='#E10000';document.getElementById('gtEmailAccentText').value='';document.getElementById('gtEmailAccentHidden').value='';" style="padding:8px 12px;background:rgba(255,255,255,0.05);border:1px solid var(--gt-border);border-radius:6px;color:var(--gt-subtle);font-size:13px;cursor:pointer;">Clear</button>
				</div>
				<div class="gt-form-hint" style="margin-top:6px">Overrides the theme accent for buttons, borders and highlights. Leave blank to use the selected theme's default colour.</div>
			</div>
			<div>
				<div class="gt-form-label" style="margin-bottom:6px">Email Logo URL <span style="font-weight:400;font-size:13px;color:var(--gt-subtle)">— optional</span></div>
				<input type="url" name="email_logo_url" class="gt-input" style="width:100%" value="<?php echo esc_attr( $s['email_logo_url'] ); ?>" placeholder="https://yourstore.com/logo.png" id="gtbogo_email_logo_url" aria-label="Email Logo Url">
				<div class="gt-form-hint" style="margin-top:6px">Leave blank to use your WordPress site icon. Square PNG, 144&#215;144px recommended.</div>
				<?php if ( $s['email_logo_url'] ) : ?>
				<div style="margin-top:8px;padding:8px;background:rgba(255,255,255,0.03);border:1px solid var(--gt-border);border-radius:6px;display:inline-block">
					<img src="<?php echo esc_url( $s['email_logo_url'] ); ?>" style="height:40px;width:auto;display:block" alt="Logo preview">
				</div>
				<?php endif; ?>
			</div>
		</div>
	</div>
	<div style="padding:14px 20px;background:rgba(34,197,94,0.05);border-top:1px solid var(--gt-border);border-radius:0 0 12px 12px">
		<p style="margin:0;font-size:13px;color:var(--gt-subtle)">&#128236; Emails are sent via your WordPress mail configuration (wp_mail). For reliable delivery configure SMTP in your WordPress settings or use a mail plugin like WP Mail SMTP. Extended delivery via Mailchimp or Klaviyo is available in the <a href="<?php echo esc_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=integrations' ) ); ?>" style="color:var(--gt-red)">Integrations page</a>.</p>
	</div>
</div>


<!-- ── INTELLIGENCE SYSTEMS ────────────────────────────────────────────── -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px;border-color:rgba(99,102,241,0.2)">
	<div class="gt-card-header"><h2 class="gt-card-title">&#129504; Intelligence Systems</h2></div>
	<p style="margin:0 0 20px;font-size:13px;color:var(--gt-subtle)">Backend intelligence that runs automatically. All systems are off by default — enable the ones relevant to your store. Zero frontend output. Zero customer visibility.</p>

	<div class="gt-setting-row">
		<div><div class="gt-setting-label">Cart Value Intelligence</div><div class="gt-setting-desc">Automatically adjusts discount depth based on cart total. High-value carts receive smaller discounts. Configure tiers below after enabling.</div></div>
		<label class="gt-toggle"><input type="checkbox" name="gtbogo_cart_value_enabled" value="1" <?php checked( get_option( 'gtbogo_cart_value_enabled', 0 ) ); ?>><span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span></label>
	</div>

	<div class="gt-setting-row">
		<div><div class="gt-setting-label">Conversion Timing Intelligence</div><div class="gt-setting-desc">Tracks each customer's peak purchase hours. Fires deals at the exact moment each customer is most likely to convert. Requires 3+ orders per customer before activating.</div></div>
		<label class="gt-toggle"><input type="checkbox" name="gtbogo_timing_enabled" value="1" <?php checked( get_option( 'gtbogo_timing_enabled', 0 ) ); ?>><span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span></label>
	</div>

	<div class="gt-setting-row">
		<div><div class="gt-setting-label">Price Sensitivity Detection</div><div class="gt-setting-desc">Detects hesitation signals — item removals, extended cart dwell time, repeated returns without checkout. Automatically applies a bonus discount when threshold is reached.</div></div>
		<label class="gt-toggle"><input type="checkbox" name="gtbogo_price_sensitivity_enabled" value="1" <?php checked( get_option( 'gtbogo_price_sensitivity_enabled', 0 ) ); ?>><span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span></label>
	</div>

	<?php if ( get_option( 'gtbogo_price_sensitivity_enabled', 0 ) ) : ?>
	<div class="gt-setting-row" style="padding-left:20px;border-left:2px solid rgba(99,102,241,0.3)">
		<div><div class="gt-setting-label">Sensitivity Threshold Score</div><div class="gt-setting-desc">Score required before bonus discount fires. Remove = +2pts, return = +3pts, idle minute = +1pt. Default: 6 (3 item removals).</div></div>
		<input type="number" name="gtbogo_sensitivity_threshold" value="<?php echo esc_attr( get_option( 'gtbogo_sensitivity_threshold', 6 ) ); ?>" min="3" max="20" style="width:80px;background:var(--gt-subtle-bg,#0f1a2e);border:1px solid var(--gt-border);border-radius:6px;padding:8px 10px;color:var(--gt-white);font-size:13px" id="gtbogo_gtbogo_sensitivity_threshold" aria-label="Gtbogo Sensitivity Threshold">
	</div>
	<div class="gt-setting-row" style="padding-left:20px;border-left:2px solid rgba(99,102,241,0.3)">
		<div><div class="gt-setting-label">Sensitivity Bonus Discount %</div><div class="gt-setting-desc">Additional percentage discount applied to cart subtotal when sensitivity threshold is reached. Max 50%.</div></div>
		<input type="number" name="gtbogo_sensitivity_bonus_pct" value="<?php echo esc_attr( get_option( 'gtbogo_sensitivity_bonus_pct', 10 ) ); ?>" min="1" max="50" style="width:80px;background:var(--gt-subtle-bg,#0f1a2e);border:1px solid var(--gt-border);border-radius:6px;padding:8px 10px;color:var(--gt-white);font-size:13px" id="gtbogo_gtbogo_sensitivity_bonus_pct" aria-label="Gtbogo Sensitivity Bonus Pct">
	</div>
	<?php endif; ?>

	<div class="gt-setting-row">
		<div><div class="gt-setting-label">Repeat Purchase Prediction (RFM)</div><div class="gt-setting-desc">Scores each customer's return likelihood using Recency, Frequency, Monetary value. High-score customers skip optional discounts to preserve margin.</div></div>
		<label class="gt-toggle"><input type="checkbox" name="gtbogo_rfm_enabled" value="1" <?php checked( get_option( 'gtbogo_rfm_enabled', 0 ) ); ?>><span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span></label>
	</div>

	<div class="gt-setting-row">
		<div><div class="gt-setting-label">Bundle Intelligence</div><div class="gt-setting-desc">Analyses order history weekly to discover product affinity pairs. Powers cart recommendations with real co-purchase data instead of manual configuration.</div></div>
		<label class="gt-toggle"><input type="checkbox" name="gtbogo_bundle_intel_enabled" value="1" <?php checked( get_option( 'gtbogo_bundle_intel_enabled', 0 ) ); ?>><span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span></label>
	</div>

	<div class="gt-setting-row">
		<div><div class="gt-setting-label">Cohort Intelligence</div><div class="gt-setting-desc">Groups customers by acquisition month, first product category, and LTV tier. Auto-prioritises the highest-converting rule for each cohort. Requires meaningful order volume to activate.</div></div>
		<label class="gt-toggle"><input type="checkbox" name="gtbogo_cohort_enabled" value="1" <?php checked( get_option( 'gtbogo_cohort_enabled', 0 ) ); ?>><span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span></label>
	</div>

	<div class="gt-setting-row" style="border:none">
		<div><div class="gt-setting-label">Outside Peak Window Behavior</div><div class="gt-setting-desc">When Timing Intelligence is active and customer is outside their peak purchase window. "Fire anyway" always applies the full discount.</div></div>
		<select name="gtbogo_timing_outside_behavior" style="background:var(--gt-subtle-bg,#0f1a2e);border:1px solid var(--gt-border);border-radius:6px;padding:8px 12px;color:var(--gt-white);font-size:13px">
			<option value="fire_anyway" <?php selected( get_option( 'gtbogo_timing_outside_behavior', 'fire_anyway' ), 'fire_anyway' ); ?>>Fire anyway — always apply full discount</option>
			<option value="reduce"      <?php selected( get_option( 'gtbogo_timing_outside_behavior', 'fire_anyway' ), 'reduce' ); ?>>Reduce — apply partial discount outside window</option>
			<option value="suppress"    <?php selected( get_option( 'gtbogo_timing_outside_behavior', 'fire_anyway' ), 'suppress' ); ?>>Suppress — skip discount outside window</option>
		</select>
	</div>
</div>

<!-- ── ADVANCED ──────────────────────────────────────────────────────────── -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px;border-color:rgba(245,158,11,0.2)">
	<div class="gt-card-header"><h2 class="gt-card-title">&#128295; Advanced</h2></div>
	<div class="gt-setting-row">
		<div><div class="gt-setting-label">Debug Mode</div><div class="gt-setting-desc">Write verbose debug output to the WordPress debug log (wp-content/debug.log). Only enable temporarily when diagnosing an issue. Never leave enabled in production.</div></div>
		<label class="gt-toggle"><input type="checkbox" name="debug_mode" value="1" <?php checked( $s['debug_mode'] ); ?>><span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span></label>
	</div>
	<div class="gt-setting-row" style="border:none">
		<div>
			<div class="gt-setting-label" style="color:#fca5a5">Delete All Data on Uninstall</div>
			<div class="gt-setting-desc">When enabled, uninstalling the plugin will permanently delete all rules, analytics data, audit logs, and plugin settings from the database. This cannot be undone. Leave disabled unless you intend a complete clean removal.</div>
		</div>
		<label class="gt-toggle"><input type="checkbox" name="uninstall_data" value="1" <?php checked( $s['uninstall_data'] ); ?>><span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span></label>
	</div>
</div>

<!-- ── SAVE ──────────────────────────────────────────────────────────────── -->
<div style="text-align:right;margin-bottom:40px">
	<!-- ── Storefront Appearance ─────────────────────────────────────── -->
	<div class="gt-card" style="margin-bottom:24px">
		<div class="gt-card-header"><h2 class="gt-card-title">&#127912; Storefront Appearance</h2></div>
		<p style="margin:0 0 20px;font-size:13px;color:var(--gt-subtle)">Control how GT BOGO Engine elements look on your storefront. These CSS variables apply to all superpowers — progress bars, nudges, badges, and cart notices. Works on every WordPress theme.</p>
		<div class="gt-settings-grid">
			<div class="gt-setting-row">
				<div><div class="gt-setting-label">Accent Color</div><div class="gt-setting-desc">Primary highlight color used on buttons, badges, and deal indicators.</div></div>
				<div style="display:flex;align-items:center;gap:10px">
					<input type="color" name="gtbogo_css_accent" value="<?php echo esc_attr( get_option( 'gtbogo_css_accent', '#acfe01' ) ); ?>" style="width:48px;height:36px;border:1px solid var(--gt-border);border-radius:6px;background:transparent;cursor:pointer" id="gtbogo_gtbogo_css_accent" aria-label="Gtbogo Css Accent">
					<input type="text" name="gtbogo_css_accent_text" value="<?php echo esc_attr( get_option( 'gtbogo_css_accent', '#acfe01' ) ); ?>" style="width:100px;background:var(--gt-subtle-bg,#0f1a2e);border:1px solid var(--gt-border);border-radius:6px;padding:8px 10px;color:var(--gt-white);font-size:13px" oninput="document.querySelector('[name=gtbogo_css_accent]').value=this.value" id="gtbogo_gtbogo_css_accent_text" aria-label="Gtbogo Css Accent Text">
				</div>
			</div>
			<div class="gt-setting-row">
				<div><div class="gt-setting-label">Danger / Urgency Color</div><div class="gt-setting-desc">Used for urgency indicators, scarcity bars, and countdown timers.</div></div>
				<div style="display:flex;align-items:center;gap:10px">
					<input type="color" name="gtbogo_css_danger" id="gtbogo_css_danger" aria-label="Danger color" value="<?php echo esc_attr( get_option( 'gtbogo_css_danger', '#ff4444' ) ); ?>" style="width:48px;height:36px;border:1px solid var(--gt-border);border-radius:6px;background:transparent;cursor:pointer">
					<input type="text" id="gtbogo_css_danger_hex" aria-label="Danger color hex value" value="<?php echo esc_attr( get_option( 'gtbogo_css_danger', '#ff4444' ) ); ?>" style="width:100px;background:var(--gt-subtle-bg,#0f1a2e);border:1px solid var(--gt-border);border-radius:6px;padding:8px 10px;color:var(--gt-white);font-size:13px" oninput="document.querySelector('[name=gtbogo_css_danger]').value=this.value">
				</div>
			</div>
			<div class="gt-setting-row">
				<div><div class="gt-setting-label">Widget Background</div><div class="gt-setting-desc">Background color for superpower cards and notice boxes on your storefront.</div></div>
				<div style="display:flex;align-items:center;gap:10px">
					<input type="color" name="gtbogo_css_bg" id="gtbogo_css_bg" aria-label="Background color" value="<?php echo esc_attr( get_option( 'gtbogo_css_bg', '#0f172a' ) ); ?>" style="width:48px;height:36px;border:1px solid var(--gt-border);border-radius:6px;background:transparent;cursor:pointer">
					<input type="text" id="gtbogo_css_bg_hex" aria-label="Background color hex value" value="<?php echo esc_attr( get_option( 'gtbogo_css_bg', '#0f172a' ) ); ?>" style="width:100px;background:var(--gt-subtle-bg,#0f1a2e);border:1px solid var(--gt-border);border-radius:6px;padding:8px 10px;color:var(--gt-white);font-size:13px" oninput="document.querySelector('[name=gtbogo_css_bg]').value=this.value">
				</div>
			</div>
			<div class="gt-setting-row">
				<div><div class="gt-setting-label">Text Color</div><div class="gt-setting-desc">Primary text color inside superpower widgets.</div></div>
				<div style="display:flex;align-items:center;gap:10px">
					<input type="color" name="gtbogo_css_text" id="gtbogo_css_text" aria-label="Text color" value="<?php echo esc_attr( get_option( 'gtbogo_css_text', '#ffffff' ) ); ?>" style="width:48px;height:36px;border:1px solid var(--gt-border);border-radius:6px;background:transparent;cursor:pointer">
					<input type="text" id="gtbogo_css_text_hex" aria-label="Text color hex value" value="<?php echo esc_attr( get_option( 'gtbogo_css_text', '#ffffff' ) ); ?>" style="width:100px;background:var(--gt-subtle-bg,#0f1a2e);border:1px solid var(--gt-border);border-radius:6px;padding:8px 10px;color:var(--gt-white);font-size:13px" oninput="document.querySelector('[name=gtbogo_css_text]').value=this.value">
				</div>
			</div>
			<div class="gt-setting-row">
				<div><div class="gt-setting-label">Border Radius</div><div class="gt-setting-desc">Corner rounding for all superpower widgets. Use 0px for sharp corners, 50px for fully rounded pills.</div></div>
				<input type="text" name="gtbogo_css_radius" value="<?php echo esc_attr( get_option( 'gtbogo_css_radius', '10px' ) ); ?>" style="width:120px;background:var(--gt-subtle-bg,#0f1a2e);border:1px solid var(--gt-border);border-radius:6px;padding:8px 10px;color:var(--gt-white);font-size:13px" placeholder="10px" id="gtbogo_gtbogo_css_radius" aria-label="Gtbogo Css Radius">
			</div>
		</div>
		<div style="margin-top:16px;padding:14px 18px;background:rgba(172,254,1,0.05);border:1px solid rgba(172,254.3.0.15);border-radius:8px;font-size:12px;color:var(--gt-subtle)">
			&#9432; These settings apply to all superpower widgets on your storefront. Your theme's fonts and layout are never touched — only the plugin's own elements use these colors.
		</div>
	</div>
	<button type="submit" name="gtbogo_save_settings" class="gt-btn gt-btn-primary" style="padding:14px 40px">&#128190; Save Settings</button>
</div>

</form>

<script>
function gtUpdateThemeSwatch(activeKey) {
	document.querySelectorAll('.gt-email-swatch').forEach(function(s) {
		s.style.borderColor = s.dataset.theme === activeKey ? 'var(--gt-red)' : 'var(--gt-border)';
	});
}
</script>

<!-- ── RECOMMENDATIONS ──────────────────────────────────────────────────── -->
<div class="gt-card gt-animate-in" style="background:linear-gradient(135deg,rgba(59,130,246,0.06),rgba(7,12,28,0));border-color:rgba(59,130,246,0.15)">
	<div class="gt-card-header"><h2 class="gt-card-title">&#129504; Settings Recommendations</h2></div>
	<div class="gt-feature-grid gt-feature-grid--2col">
		<div><div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Recommended Production Setup</div><div style="font-size:13px;color:var(--gt-soft);line-height:1.7">Auto-add ON &#183; Auto-remove ON &#183; Cache rules ON (300s TTL) &#183; Analytics ON (90-day retention) &#183; Audit log ON (Info level, 1000 entries) &#183; Debug mode OFF &#183; Delete on uninstall OFF. This is the safest and most performant configuration for a live store.</div></div>
		<div><div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Conflict Strategy Selection</div><div style="font-size:13px;color:var(--gt-soft);line-height:1.7">"Highest priority" is the safest default — you control outcomes via priority numbers. "Best for customer" maximises order conversion but reduces margin control. "All eligible stack" is powerful for promotions but requires a maximum discount cap to prevent runaway discounting.</div></div>
		<div><div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Always Exclude Admin from Analytics</div><div style="font-size:13px;color:var(--gt-soft);line-height:1.7">Test orders placed by administrators contaminate your analytics data. Add the administrator role to the analytics exclusion list from day one. This keeps your AOV, order count, and revenue figures clean and representative of actual customer behaviour.</div></div>
		<div><div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Maximum Discount Cap for Stacking</div><div style="font-size:13px;color:var(--gt-soft);line-height:1.7">If using "All eligible stack" conflict strategy, set a maximum discount cap of 50&#8211;60% to protect margin. Without a cap a customer with multiple qualifying rules could receive a discount that exceeds your actual margin, resulting in a net loss.</div></div>
	</div>
</div>

<script>
(function() {
	// Universal interconnected toggle — any checkbox with data-option auto-saves instantly
	// Same wp_options key read by Dashboard, Analytics, Emails — all stay in sync
	var _sysNonce = '<?php echo esc_js( $_gtbogo_sys_nonce ); ?>';
	document.querySelectorAll('input[type="checkbox"][data-option]').forEach(function(cb) {
		cb.addEventListener('change', function() {
			var fd = new FormData();
			fd.append('action',     'gtbogo_autosave_toggle');
			fd.append('nonce',      _sysNonce);
			fd.append('option_key', this.dataset.option);
			fd.append('value',      this.checked ? '1' : '0');
			fetch('<?php echo esc_js( admin_url( 'admin-ajax.php' ) ); ?>', {
				method: 'POST', body: fd, credentials: 'same-origin'
			}).then(function(r){ return r.json(); }).then(function(res){
				if (!res.success) console.warn('GT BOGO toggle save failed', res);
			});
		});
	});
})();
</script>
<?php require_once __DIR__ . '/../ui-system/wrapper-end.php'; ?>
