<?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

/**
 * GT BOGO Engine — Geographic Targeting (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 = '';

// Country list
$countries  = WC()->countries ? WC()->countries->get_countries() : array();
$states_raw = WC()->countries ? WC()->countries->get_states() : array();

// ── Save Global Geo Settings ──────────────────────────────────────────────
if ( $is_pro && isset( $_POST['gtbogo_save_geo'] ) && check_admin_referer( 'gtbogo_geo', 'gtbogo_geo_nonce' ) ) {
	update_option( 'gtbogo_geo_enabled', isset( $_POST['geo_enabled'] ) );
	update_option( 'gtbogo_geo_detect', sanitize_text_field( $_POST['geo_detect'] ?? 'billing' ) );
	update_option( 'gtbogo_geo_fallback', sanitize_text_field( $_POST['geo_fallback'] ?? 'allow' ) );
	delete_transient( 'gtbogo_active_rules' );
	delete_transient( 'gtbogo_active_rules_summary' );
	$message      = 'Geographic targeting settings saved.';
	$message_type = 'success';
}

// ── Save a Geo Zone ───────────────────────────────────────────────────────
if ( $is_pro && isset( $_POST['gtbogo_save_zone'] ) && check_admin_referer( 'gtbogo_save_zone' ) ) {
	$zones             = get_option( 'gtbogo_geo_zones', array() );
	$zone_id           = sanitize_text_field( $_POST['zone_id'] ?? uniqid( 'z_' ) );
	$zones[ $zone_id ] = array(
		'name'      => sanitize_text_field( $_POST['zone_name'] ?? 'New Zone' ),
		'mode'      => sanitize_text_field( $_POST['zone_mode'] ?? 'include' ),
		'countries' => array_map( 'sanitize_text_field', (array) ( $_POST['zone_countries'] ?? array() ) ),
		'states'    => array_map( 'sanitize_text_field', (array) ( $_POST['zone_states'] ?? array() ) ),
		'postcodes' => array_map( 'sanitize_text_field', array_filter( preg_split( '/[\n,]+/', $_POST['zone_postcodes'] ?? '' ) ) ),
		'rule_ids'  => array_map( 'intval', (array) ( $_POST['zone_rule_ids'] ?? array() ) ),
		'enabled'   => isset( $_POST['zone_enabled'] ),
		'created'   => $zones[ $zone_id ]['created'] ?? current_time( 'mysql', true ),
	);
	update_option( 'gtbogo_geo_zones', $zones );
	if ( function_exists( 'gt_bogo_log' ) ) {
		gt_bogo_log( 'Geo zone saved', $zones[ $zone_id ]['name'], 'success' );
	}
	delete_transient( 'gtbogo_active_rules' );
	delete_transient( 'gtbogo_active_rules_summary' );
	$message      = 'Geo zone saved.';
	$message_type = 'success';
}

// ── Delete Geo Zone ───────────────────────────────────────────────────────
if ( $is_pro && isset( $_GET['delete_zone'] ) && check_admin_referer( 'delete_zone_' . sanitize_text_field( $_GET['delete_zone'] ) ) ) {
	$zones = get_option( 'gtbogo_geo_zones', array() );
	$zid   = sanitize_text_field( $_GET['delete_zone'] );
	if ( isset( $zones[ $zid ] ) ) {
		if ( function_exists( 'gt_bogo_log' ) ) {
			gt_bogo_log( 'Geo zone deleted', $zones[ $zid ]['name'], 'warn' );
		}
		unset( $zones[ $zid ] );
		update_option( 'gtbogo_geo_zones', $zones );
	}
	$message      = 'Zone deleted.';
	$message_type = 'success';
}

// ── Toggle Zone ───────────────────────────────────────────────────────────
if ( $is_pro && isset( $_GET['toggle_zone'] ) && check_admin_referer( 'toggle_zone_' . sanitize_text_field( $_GET['toggle_zone'] ) ) ) {
	$zones = get_option( 'gtbogo_geo_zones', array() );
	$zid   = sanitize_text_field( $_GET['toggle_zone'] );
	if ( isset( $zones[ $zid ] ) ) {
		$zones[ $zid ]['enabled'] = ! ( $zones[ $zid ]['enabled'] ?? true );
		update_option( 'gtbogo_geo_zones', $zones );
		$message      = 'Zone ' . ( $zones[ $zid ]['enabled'] ? 'enabled' : 'disabled' ) . '.';
		$message_type = 'success';
	}
}

$geo_enabled  = get_option( 'gtbogo_geo_enabled', false );
$geo_detect   = get_option( 'gtbogo_geo_detect', 'billing' );
$geo_fallback = get_option( 'gtbogo_geo_fallback', 'allow' );
$geo_zones    = get_option( 'gtbogo_geo_zones', array() );
$active_zones = count( array_filter( $geo_zones, fn( $z ) => ! empty( $z['enabled'] ) ) );

// Load PRO rules
global $wpdb;
$rtbl  = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->prefix . 'gtbogo_rules' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.NotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter,WordPress.DB.PreparedSQLPlaceholders.UnnecessaryPrepare
$rules = $rtbl ? $wpdb->get_results( "SELECT id, name, status FROM {$wpdb->prefix}gtbogo_rules ORDER BY name ASC" ) : array(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.NotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter,WordPress.DB.PreparedSQLPlaceholders.UnnecessaryPrepare

// Edit mode
$edit_zone_id = isset( $_GET['edit_zone'] ) ? sanitize_text_field( $_GET['edit_zone'] ) : '';
$edit_zone    = ( $edit_zone_id && isset( $geo_zones[ $edit_zone_id ] ) ) ? $geo_zones[ $edit_zone_id ] : null;

// WooCommerce sell-to countries
$wc_countries_enabled = WC()->countries ? array_keys( WC()->countries->get_allowed_countries() ) : array();

require_once __DIR__ . '/../ui-system/wrapper-start.php';
?>
<div class="gt-page-header gt-animate-in">
	<div>
		<h1 class="gt-page-title">🌍 Geographic Targeting</h1>
		<p class="gt-page-subtitle">Run BOGO rules for specific countries, states, or postcodes — or exclude certain regions entirely</p>
	</div>
	<div style="display:flex;gap:8px;align-items:center">
		<span class="gt-badge <?php echo esc_html( $geo_enabled ) ? 'gt-badge-active' : 'gt-badge-free'; ?>"><?php echo esc_html( $geo_enabled ) ? '● Geo Targeting Active' : '○ Geo Targeting Off'; ?></span>
	</div>
</div>
<?php
if ( $message ) :
	?>
	<div class="gt-notice gt-notice-<?php echo esc_attr( $message_type ); ?> gt-animate-in">✓ <?php echo esc_html( $message ); ?></div><?php endif; ?>

<?php if ( ! $is_pro ) : ?>
<div class="gt-pro-gate gt-animate-in">
	<span class="gt-pro-gate-icon">🌍</span>
	<h2>PRO License Required</h2>
	<p>Geographic Targeting lets you run BOGO promotions for specific countries, states, or postcodes — perfect for region-specific campaigns, EU compliance, or market-entry promotions.</p>
	<div style="display:grid;grid-template-columns:repeat(2,1fr);gap:12px;max-width:480px;margin:24px auto 0">
		<?php foreach ( array( 'Country, state, and postcode targeting', 'Include or exclude geo zones', 'Per-rule geo assignment', 'WooCommerce billing or shipping address detection' ) as $f ) : ?>
		<div style="display:flex;align-items:flex-start;gap:8px;text-align:left"><span style="color:#e10000;font-weight:700">—</span><span style="font-size:13px;color:var(--gt-soft)"><?php echo esc_html( $f ); ?></span></div>
		<?php endforeach; ?>
	</div>
	<div style="margin-top:24px;display:flex;justify-content:center;gap:12px">
		<a href="https://graphictshirts.shop/bogo/" target="_blank" rel="noopener" class="gt-btn gt-btn-primary">Purchase PRO — $499/yr</a>
	</div>
</div>
<?php else : ?>

<!-- METRICS -->
<div class="gt-metrics gt-animate-in" style="margin-bottom:20px">
	<div class="gt-metric" style="--gt-metric-c:#e10000">
		<span class="gt-metric-icon">🌍</span>
		<div class="gt-metric-label">Geo Zones</div>
		<div class="gt-metric-value"><?php echo esc_html( count( $geo_zones ) ); ?></div>
		<div class="gt-metric-trend"><?php echo esc_html( $active_zones ); ?> active</div>
	</div>
	<div class="gt-metric" style="--gt-metric-c:#22c55e">
		<span class="gt-metric-icon">🗺️</span>
		<div class="gt-metric-label">Countries Targeted</div>
		<div class="gt-metric-value"><?php echo count( array_unique( array_merge( ...array_map( fn( $z )=>$z['countries'] ?? array(), $geo_zones ) ) ) ); ?></div>
		<div class="gt-metric-trend">Across all zones</div>
	</div>
	<div class="gt-metric" style="--gt-metric-c:#3b82f6">
		<span class="gt-metric-icon">📍</span>
		<div class="gt-metric-label">Detection Method</div>
		<div class="gt-metric-value" style="font-size:16px"><?php echo esc_html( ucfirst( $geo_detect ) ); ?></div>
		<div class="gt-metric-trend">Address used for matching</div>
	</div>
	<div class="gt-metric" style="--gt-metric-c:#8b5cf6">
		<span class="gt-metric-icon">⚠️</span>
		<div class="gt-metric-label">Fallback</div>
		<div class="gt-metric-value" style="font-size:16px"><?php echo esc_html( ucfirst( $geo_fallback ) ); ?></div>
		<div class="gt-metric-trend">When location unknown</div>
	</div>
</div>

<!-- GLOBAL SETTINGS -->
<form method="post" action="">
	<?php wp_nonce_field( 'gtbogo_geo', 'gtbogo_geo_nonce' ); ?>
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header"><h2 class="gt-card-title">⚙️ Global Geo Settings</h2></div>
	<div class="gt-setting-row">
		<div><div class="gt-setting-label" style="font-size:16px">Enable Geographic Targeting</div><div class="gt-setting-desc">When enabled, BOGO rules are filtered by the customer's location before being applied. Disable to let all rules fire regardless of location.</div></div>
		<label class="gt-toggle"><input type="checkbox" name="geo_enabled" value="1" <?php checked( $geo_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">Location Detection Method</div><div class="gt-setting-desc">Which address WooCommerce uses to determine customer location. Billing is available earlier in checkout; Shipping may differ for gift orders.</div></div>
		<select name="geo_detect" class="gt-select" style="width:220px">
			<option value="billing"  <?php selected( $geo_detect, 'billing' ); ?>>Billing Address</option>
			<option value="shipping" <?php selected( $geo_detect, 'shipping' ); ?>>Shipping Address</option>
			<option value="either"   <?php selected( $geo_detect, 'either' ); ?>>Either (billing, fallback to shipping)</option>
		</select>
	</div>
	<div class="gt-setting-row" style="border:none">
		<div><div class="gt-setting-label">Fallback Behaviour (Unknown Location)</div><div class="gt-setting-desc">What happens when the customer's location cannot be determined (e.g. guest checkout before address entry).</div></div>
		<select name="geo_fallback" class="gt-select" style="width:220px">
			<option value="allow"  <?php selected( $geo_fallback, 'allow' ); ?>>Allow All Rules</option>
			<option value="deny"   <?php selected( $geo_fallback, 'deny' ); ?>>Deny All Rules</option>
			<option value="zones"  <?php selected( $geo_fallback, 'zones' ); ?>>Apply Global Zones Only</option>
		</select>
	</div>
	<div style="margin-top:16px;text-align:right">
		<button type="submit" name="gtbogo_save_geo" class="gt-btn gt-btn-primary" style="padding:10px 28px">💾 Save Global Settings</button>
	</div>
</div>
</form>

<!-- ZONE LIST -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header">
		<h2 class="gt-card-title">🗺️ Geo Zones</h2>
		<a href="?page=gt-bogo-engine&tab=geo-targeting&new_zone=1" class="gt-btn gt-btn-primary gt-btn-sm">+ Add Zone</a>
	</div>
	<?php if ( ! empty( $geo_zones ) ) : ?>
	<div style="display:flex;flex-direction:column;gap:10px">
		<?php foreach ( $geo_zones as $zid => $zone ) : ?>
		<div style="padding:16px 20px;border-radius:10px;border:1px solid <?php echo ! empty( $zone['enabled'] ) ? 'rgba(225,0,0,0.2)' : 'var(--gt-border)'; ?>;background:<?php echo ! empty( $zone['enabled'] ) ? 'rgba(225,0,0,0.03)' : 'rgba(255,255,255,0.01)'; ?>;display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px">
			<div>
				<div style="display:flex;align-items:center;gap:10px;margin-bottom:4px">
					<span style="font-size:14px;font-weight:700;color:var(--gt-white)"><?php echo esc_html( $zone['name'] ); ?></span>
					<span style="font-size:13px;font-weight:700;color:<?php echo $zone['mode'] === 'include' ? '#86efac' : '#fca5a5'; ?>;background:<?php echo $zone['mode'] === 'include' ? 'rgba(34,197,94,0.08)' : 'rgba(225,0,0,0.08)'; ?>;padding:2px 8px;border-radius:50px"><?php echo esc_html( strtoupper( $zone['mode'] ) ); ?></span>
					<span class="gt-badge <?php echo ! empty( $zone['enabled'] ) ? 'gt-badge-active' : 'gt-badge-free'; ?>" style="font-size:13px"><?php echo ! empty( $zone['enabled'] ) ? 'Active' : 'Inactive'; ?></span>
				</div>
				<div style="font-size:13px;color:var(--gt-soft)">
					<?php
					$parts = array();
					if ( ! empty( $zone['countries'] ) ) {
						$cnames  = array_slice( array_map( fn( $c ) => $countries[ $c ] ?? $c, $zone['countries'] ), 0, 3 );
						$parts[] = implode( ', ', $cnames ) . ( count( $zone['countries'] ) > 3 ? ' +' . ( count( $zone['countries'] ) - 3 ) . ' more' : '' );
					}
					if ( ! empty( $zone['states'] ) ) {
						$parts[] = count( $zone['states'] ) . ' state(s)';
					}
					if ( ! empty( $zone['postcodes'] ) ) {
						$parts[] = count( $zone['postcodes'] ) . ' postcode(s)';
					}
					if ( ! empty( $zone['rule_ids'] ) ) {
						$parts[] = count( $zone['rule_ids'] ) . ' rule(s) assigned';
					}
					echo esc_html( implode( ' · ', $parts ) ?: 'No targeting criteria set' );
					?>
				</div>
			</div>
			<div style="display:flex;gap:8px;flex-wrap:wrap">
				<a href="?page=gt-bogo-engine&tab=geo-targeting&edit_zone=<?php echo esc_attr( $zid ); ?>" class="gt-btn gt-btn-ghost gt-btn-sm">✎ Edit</a>
				<a href="
				<?php
				echo esc_url(
					wp_nonce_url(
						add_query_arg(
							array(
								'toggle_zone' => $zid,
								'page'        => 'gt-bogo-engine',
								'tab'         => 'geo-targeting',
							),
							admin_url( 'admin.php' )
						),
						'toggle_zone_' . $zid
					)
				);
				?>
							" class="gt-btn gt-btn-ghost gt-btn-sm"><?php echo ! empty( $zone['enabled'] ) ? '⏸ Disable' : '▶ Enable'; ?></a>
				<a href="
				<?php
				echo esc_url(
					wp_nonce_url(
						add_query_arg(
							array(
								'delete_zone' => $zid,
								'page'        => 'gt-bogo-engine',
								'tab'         => 'geo-targeting',
							),
							admin_url( 'admin.php' )
						),
						'delete_zone_' . $zid
					)
				);
				?>
							" class="gt-btn gt-btn-ghost gt-btn-sm" style="color:#fca5a5" onclick="return confirm('Delete this geo zone?')">✕</a>
			</div>
		</div>
		<?php endforeach; ?>
	</div>
	<?php else : ?>
	<div style="text-align:center;padding:40px 24px">
		<div style="font-size:48px;margin-bottom:16px">🌍</div>
		<h3 style="color:var(--gt-white);margin:0 0 8px">No Geo Zones Yet</h3>
		<p class="gt-text-soft" style="font-size:13px">Create your first zone to start targeting rules by country, state, or postcode.</p>
		<a href="?page=gt-bogo-engine&tab=geo-targeting&new_zone=1" class="gt-btn gt-btn-primary gt-btn-sm" style="margin-top:16px">+ Create First Zone</a>
	</div>
	<?php endif; ?>
</div>

<!-- ZONE FORM (new or edit) -->
	<?php if ( isset( $_GET['new_zone'] ) || $edit_zone ) : ?>
<div class="gt-card gt-animate-in" style="margin-bottom:20px;border-color:rgba(225,0,0,0.2)">
	<div class="gt-card-header">
		<h2 class="gt-card-title"><?php echo esc_html( $edit_zone ) ? '✎ Edit Zone: ' . esc_html( $edit_zone['name'] ) : '➕ New Geo Zone'; ?></h2>
		<a href="?page=gt-bogo-engine&tab=geo-targeting" class="gt-btn gt-btn-ghost gt-btn-sm">✕ Cancel</a>
	</div>
	<form method="post" action="">
			<?php wp_nonce_field( 'gtbogo_save_zone' ); ?>
			<?php
			if ( $edit_zone ) :
				?>
				<input type="hidden" name="zone_id" value="<?php echo esc_attr( $edit_zone_id ); ?>"><?php endif; ?>

		<div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;margin-bottom:20px">
			<div class="gt-form-group">
				<label class="gt-form-label">Zone Name</label>
				<input type="text" name="zone_name" class="gt-input" value="<?php echo esc_attr( $edit_zone['name'] ?? '' ); ?>" placeholder="e.g. Europe, US East Coast" required id="gtbogo_zone_name" aria-label="Zone Name">
			</div>
			<div class="gt-form-group">
				<label class="gt-form-label">Mode</label>
				<select name="zone_mode" class="gt-select">
					<option value="include" <?php selected( $edit_zone['mode'] ?? 'include', 'include' ); ?>>Include — rules fire only in this zone</option>
					<option value="exclude" <?php selected( $edit_zone['mode'] ?? '', 'exclude' ); ?>>Exclude — rules are blocked in this zone</option>
				</select>
			</div>
		</div>

		<!-- Countries -->
		<div class="gt-form-group">
			<label class="gt-form-label">Countries</label>
			<div style="margin-bottom:8px;display:flex;gap:8px">
				<button type="button" class="gt-btn gt-btn-ghost gt-btn-sm" onclick="document.querySelectorAll('.geo-country-cb').forEach(c=>c.checked=true)">Select All</button>
				<button type="button" class="gt-btn gt-btn-ghost gt-btn-sm" onclick="document.querySelectorAll('.geo-country-cb').forEach(c=>c.checked=false)">Clear All</button>
				<input type="text" id="country-search" class="gt-input gt-btn-sm" placeholder="Filter countries..." style="max-width:200px"
						oninput="document.querySelectorAll('.geo-c-label').forEach(l=>l.style.display=l.dataset.name.includes(this.value.toLowerCase())?'':'none')">
			</div>
			<div style="max-height:200px;overflow-y:auto;border:1px solid var(--gt-border);border-radius:8px;padding:10px;display:flex;flex-wrap:wrap;gap:6px">
					<?php
					foreach ( $countries as $code => $name ) :
						$sel = in_array( $code, (array) ( $edit_zone['countries'] ?? array() ) );
						?>
				<label class="geo-c-label" data-name="<?php echo esc_attr( strtolower( $code . ' ' . $name ) ); ?>" style="cursor:pointer">
					<input type="checkbox" class="geo-country-cb" name="zone_countries[]" value="<?php echo esc_attr( $code ); ?>" <?php checked( $sel ); ?> style="display:none">
					<span onclick="var cb=this.previousElementSibling;cb.checked=!cb.checked;this.style.background=cb.checked?'rgba(225,0,0,0.1)':'rgba(255,255,255,0.03)';this.style.borderColor=cb.checked?'rgba(225,0,0,0.4)':'rgba(255,255,255,0.07)';this.style.color=cb.checked?'var(--gt-white)':'var(--gt-soft)'"
							style="display:inline-block;padding:3px 10px;border-radius:50px;font-size:13px;font-weight:600;border:1px solid <?php echo esc_html( $sel ) ? 'rgba(225,0,0,0.4)' : 'rgba(255,255,255,0.07)'; ?>;background:<?php echo esc_html( $sel ) ? 'rgba(225,0,0,0.1)' : 'rgba(255,255,255,0.03)'; ?>;color:<?php echo esc_html( $sel ) ? 'var(--gt-white)' : 'var(--gt-soft)'; ?>">
						<?php echo esc_html( $code ); ?>
					</span>
				</label>
					<?php endforeach; ?>
			</div>
			<div class="gt-form-hint">Select countries to include in or exclude from this zone</div>
		</div>

		<!-- States / Regions -->
		<div class="gt-form-group">
			<label class="gt-form-label">States / Regions (optional)</label>
			<div style="max-height:150px;overflow-y:auto;border:1px solid var(--gt-border);border-radius:8px;padding:10px;display:flex;flex-wrap:wrap;gap:6px">
				<?php
				$zone_states = (array) ( $edit_zone['states'] ?? array() );
				foreach ( $states_raw as $c_code => $c_states ) :
					if ( ! in_array( $c_code, $wc_countries_enabled ) ) {
						continue;
					}
					foreach ( $c_states as $s_code => $s_name ) :
						$s_key = $c_code . ':' . $s_code;
						$sel   = in_array( $s_key, $zone_states );
						?>
				<label style="cursor:pointer">
					<input type="checkbox" name="zone_states[]" value="<?php echo esc_attr( $s_key ); ?>" <?php checked( $sel ); ?> style="display:none">
					<span onclick="var cb=this.previousElementSibling;cb.checked=!cb.checked;this.style.background=cb.checked?'rgba(225,0,0,0.08)':'rgba(255,255,255,0.02)';this.style.borderColor=cb.checked?'rgba(225,0,0,0.3)':'rgba(255,255,255,0.06)';this.style.color=cb.checked?'var(--gt-white)':'var(--gt-soft)'"
							style="display:inline-block;padding:3px 8px;border-radius:50px;font-size:13px;font-weight:600;border:1px solid <?php echo esc_html( $sel ) ? 'rgba(225,0,0,0.3)' : 'rgba(255,255,255,0.06)'; ?>;background:<?php echo esc_html( $sel ) ? 'rgba(225,0,0,0.08)' : 'rgba(255,255,255,0.02)'; ?>;color:<?php echo esc_html( $sel ) ? 'var(--gt-white)' : 'var(--gt-soft)'; ?>">
						<?php echo esc_html( $c_code . ': ' . $s_name ); ?>
					</span>
				</label>
						<?php
				endforeach;
endforeach;
				?>
			</div>
		</div>

		<!-- Postcodes -->
		<div class="gt-form-group">
			<label class="gt-form-label">Postcodes / ZIP Codes (optional)</label>
			<textarea name="zone_postcodes" class="gt-input" rows="3" style="font-family:'DM Mono',monospace;font-size:13px" placeholder="SW1A 1AA&#10;10001&#10;E1, E2, E3"><?php echo esc_textarea( implode( "\n", (array) ( $edit_zone['postcodes'] ?? array() ) ) ); ?></textarea>
			<div class="gt-form-hint">One per line, or comma-separated. Prefix or exact match — e.g. "SW1" matches all SW1 postcodes.</div>
		</div>

		<!-- Assign Rules -->
			<?php if ( ! empty( $rules ) ) : ?>
		<div class="gt-form-group">
			<label class="gt-form-label">Assign Rules to This Zone (optional)</label>
			<div style="max-height:160px;overflow-y:auto;border:1px solid var(--gt-border);border-radius:8px;padding:10px;display:flex;flex-direction:column;gap:6px">
				<?php
				foreach ( $rules as $rule ) :
					$sel = in_array( $rule->id, array_map( 'intval', (array) ( $edit_zone['rule_ids'] ?? array() ) ) );
					?>
				<label style="display:flex;align-items:center;gap:8px;cursor:pointer;padding:4px">
					<input type="checkbox" name="zone_rule_ids[]" value="<?php echo esc_html( $rule->id ); ?>" <?php checked( $sel ); ?> style="accent-color:var(--gt-red)">
					<span style="font-size:13px;color:var(--gt-white)"><?php echo esc_html( $rule->name ); ?></span>
					<span style="font-size:13px;color:<?php echo $rule->status === 'active' ? '#86efac' : '#94a3b8'; ?>"><?php echo esc_html( $rule->status ); ?></span>
				</label>
				<?php endforeach; ?>
			</div>
			<div class="gt-form-hint">If no rules are assigned, this zone applies to all active rules</div>
		</div>
		<?php endif; ?>

		<div class="gt-setting-row" style="border:none;padding:0;margin-bottom:20px">
			<div><div class="gt-setting-label">Zone Active</div><div class="gt-setting-desc">Inactive zones are saved but not evaluated at checkout</div></div>
			<label class="gt-toggle"><input type="checkbox" name="zone_enabled" value="1" <?php checked( ! empty( $edit_zone['enabled'] ?? true ) ); ?>><span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span></label>
		</div>

		<div style="display:flex;gap:12px;justify-content:flex-end">
			<a href="?page=gt-bogo-engine&tab=geo-targeting" class="gt-btn gt-btn-ghost">Cancel</a>
			<button type="submit" name="gtbogo_save_zone" class="gt-btn gt-btn-primary" style="padding:12px 32px">💾 Save Zone</button>
		</div>
	</form>
</div>
	<?php endif; ?>

<!-- GUIDANCE -->
<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">🧠 Geo Targeting Strategy Guide</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">Market Entry Promotions</div><div style="font-size:13px;color:var(--gt-soft);line-height:1.7">Create an Include zone for a new market — for example, all Canadian provinces — and assign your most aggressive BOGO rule. This gives you a geographically isolated launch promotion without affecting existing UK and US customers who are at full price.</div></div>
		<div><div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">EU VAT Compliance</div><div style="font-size:13px;color:var(--gt-soft);line-height:1.7">Create an Exclude zone covering all EU member states for any BOGO rule that would create compliance complications under EU consumer protection law. This is a belt-and-braces approach while your legal review is ongoing — you can flip the zone back to Include once cleared.</div></div>
		<div><div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Postcode-Level Flash Sales</div><div style="font-size:13px;color:var(--gt-soft);line-height:1.7">Use postcode targeting for hyper-local campaigns — for example, a BOGO deal valid only for customers in the E1 postal district near a pop-up event. Combine with a short campaign window in the Scheduler for maximum exclusivity and urgency.</div></div>
		<div><div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Fallback Setting for Guest Checkout</div><div style="font-size:13px;color:var(--gt-soft);line-height:1.7">Set Fallback to "Allow All Rules" for stores with high guest checkout rates — location is unknown until the billing step, and blocking BOGO for guests before they provide an address will suppress conversion. Tighten fallback to "Deny" only for high-restriction regulated markets.</div></div>
	</div>
</div>

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