<?php

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

$s = isset( $settings ) && is_array( $settings )
	? $settings
	: ( isset( $module ) ? $module->get_settings() : array() );
$sitekit_active = isset( $sitekit_active ) ? (bool) $sitekit_active : false;

$nonce = wp_create_nonce( AIEO_DMM::NONCE_ACTION );
$ajax  = admin_url( 'admin-ajax.php' );

$has_fb_token  = ! empty( $s['fb_access_token'] );
$has_tt_token  = ! empty( $s['tiktok_access_token'] );
$has_ga_secret = ! empty( $s['ga_api_secret'] );
$recent_events = isset( $recent_events ) && is_array( $recent_events ) ? $recent_events : array();
?>
<div class="aieo-dmm-section">
	<h2><?php esc_html_e( 'Pixels & Conversions', 'ai-eshop-optimizer' ); ?></h2>
	<p class="description" style="max-width:820px;">
		<?php esc_html_e( 'Choose how AIEO forwards your conversion signals to the ad platforms. Each platform is independent — let AIEO own it, or defer to a tool you already run (for example keep Google Site Kit for GA4) and AIEO will stay out of the way to avoid double-counting.', 'ai-eshop-optimizer' ); ?>
	</p>

	<form id="aieo-dmm-conversions-form" class="aieo-dmm-form">

		<!-- Facebook / Meta -->
		<div class="aieo-dmm-card">
			<h3><?php esc_html_e( 'Facebook / Meta — Pixel & Conversions API', 'ai-eshop-optimizer' ); ?></h3>
			<p class="description" style="max-width:840px;"><strong><?php esc_html_e( 'What it does.', 'ai-eshop-optimizer' ); ?></strong> <?php esc_html_e( 'Tells Meta which visitors viewed products, started checkout and bought, so Facebook and Instagram ads can attribute sales, optimise delivery and build retargeting audiences. Meta\'s pixel does NOT collect these on its own — only PageView fires automatically, so AIEO explicitly sends ViewContent, InitiateCheckout and Purchase. The Conversions API delivers events straight from your server (survives iOS limits and ad-blockers); paired with the browser pixel they share one event_id and Meta de-duplicates them.', 'ai-eshop-optimizer' ); ?></p>
			<p class="description" style="max-width:840px;"><strong><?php esc_html_e( 'How to set up.', 'ai-eshop-optimizer' ); ?></strong> <?php esc_html_e( 'Pick a Mode — "Conversions API only" is the robust server-side default; "Browser pixel + CAPI" adds the in-page pixel for the best match rate. Enter your Pixel ID (Meta Events Manager → Data sources → your dataset) and, for CAPI, a System-User access token (same dataset → Settings → Conversions API → Generate access token). Use the Test event code to confirm events appear under Events Manager → Test events, then clear it for production.', 'ai-eshop-optimizer' ); ?></p>
			<table class="form-table">
				<tr>
					<th scope="row"><?php esc_html_e( 'Mode', 'ai-eshop-optimizer' ); ?></th>
					<td>
						<select name="fb_mode" id="aieo-fb-mode">
							<option value="off"     <?php selected( $s['fb_mode'], 'off' ); ?>><?php esc_html_e( 'Off — don\'t send (I use another tool)', 'ai-eshop-optimizer' ); ?></option>
							<option value="browser" <?php selected( $s['fb_mode'], 'browser' ); ?>><?php esc_html_e( 'Browser pixel only', 'ai-eshop-optimizer' ); ?></option>
							<option value="capi"    <?php selected( $s['fb_mode'], 'capi' ); ?>><?php esc_html_e( 'Conversions API only (server-side)', 'ai-eshop-optimizer' ); ?></option>
							<option value="both"    <?php selected( $s['fb_mode'], 'both' ); ?>><?php esc_html_e( 'Browser pixel + CAPI (deduplicated) — recommended', 'ai-eshop-optimizer' ); ?></option>
						</select>
						<p class="description"><?php esc_html_e( 'Browser + CAPI share one event_id so Meta de-duplicates them — better match rates, resilient to iOS / ad-blockers.', 'ai-eshop-optimizer' ); ?></p>
					</td>
				</tr>
				<tr class="aieo-fb-field">
					<th scope="row"><?php esc_html_e( 'Pixel ID', 'ai-eshop-optimizer' ); ?></th>
					<td><input type="text" name="fb_pixel_id" value="<?php echo esc_attr( $s['fb_pixel_id'] ); ?>" class="regular-text" inputmode="numeric" placeholder="000000000000000"></td>
				</tr>
				<tr class="aieo-fb-field aieo-fb-capi-field">
					<th scope="row"><?php esc_html_e( 'Access token (CAPI)', 'ai-eshop-optimizer' ); ?></th>
					<td>
						<input type="password" name="fb_access_token" value="" class="regular-text" autocomplete="new-password" placeholder="<?php echo $has_fb_token ? esc_attr__( '•••••••• stored — leave blank to keep', 'ai-eshop-optimizer' ) : ''; ?>">
						<p class="description"><?php esc_html_e( 'System-User token from Meta Events Manager. Stored server-side; never exposed to the browser.', 'ai-eshop-optimizer' ); ?></p>
					</td>
				</tr>
				<tr class="aieo-fb-field aieo-fb-capi-field">
					<th scope="row"><?php esc_html_e( 'Test event code', 'ai-eshop-optimizer' ); ?></th>
					<td>
						<input type="text" name="fb_test_event_code" value="<?php echo esc_attr( $s['fb_test_event_code'] ); ?>" class="regular-text" placeholder="TEST00000">
						<p class="description"><?php esc_html_e( 'Optional — shows events under "Test events" in Events Manager while you verify. Clear it for production.', 'ai-eshop-optimizer' ); ?></p>
					</td>
				</tr>
			</table>
		</div>

		<!-- TikTok -->
		<div class="aieo-dmm-card">
			<h3><?php esc_html_e( 'TikTok — Pixel & Events API', 'ai-eshop-optimizer' ); ?></h3>
			<p class="description" style="max-width:840px;"><strong><?php esc_html_e( 'What it does.', 'ai-eshop-optimizer' ); ?></strong> <?php esc_html_e( 'Reports product views, checkouts and purchases to TikTok so your TikTok ads can attribute conversions and optimise bidding. As with Meta, the pixel does not collect the funnel by itself — AIEO sends the events explicitly. The Events API delivers them server-side; combined with the browser pixel they share one event_id for de-duplication, and the click id (ttclid) is recovered from the visitor session.', 'ai-eshop-optimizer' ); ?></p>
			<p class="description" style="max-width:840px;"><strong><?php esc_html_e( 'How to set up.', 'ai-eshop-optimizer' ); ?></strong> <?php esc_html_e( 'Pick a Mode ("Events API only" is the robust default; "Browser pixel + Events API" adds the in-page pixel). Enter your Pixel ID / code (TikTok Events Manager → your pixel → Settings) and, for the server side, an Events API access token (same pixel → Manage → Generate access token). Verify with a Test event code under TikTok\'s Test events, then clear it.', 'ai-eshop-optimizer' ); ?></p>
			<table class="form-table">
				<tr>
					<th scope="row"><?php esc_html_e( 'Mode', 'ai-eshop-optimizer' ); ?></th>
					<td>
						<select name="tiktok_mode" id="aieo-tt-mode">
							<option value="off"     <?php selected( $s['tiktok_mode'], 'off' ); ?>><?php esc_html_e( 'Off — don\'t send (I use another tool)', 'ai-eshop-optimizer' ); ?></option>
							<option value="browser" <?php selected( $s['tiktok_mode'], 'browser' ); ?>><?php esc_html_e( 'Browser pixel only', 'ai-eshop-optimizer' ); ?></option>
							<option value="server"  <?php selected( $s['tiktok_mode'], 'server' ); ?>><?php esc_html_e( 'Events API only (server-side)', 'ai-eshop-optimizer' ); ?></option>
							<option value="both"    <?php selected( $s['tiktok_mode'], 'both' ); ?>><?php esc_html_e( 'Browser pixel + Events API (deduplicated) — recommended', 'ai-eshop-optimizer' ); ?></option>
						</select>
						<p class="description"><?php esc_html_e( 'Browser + Events API share one event_id so TikTok de-duplicates them — better match rates, resilient to iOS / ad-blockers. The ttclid is recovered from the visitor\'s session.', 'ai-eshop-optimizer' ); ?></p>
					</td>
				</tr>
				<tr class="aieo-tt-field">
					<th scope="row"><?php esc_html_e( 'Pixel ID (code)', 'ai-eshop-optimizer' ); ?></th>
					<td><input type="text" name="tiktok_pixel_id" value="<?php echo esc_attr( $s['tiktok_pixel_id'] ); ?>" class="regular-text" placeholder="CXXXXXXXXXXXXXXXXXXX"></td>
				</tr>
				<tr class="aieo-tt-field aieo-tt-server-field">
					<th scope="row"><?php esc_html_e( 'Access token (Events API)', 'ai-eshop-optimizer' ); ?></th>
					<td>
						<input type="password" name="tiktok_access_token" value="" class="regular-text" autocomplete="new-password" placeholder="<?php echo $has_tt_token ? esc_attr__( '•••••••• stored — leave blank to keep', 'ai-eshop-optimizer' ) : ''; ?>">
						<p class="description"><?php esc_html_e( 'Long-lived token from TikTok Events Manager / Marketing API. Stored server-side; never exposed to the browser.', 'ai-eshop-optimizer' ); ?></p>
					</td>
				</tr>
				<tr class="aieo-tt-field aieo-tt-server-field">
					<th scope="row"><?php esc_html_e( 'Test event code', 'ai-eshop-optimizer' ); ?></th>
					<td>
						<input type="text" name="tiktok_test_event_code" value="<?php echo esc_attr( $s['tiktok_test_event_code'] ); ?>" class="regular-text" placeholder="TEST00000">
						<p class="description"><?php esc_html_e( 'Optional — shows events under "Test Events" in TikTok Events Manager while you verify. Clear it for production.', 'ai-eshop-optimizer' ); ?></p>
					</td>
				</tr>
			</table>
		</div>

		<!-- Google / GA4 -->
		<div class="aieo-dmm-card">
			<h3><?php esc_html_e( 'Google Analytics 4', 'ai-eshop-optimizer' ); ?></h3>
			<p class="description" style="max-width:840px;"><strong><?php esc_html_e( 'What it does.', 'ai-eshop-optimizer' ); ?></strong> <?php esc_html_e( 'Your measurement hub. It records the full shopping funnel (view_item, view_item_list, add_to_cart, begin_checkout, purchase) plus traffic and audiences, and is the source Google Ads pulls from for imported conversions, remarketing lists and Smart-Bidding signals. AIEO can feed it from the browser (through the Google tag below) and/or server-side (Measurement Protocol), deduplicated by transaction_id.', 'ai-eshop-optimizer' ); ?></p>
			<p class="description" style="max-width:840px;"><strong><?php esc_html_e( 'How to set up.', 'ai-eshop-optimizer' ); ?></strong> <?php esc_html_e( 'Choose "AIEO handles GA4", then enter your Measurement ID (G-XXXXXXXXXX — GA4 → Admin → Data streams → your web stream). For the server-side send also add a Measurement Protocol API secret (same Data stream → Measurement Protocol API secrets → Create) and tick "Server". Keep "Browser (gtag)" ticked and set the Google tag below to gtag. If you already run Google Site Kit, choose "Defer to Site Kit" so AIEO stays silent and you avoid double-counting. Enhanced Measurement (scrolls, site search, outbound clicks) is switched on in GA4 Admin, not here.', 'ai-eshop-optimizer' ); ?></p>
			<table class="form-table">
				<tr>
					<th scope="row"><?php esc_html_e( 'Source', 'ai-eshop-optimizer' ); ?></th>
					<td>
						<select name="ga_source" id="aieo-ga-source">
							<option value="off"     <?php selected( $s['ga_source'], 'off' ); ?>><?php esc_html_e( 'Off — don\'t send GA4 events', 'ai-eshop-optimizer' ); ?></option>
							<option value="aieo"    <?php selected( $s['ga_source'], 'aieo' ); ?>><?php esc_html_e( 'AIEO handles GA4 (send events from here)', 'ai-eshop-optimizer' ); ?></option>
							<option value="sitekit" <?php selected( $s['ga_source'], 'sitekit' ); ?>><?php esc_html_e( 'Defer to Google Site Kit / my existing GA — AIEO sends nothing', 'ai-eshop-optimizer' ); ?></option>
						</select>
						<?php if ( $sitekit_active ) : ?>
							<p class="description" style="color:#15803d;"><?php esc_html_e( 'Google Site Kit is active here — choose "Defer to Site Kit" to let it own GA4 and avoid double-counting.', 'ai-eshop-optimizer' ); ?></p>
						<?php endif; ?>
					</td>
				</tr>
				<tr class="aieo-ga-field">
					<th scope="row"><?php esc_html_e( 'Measurement ID', 'ai-eshop-optimizer' ); ?></th>
					<td><input type="text" name="ga_measurement_id" value="<?php echo esc_attr( $s['ga_measurement_id'] ); ?>" class="regular-text" placeholder="G-XXXXXXXXXX"></td>
				</tr>
				<tr class="aieo-ga-field">
					<th scope="row"><?php esc_html_e( 'API secret (Measurement Protocol)', 'ai-eshop-optimizer' ); ?></th>
					<td>
						<input type="password" name="ga_api_secret" value="" class="regular-text" autocomplete="new-password" placeholder="<?php echo $has_ga_secret ? esc_attr__( '•••••••• stored — leave blank to keep', 'ai-eshop-optimizer' ) : ''; ?>">
						<p class="description"><?php esc_html_e( 'GA4 → Admin → Data Streams → Measurement Protocol API secrets. Needed only for server-side sending.', 'ai-eshop-optimizer' ); ?></p>
					</td>
				</tr>
				<tr class="aieo-ga-field">
					<th scope="row"><?php esc_html_e( 'Send via', 'ai-eshop-optimizer' ); ?></th>
					<td>
						<label style="display:block;margin-bottom:4px;"><input type="checkbox" name="ga_send_browser" value="1" <?php checked( $s['ga_send_browser'], 'yes' ); ?>> <?php esc_html_e( 'Browser (gtag)', 'ai-eshop-optimizer' ); ?></label>
						<label style="display:block;"><input type="checkbox" name="ga_send_server" value="1" <?php checked( $s['ga_send_server'], 'yes' ); ?>> <?php esc_html_e( 'Server (Measurement Protocol)', 'ai-eshop-optimizer' ); ?></label>
					</td>
				</tr>
			</table>
		</div>

		<!-- The Google tag (gtag.js / GTM) -->
		<div class="aieo-dmm-card">
			<h3><?php esc_html_e( 'Google tag', 'ai-eshop-optimizer' ); ?></h3>
			<p class="description" style="max-width:840px;"><strong><?php esc_html_e( 'What it does.', 'ai-eshop-optimizer' ); ?></strong> <?php esc_html_e( 'Loads Google\'s single gtag.js (or your Tag Manager container) once per page — the shared delivery pipe that BOTH GA4 and Google Ads ride on. Without it, the browser-side GA4 events and Google Ads Enhanced Conversions have no tag to fire through. It automatically inherits AIEO\'s Consent Mode v2 defaults.', 'ai-eshop-optimizer' ); ?></p>
			<p class="description" style="max-width:840px;"><strong><?php esc_html_e( 'How to set up.', 'ai-eshop-optimizer' ); ?></strong> <?php esc_html_e( 'Set Load mode to "Google tag (gtag.js)" — AIEO then loads it directly and auto-configures the GA4 and Google Ads IDs you enter in the cards above, so there is nothing else to fill in. Choose "Google Tag Manager" only if you manage tags in a GTM container (then enter its GTM-XXXXXXX id). Leave it "Off" only when another plugin (e.g. Site Kit) already loads the tag, to avoid loading it twice.', 'ai-eshop-optimizer' ); ?></p>
			<table class="form-table">
				<tr>
					<th scope="row"><?php esc_html_e( 'Load mode', 'ai-eshop-optimizer' ); ?></th>
					<td>
						<select name="google_tag_mode" id="aieo-google-tag-mode">
							<option value="off"  <?php selected( $s['google_tag_mode'], 'off' ); ?>><?php esc_html_e( 'Off (another tool loads it)', 'ai-eshop-optimizer' ); ?></option>
							<option value="gtag" <?php selected( $s['google_tag_mode'], 'gtag' ); ?>><?php esc_html_e( 'Google tag (gtag.js)', 'ai-eshop-optimizer' ); ?></option>
							<option value="gtm"  <?php selected( $s['google_tag_mode'], 'gtm' ); ?>><?php esc_html_e( 'Google Tag Manager (container)', 'ai-eshop-optimizer' ); ?></option>
						</select>
					</td>
				</tr>
				<tr class="aieo-gtm-field">
					<th scope="row"><?php esc_html_e( 'GTM container id', 'ai-eshop-optimizer' ); ?></th>
					<td><input type="text" name="gtm_container_id" value="<?php echo esc_attr( $s['gtm_container_id'] ); ?>" class="regular-text" placeholder="GTM-XXXXXXX"></td>
				</tr>
			</table>
		</div>

		<!-- Google Ads — conversions + Enhanced Conversions -->
		<div class="aieo-dmm-card">
			<h3><?php esc_html_e( 'Google Ads — conversions & Enhanced Conversions', 'ai-eshop-optimizer' ); ?></h3>
			<p class="description" style="max-width:840px;"><strong><?php esc_html_e( 'What it does.', 'ai-eshop-optimizer' ); ?></strong> <?php esc_html_e( 'Fires a Google Ads purchase conversion — with Enhanced Conversions (hashed first-party email / phone) for better match rates — so Google Ads can report each campaign\'s revenue and feed Smart Bidding. This is the direct, most reliable signal; Google Ads can alternatively import the same purchase from a linked GA4 property.', 'ai-eshop-optimizer' ); ?></p>
			<p class="description" style="max-width:840px;"><strong><?php esc_html_e( 'How to set up.', 'ai-eshop-optimizer' ); ?></strong> <?php esc_html_e( 'Needs the Google tag above set to gtag or GTM. Enter your Conversion id (AW-XXXXXXXXXX) and Conversion label (the code after the slash — see the field note below). Both live in Google Ads → Goals → Conversions → your Purchase action → Tag setup. Optionally tick "Server-side EC" to also upload Enhanced Conversions through the Ads API (resilient to ad-blockers) and fill the credentials below.', 'ai-eshop-optimizer' ); ?></p>
			<table class="form-table">
				<tr>
					<th scope="row"><?php esc_html_e( 'Conversion id', 'ai-eshop-optimizer' ); ?></th>
					<td><input type="text" name="ads_conversion_id" value="<?php echo esc_attr( $s['ads_conversion_id'] ); ?>" class="regular-text" placeholder="AW-XXXXXXXXXX"></td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'Conversion label', 'ai-eshop-optimizer' ); ?></th>
					<td><input type="text" name="ads_conversion_label" value="<?php echo esc_attr( $s['ads_conversion_label'] ); ?>" class="regular-text" placeholder="AbC-D_efG">
						<p class="description" style="max-width:760px;"><?php esc_html_e( 'The part AFTER the slash in your Google Ads purchase tag (AW-XXXXXXXXXX / AbC-D_efG). Without it the purchase conversion maps to NO action and Google Ads records nothing. Get it from Google Ads → Goals → Conversions → your Purchase action → "Tag setup / Use Google tag". Optional — leave blank if your purchase is imported from a linked GA4 property instead.', 'ai-eshop-optimizer' ); ?></p></td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'Server-side EC (Ads API)', 'ai-eshop-optimizer' ); ?></th>
					<td><label><input type="checkbox" name="ads_server_ec" value="1" id="aieo-ads-server-ec" <?php checked( $s['ads_server_ec'], 'yes' ); ?>> <?php esc_html_e( 'Also upload Enhanced Conversions from the server (needs the credentials below)', 'ai-eshop-optimizer' ); ?></label></td>
				</tr>
			</table>
			<table class="form-table aieo-ads-api-field">
				<tr>
					<th scope="row"><?php esc_html_e( 'Developer token', 'ai-eshop-optimizer' ); ?></th>
					<td><input type="text" name="ads_developer_token" value="" class="regular-text" autocomplete="off" placeholder="<?php echo esc_attr( '' !== (string) $s['ads_developer_token'] ? __( '•••••• (saved — leave blank to keep)', 'ai-eshop-optimizer' ) : '' ); ?>"></td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'Customer id', 'ai-eshop-optimizer' ); ?></th>
					<td><input type="text" name="ads_customer_id" value="<?php echo esc_attr( $s['ads_customer_id'] ); ?>" class="regular-text" placeholder="1234567890"></td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'Login customer id (MCC)', 'ai-eshop-optimizer' ); ?></th>
					<td><input type="text" name="ads_login_customer_id" value="<?php echo esc_attr( $s['ads_login_customer_id'] ); ?>" class="regular-text" placeholder="<?php esc_attr_e( 'optional', 'ai-eshop-optimizer' ); ?>"></td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'Conversion action id', 'ai-eshop-optimizer' ); ?></th>
					<td><input type="text" name="ads_conversion_action_id" value="<?php echo esc_attr( $s['ads_conversion_action_id'] ); ?>" class="regular-text" placeholder="987654321"></td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'OAuth client id', 'ai-eshop-optimizer' ); ?></th>
					<td><input type="text" name="ads_oauth_client_id" value="<?php echo esc_attr( $s['ads_oauth_client_id'] ); ?>" class="regular-text" autocomplete="off"></td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'OAuth client secret', 'ai-eshop-optimizer' ); ?></th>
					<td><input type="text" name="ads_oauth_client_secret" value="" class="regular-text" autocomplete="off" placeholder="<?php echo esc_attr( '' !== (string) $s['ads_oauth_client_secret'] ? __( '•••••• (saved — leave blank to keep)', 'ai-eshop-optimizer' ) : '' ); ?>"></td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'OAuth refresh token', 'ai-eshop-optimizer' ); ?></th>
					<td><input type="text" name="ads_oauth_refresh_token" value="" class="regular-text" autocomplete="off" placeholder="<?php echo esc_attr( '' !== (string) $s['ads_oauth_refresh_token'] ? __( '•••••• (saved — leave blank to keep)', 'ai-eshop-optimizer' ) : '' ); ?>"></td>
				</tr>
			</table>
		</div>

		<!-- Server-side delivery -->
		<div class="aieo-dmm-card">
			<h3><?php esc_html_e( 'Server-side delivery', 'ai-eshop-optimizer' ); ?></h3>
			<p class="description" style="max-width:820px;"><?php esc_html_e( 'How AIEO sends the server-side conversion events (Meta CAPI, GA4, TikTok, Google Ads) after an order. The shopper never waits in either mode — the page response is flushed to the browser first.', 'ai-eshop-optimizer' ); ?></p>
			<table class="form-table">
				<tr>
					<th scope="row"><?php esc_html_e( 'Fire-and-forget', 'ai-eshop-optimizer' ); ?></th>
					<td>
						<label><input type="checkbox" name="server_event_async" value="1" <?php checked( ( $s['server_event_blocking'] ?? 'no' ), 'no' ); ?>> <?php esc_html_e( 'Send events instantly without waiting for the platform\'s reply (fastest — recommended)', 'ai-eshop-optimizer' ); ?></label>
						<p class="description"><?php esc_html_e( 'On (default, best for busy stores): events fire the moment the order is paid and appear as "dispatched" in the table below. Turn it OFF to make AIEO wait for each reply and log sent / failed per event — handy while you set things up. A test-event code always waits, regardless of this setting.', 'ai-eshop-optimizer' ); ?></p>
					</td>
				</tr>
			</table>
		</div>

		<!-- First-party consent (GDPR) — moved to its own tab -->
		<div class="aieo-dmm-card">
			<h3><?php esc_html_e( 'Consent / GDPR', 'ai-eshop-optimizer' ); ?></h3>
			<p class="description" style="max-width:820px;">
				<?php
				echo wp_kses_post( sprintf(
					
					__( 'The first-party consent banner, cookie scanner and theming now live on their own page: %s.', 'ai-eshop-optimizer' ),
					'<a href="' . esc_url( admin_url( 'admin.php?page=ai-eshop-dmm&dmm_tab=consent' ) ) . '"><strong>' . esc_html__( 'Consent / GDPR', 'ai-eshop-optimizer' ) . '</strong></a>'
				) );
				?>
			</p>
		</div>

		<p>
			<button type="button" class="button button-primary" id="aieo-dmm-conv-save"><?php esc_html_e( 'Save settings', 'ai-eshop-optimizer' ); ?></button>
			<span id="aieo-dmm-conv-status" style="margin-left:10px;font-weight:600;"></span>
		</p>
	</form>

	<div class="aieo-dmm-card">
		<h3><?php esc_html_e( 'Recent server events', 'ai-eshop-optimizer' ); ?></h3>
		<?php if ( empty( $recent_events ) ) : ?>
			<p class="description"><?php esc_html_e( 'No server-side events sent yet. Purchases appear here once a platform mode is server-side (CAPI / Events API / Both) with valid credentials and consent is granted.', 'ai-eshop-optimizer' ); ?></p>
		<?php else : ?>
			<table class="widefat striped" style="margin-top:6px;">
				<thead><tr>
					<th><?php esc_html_e( 'When (UTC)', 'ai-eshop-optimizer' ); ?></th>
					<th><?php esc_html_e( 'Platform', 'ai-eshop-optimizer' ); ?></th>
					<th><?php esc_html_e( 'Event', 'ai-eshop-optimizer' ); ?></th>
					<th><?php esc_html_e( 'Order', 'ai-eshop-optimizer' ); ?></th>
					<th><?php esc_html_e( 'Status', 'ai-eshop-optimizer' ); ?></th>
					<th><?php esc_html_e( 'HTTP', 'ai-eshop-optimizer' ); ?></th>
					<th><?php esc_html_e( 'Value', 'ai-eshop-optimizer' ); ?></th>
					<th><?php esc_html_e( 'Mode', 'ai-eshop-optimizer' ); ?></th>
					<th><?php esc_html_e( 'event_id', 'ai-eshop-optimizer' ); ?></th>
				</tr></thead>
				<tbody>
				<?php foreach ( $recent_events as $ev ) :
					$status = (string) ( $ev['status'] ?? '' );
					$color  = ( 'sent' === $status ) ? '#15803d' : ( 'failed' === $status ? '#b91c1c' : '#6b7280' );
				?>
					<tr>
						<td><?php echo esc_html( (string) ( $ev['created_at'] ?? '' ) ); ?></td>
						<td><?php echo esc_html( strtoupper( (string) ( $ev['platform'] ?? '' ) ) ); ?></td>
						<td><?php echo esc_html( (string) ( $ev['event_name'] ?? '' ) ); ?></td>
						<td><?php
							$oid = (int) ( $ev['order_id'] ?? 0 );
							if ( $oid > 0 ) {
								echo '<a href="' . esc_url( admin_url( 'post.php?post=' . $oid . '&action=edit' ) ) . '" target="_blank" rel="noopener">#' . esc_html( $oid ) . '</a>';
							} else {
								echo '&mdash;';
							}
						?></td>
						<td><strong style="color:<?php echo esc_attr( $color ); ?>;"><?php echo esc_html( $status ); ?></strong></td>
						<td title="<?php echo esc_attr( (string) ( $ev['fbtrace_id'] ?? '' ) ); ?>"><?php echo esc_html( (string) ( $ev['http_code'] ?? '' ) ); ?></td>
						<td><?php echo esc_html( ( '' !== (string) ( $ev['value'] ?? '' ) ) ? number_format_i18n( (float) $ev['value'], 2 ) . ' ' . (string) ( $ev['currency'] ?? '' ) : '' ); ?></td>
						<td><?php echo ! empty( $ev['test_mode'] ) ? '<span class="aieo-c-chip">test</span>' : esc_html__( 'live', 'ai-eshop-optimizer' ); ?></td>
						<td><code style="font-size:11px;color:#9ca3af;"><?php echo esc_html( substr( (string) ( $ev['event_id'] ?? '' ), 0, 8 ) ); ?></code></td>
					</tr>
				<?php endforeach; ?>
				</tbody>
			</table>
		<?php endif; ?>
	</div>
</div>

<script>
(function(){
	var form = document.getElementById('aieo-dmm-conversions-form');
	if (!form) { return; }
	var fbMode   = document.getElementById('aieo-fb-mode');
	var gaSource = document.getElementById('aieo-ga-source');

	function show(el, on){ if (el) { el.style.display = on ? '' : 'none'; } }
	function each(sel, cb){ Array.prototype.forEach.call(form.querySelectorAll(sel), cb); }

	function syncFb(){
		var m = fbMode ? fbMode.value : 'off';
		var on = (m !== 'off');
		each('.aieo-fb-field', function(r){ show(r, on); });
		var capiOn = on && (m === 'capi' || m === 'both');
		each('.aieo-fb-capi-field', function(r){ show(r, capiOn); });
	}
	function syncGa(){
		var owns = gaSource && gaSource.value === 'aieo';
		each('.aieo-ga-field', function(r){ show(r, owns); });
	}
	var ttMode = document.getElementById('aieo-tt-mode');
	function syncTt(){
		var m = ttMode ? ttMode.value : 'off';
		var on = (m !== 'off');
		each('.aieo-tt-field', function(r){ show(r, on); });
		var srvOn = on && (m === 'server' || m === 'both');
		each('.aieo-tt-server-field', function(r){ show(r, srvOn); });
	}
	if (fbMode)   { fbMode.addEventListener('change', syncFb); }
	if (gaSource) { gaSource.addEventListener('change', syncGa); }
	if (ttMode)   { ttMode.addEventListener('change', syncTt); }
	syncFb(); syncGa(); syncTt();

	var btn = document.getElementById('aieo-dmm-conv-save');
	var status = document.getElementById('aieo-dmm-conv-status');
	if (!btn) { return; }
	btn.addEventListener('click', function(){
		var fd = new FormData(form);
		fd.set('action', 'aieo_dmm_conversions_save');
		fd.set('nonce', '<?php echo esc_js( $nonce ); ?>');
		status.style.color = '#6b7280';
		status.textContent = '<?php echo esc_js( __( 'Saving…', 'ai-eshop-optimizer' ) ); ?>';
		fetch('<?php echo esc_js( $ajax ); ?>', { method:'POST', credentials:'same-origin', body: fd })
			.then(function(r){ return r.json(); })
			.then(function(j){
				if (j && j.success) { status.style.color = '#15803d'; status.textContent = j.data.message; }
				else { status.style.color = '#b91c1c'; status.textContent = (j && j.data && j.data.message) ? j.data.message : 'Save failed.'; }
			})
			.catch(function(){ status.style.color = '#b91c1c'; status.textContent = 'Network error.'; });
	});
})();
</script>
