<?php
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals
// phpcs:disable WordPress.Security.NonceVerification
// phpcs:disable WordPress.Security.ValidatedSanitizedInput
// phpcs:disable WordPress.DB.DirectDatabaseQuery
// phpcs:disable WordPress.DB.SlowDBQuery
// phpcs:disable WordPress.DB.PreparedSQL
// phpcs:disable PluginCheck.CodeAnalysis
// phpcs:disable WordPressVIPMinimum
/**
 * GT BOGO Engine — Integrations Hub
 *
 * Enterprise integration management:
 *   - Per-integration live status cards with health indicator
 *   - AJAX test connection button (pings each service, shows latency)
 *   - WooCommerce core integration status (HPOS, Blocks, Subscriptions, Points)
 *   - Email marketing: Mailchimp + Klaviyo API key config + event mapping
 *   - Webhook configuration: add/edit/delete webhooks, event selection
 *   - Webhook delivery log (last 20 deliveries, status codes, retry count)
 *   - PayPal IPN status
 *   - REST API status + endpoint list
 *   - Missing integration recommendations (auto-detect active plugins)
 *
 * @package GT_BOGO_Engine
 * @since   5.0.0
 */
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
if ( ! current_user_can( 'manage_options' ) ) {
	return;
}

global $wpdb;

$is_pro  = function_exists( 'gt_bogo_has_pro' ) ? gt_bogo_has_pro() : false;
$nonce   = wp_create_nonce( 'gtbogo_integrations' );
$message = '';

/* ── Save ─────────────────────────────────────────────────────────────────── */
if ( $is_pro && isset( $_POST['gtbogo_save_integrations'] )
	&& check_admin_referer( 'gtbogo_integrations', 'gtbogo_int_nonce' ) ) {

	$int = array(
		'mailchimp_key'       => sanitize_text_field( wp_unslash( $_POST['mailchimp_key'] ?? '' ) ),
		'klaviyo_key'         => sanitize_text_field( wp_unslash( $_POST['klaviyo_key'] ?? '' ) ),
		'mailchimp_tag_bogo'  => sanitize_text_field( wp_unslash( $_POST['mailchimp_tag_bogo'] ?? 'bogo-customer' ) ),
		'klaviyo_event'       => sanitize_text_field( wp_unslash( $_POST['klaviyo_event'] ?? 'BOGO Redeemed' ) ),
		'slack_webhook'       => esc_url_raw( wp_unslash( $_POST['slack_webhook'] ?? '' ) ),
		'slack_events'        => array_map( 'sanitize_key', (array) ( $_POST['slack_events'] ?? array() ) ),
		'zapier_webhook'      => esc_url_raw( wp_unslash( $_POST['zapier_webhook'] ?? '' ) ),
             'human_handoff_webhook' => esc_url_raw( wp_unslash( $_POST['human_handoff_webhook'] ?? '' ) ),
             'human_handoff_secret'  => sanitize_text_field( wp_unslash( $_POST['human_handoff_secret'] ?? '' ) ),
		'webhook_url'         => esc_url_raw( wp_unslash( $_POST['webhook_url'] ?? '' ) ),
		'webhook_secret'      => sanitize_text_field( wp_unslash( $_POST['webhook_secret'] ?? '' ) ),
		'webhook_on_redeem'   => isset( $_POST['webhook_on_redeem'] ),
		'webhook_on_activate' => isset( $_POST['webhook_on_activate'] ),
		'webhook_on_email'    => isset( $_POST['webhook_on_email'] ),
	);
	update_option( 'gtbogo_integrations', $int );
	$message = 'Integration settings saved.';
}

$int = get_option( 'gtbogo_integrations', array() );

/* ── Plugin detection ─────────────────────────────────────────────────────── */
$has_wc            = class_exists( 'WooCommerce' );
$has_subscriptions = class_exists( 'WC_Subscriptions' );
$has_points        = class_exists( 'WC_Points_Rewards' ) || class_exists( 'YITH_WC_Points_Rewards' );
$has_memberships   = class_exists( 'WC_Memberships' );
$has_mailchimp     = defined( 'MAILCHIMP_FOR_WP_VERSION' ) || class_exists( 'MailChimp_WooCommerce' );
$has_klaviyo       = defined( 'KLAVIYO_FOR_WC' ) || class_exists( 'WC_Klaviyo' );
$has_wpml          = defined( 'ICL_SITEPRESS_VERSION' );
$has_polylang      = function_exists( 'pll_register_string' );
$hpos              = class_exists( 'Automattic\WooCommerce\Utilities\OrderUtil' );
$wc_blocks         = class_exists( 'Automattic\WooCommerce\Blocks\BlocksController' );
$redis_ok          = wp_using_ext_object_cache();

/* ── REST API status ─────────────────────────────────────────────────────── */
$rest_url    = rest_url( 'gtbogo/v1/' );
$rest_active = class_exists( 'GT_BOGO_Rest_API' );

/* ── Webhook log ─────────────────────────────────────────────────────────── */
$webhook_log_tbl = $wpdb->prefix . 'gtbogo_webhook_log';
$webhook_log     = array();
if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $webhook_log_tbl ) ) ) { // phpcs:ignore
    $webhook_log = $wpdb->get_results( // phpcs:ignore
		"SELECT url, event, response_code, response_ms, retry_count, sent_at
         FROM {$webhook_log_tbl} ORDER BY sent_at DESC LIMIT 20",
		ARRAY_A
	) ?: array();
}

/* ── Active GT BOGO webhooks ─────────────────────────────────────────────── */
$active_webhooks = get_option( 'gtbogo_webhooks', array() );

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

<div class="gt-page-header gt-animate-in" style="align-items:flex-start">
	<div>
		<h1 class="gt-page-title">🔌 Integrations Hub</h1>
		<p class="gt-page-subtitle">
			Connect GT BOGO Engine to your marketing stack — email platforms,
			webhooks, and WooCommerce extensions.
		</p>
	</div>
</div>

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

<!-- ═══ INTEGRATION STATUS CARDS ═══════════════════════════════════════════ -->
<div class="gt-animate-in" style="display:grid;grid-template-columns:repeat(4,1fr);gap:14px;margin-bottom:20px">
	<?php
	$integrations_status = array(
		array( 'WooCommerce', $has_wc, 'Core cart engine', '#22c55e' ),
		array( 'WC Blocks', $wc_blocks, 'Blocks cart compatible', '#22c55e' ),
		array( 'HPOS Orders', $hpos, 'High performance orders', $hpos ? '#22c55e' : 'var(--gt-subtle)' ),
		array( 'WC Subscriptions', $has_subscriptions, 'Subscription intelligence', $has_subscriptions ? '#22c55e' : '#64748b' ),
		array( 'Points & Rewards', $has_points, 'Loyalty points sync', $has_points ? '#22c55e' : '#64748b' ),
		array( 'WC Memberships', $has_memberships, 'Member-only deals', $has_memberships ? '#22c55e' : '#64748b' ),
		array( 'Redis Object Cache', $redis_ok, 'Performance layer', $redis_ok ? '#22c55e' : '#f59e0b' ),
		array( 'REST API', $rest_active, 'API endpoints active', $rest_active ? '#22c55e' : '#64748b' ),
	);
	foreach ( $integrations_status as $is ) :
		$ic = $is[1] ? $is[3] : '#64748b';
		?>
	<div class="gt-card" style="padding:16px 18px">
		<div style="display:flex;align-items:center;gap:10px;margin-bottom:6px">
			<div style="width:8px;height:8px;border-radius:50%;background:<?php echo esc_attr( $ic ); ?>;
						box-shadow:0 0 <?php echo $is[1] ? '6px' : '0'; ?> <?php echo esc_attr( $ic ); ?>;flex-shrink:0"></div>
			<div style="font-size:12px;font-weight:700;color:var(--gt-white)">
				<?php echo esc_html( $is[0] ); ?>
			</div>
		</div>
		<div style="font-size:10px;color:var(--gt-subtle)"><?php echo esc_html( $is[2] ); ?></div>
		<div style="font-size:10px;font-weight:700;color:<?php echo esc_attr( $ic ); ?>;margin-top:4px">
			<?php echo $is[1] ? '✓ Active' : '○ Not detected'; ?>
		</div>
	</div>
	<?php endforeach; ?>
</div>

<?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>Integration configuration requires a PRO license.</p>
	<a href="https://graphictshirts.shop/bogo/" target="_blank" rel="noopener" class="gt-btn gt-btn-primary">Purchase PRO</a>
</div>
<?php else : ?>

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

<!-- ═══ EMAIL MARKETING ═══════════════════════════════════════════════════════ -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header">
		<h2 class="gt-card-title">✉️ Email Marketing</h2>
		<button type="button" class="gt-btn gt-btn-ghost gt-btn-sm"
			onclick="gtIntTestEmail('<?php echo esc_js( $nonce ); ?>')">
			🔌 Test Connections
		</button>
	</div>

	<!-- Mailchimp -->
	<div style="padding:16px 0;border-bottom:1px solid var(--gt-border)">
		<div style="display:flex;align-items:center;gap:10px;margin-bottom:12px">
			<div id="gt-int-mc-dot"
				style="width:8px;height:8px;border-radius:50%;background:<?php echo ! empty( $int['mailchimp_key'] ) ? '#22c55e' : '#64748b'; ?>;flex-shrink:0"></div>
			<div style="font-size:13px;font-weight:700;color:var(--gt-white)">Mailchimp</div>
			<?php if ( $has_mailchimp ) : ?>
			<span style="font-size:10px;background:rgba(34,197,94,0.1);border:1px solid rgba(34,197,94,0.3);color:#22c55e;padding:1px 7px;border-radius:20px">Plugin detected</span>
			<?php endif; ?>
		</div>
		<div style="display:grid;grid-template-columns:1fr 1fr;gap:14px">
			<div class="gt-form-group" style="margin:0">
				<label class="gt-form-label">Mailchimp API Key</label>
				<input type="password" name="mailchimp_key" class="gt-input"
						value="<?php echo esc_attr( $int['mailchimp_key'] ?? '' ); ?>"
						placeholder="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-us1">
				<div class="gt-form-hint">Found at Mailchimp → Account → Extras → API keys</div>
			</div>
			<div class="gt-form-group" style="margin:0">
				<label class="gt-form-label">BOGO Customer Tag</label>
				<input type="text" name="mailchimp_tag_bogo" class="gt-input"
						value="<?php echo esc_attr( $int['mailchimp_tag_bogo'] ?? 'bogo-customer' ); ?>"
						placeholder="bogo-customer">
				<div class="gt-form-hint">Applied to contacts who complete a BOGO deal</div>
			</div>
		</div>
	</div>

	<!-- Klaviyo -->
	<div style="padding:16px 0">
		<div style="display:flex;align-items:center;gap:10px;margin-bottom:12px">
			<div id="gt-int-kl-dot"
				style="width:8px;height:8px;border-radius:50%;background:<?php echo ! empty( $int['klaviyo_key'] ) ? '#22c55e' : '#64748b'; ?>;flex-shrink:0"></div>
			<div style="font-size:13px;font-weight:700;color:var(--gt-white)">Klaviyo</div>
			<?php if ( $has_klaviyo ) : ?>
			<span style="font-size:10px;background:rgba(34,197,94,0.1);border:1px solid rgba(34,197,94,0.3);color:#22c55e;padding:1px 7px;border-radius:20px">Plugin detected</span>
			<?php endif; ?>
		</div>
		<div style="display:grid;grid-template-columns:1fr 1fr;gap:14px">
			<div class="gt-form-group" style="margin:0">
				<label class="gt-form-label">Klaviyo Private API Key</label>
				<input type="password" name="klaviyo_key" class="gt-input"
						value="<?php echo esc_attr( $int['klaviyo_key'] ?? '' ); ?>"
						placeholder="pk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx">
				<div class="gt-form-hint">Found at Klaviyo → Account → API Keys</div>
			</div>
			<div class="gt-form-group" style="margin:0">
				<label class="gt-form-label">BOGO Event Name</label>
				<input type="text" name="klaviyo_event" class="gt-input"
						value="<?php echo esc_attr( $int['klaviyo_event'] ?? 'BOGO Redeemed' ); ?>"
						placeholder="BOGO Redeemed">
				<div class="gt-form-hint">Klaviyo metric name for BOGO redemption events</div>
			</div>
		</div>
	</div>
</div>

<!-- ═══ WEBHOOKS ════════════════════════════════════════════════════════════ -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header">
		<h2 class="gt-card-title">🔗 Webhook Configuration</h2>
		<button type="button" class="gt-btn gt-btn-ghost gt-btn-sm"
			onclick="gtIntTestWebhook('<?php echo esc_js( $nonce ); ?>')">
			Send Test →
		</button>
	</div>

	<div style="display:grid;grid-template-columns:1fr 1fr;gap:14px;margin-bottom:16px">
		<div class="gt-form-group" style="margin:0">
			<label class="gt-form-label">Webhook URL</label>
			<input type="url" name="webhook_url" class="gt-input"
					value="<?php echo esc_attr( $int['webhook_url'] ?? '' ); ?>"
					placeholder="https://yoursite.com/webhook">
			<div class="gt-form-hint">Receives POST with BOGO event data on configured triggers</div>
		</div>
		<div class="gt-form-group" style="margin:0">
			<label class="gt-form-label">Webhook Secret (for HMAC signing)</label>
			<input type="text" name="webhook_secret" class="gt-input"
					value="<?php echo esc_attr( $int['webhook_secret'] ?? '' ); ?>"
					placeholder="whsec_xxxxxxxxxxxxxxxxxxxx">
			<div class="gt-form-hint">Sent as X-GTBOGO-Signature header for payload verification</div>
		</div>
	</div>

	<div style="margin-bottom:14px">
		<div class="gt-form-label" style="margin-bottom:8px">Trigger Events</div>
		<?php
		$wh_events = array(
			array( 'webhook_on_redeem', 'Deal Redeemed', 'Fires when a customer completes checkout with a BOGO discount applied' ),
			array( 'webhook_on_activate', 'Rule Activated', 'Fires when a BOGO rule is enabled or imported' ),
			array( 'webhook_on_email', 'Email Triggered', 'Fires when a loyalty or BOGO email is sent' ),
		);
		foreach ( $wh_events as $whe ) :
			?>
		<div class="gt-setting-row" style="padding:8px 0">
			<div>
				<div class="gt-setting-label"><?php echo esc_html( $whe[1] ); ?></div>
				<div class="gt-setting-desc"><?php echo esc_html( $whe[2] ); ?></div>
			</div>
			<label class="gt-toggle">
				<input type="checkbox" name="<?php echo esc_attr( $whe[0] ); ?>" value="1"
						<?php checked( ! empty( $int[ $whe[0] ] ) ); ?>>
				<span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span>
			</label>
		</div>
		<?php endforeach; ?>
	</div>
</div>

<!-- ═══ SLACK ═══════════════════════════════════════════════════════════════ -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header">
		<h2 class="gt-card-title">💬 Slack Notifications</h2>
	</div>
	<div style="display:grid;grid-template-columns:1fr 1fr;gap:14px">
		<div class="gt-form-group" style="margin:0">
			<label class="gt-form-label">Slack Webhook URL</label>
			<input type="url" name="slack_webhook" class="gt-input"
					value="<?php echo esc_attr( $int['slack_webhook'] ?? '' ); ?>"
					placeholder="https://hooks.slack.com/services/T.../B.../...">
			<div class="gt-form-hint">Create an incoming webhook at api.slack.com/apps</div>
					<div class="gt-form-group" style="margin-top:16px">
						<label class="gt-form-label">Human Handoff Webhook URL (GAP 7)</label>
						<input type="url" name="human_handoff_webhook" class="gt-input"
							value="<?php echo esc_attr( get_option( 'gtbogo_human_handoff_webhook_url', '' ) ); ?>"
							placeholder="https://hooks.slack.com/services/... or any webhook endpoint">
						<div class="gt-form-hint">Receives a signed POST when a gold/platinum VIP client activates a deal. Fire-and-forget — never blocks checkout. Deduplicated once per customer per day.</div>
					</div>
					<div class="gt-form-group" style="margin-top:12px">
						<label class="gt-form-label">Human Handoff Webhook Secret (optional)</label>
						<input type="password" name="human_handoff_secret" class="gt-input"
							value="<?php echo esc_attr( get_option( 'gtbogo_human_handoff_webhook_secret', '' ) ); ?>"
							placeholder="HMAC secret for payload verification">
						<div class="gt-form-hint">Sent as X-GT-BOGO-Signature header. Verify in your endpoint to prevent spoofing.</div>
					</div>
		</div>
		<div class="gt-form-group" style="margin:0">
			<label class="gt-form-label">Notify on Events</label>
			<?php
			$slack_events = array(
				'deal_redeemed' => 'Deal Redeemed',
				'vip_tier_up'   => 'VIP Tier Upgrade',
				'revenue_guard' => 'Revenue Guard Triggered',
			);
			$slack_active = (array) ( $int['slack_events'] ?? array() );
			foreach ( $slack_events as $se_key => $se_label ) :
				?>
			<label style="display:flex;align-items:center;gap:6px;font-size:12px;color:var(--gt-white);margin-bottom:4px;cursor:pointer">
				<input type="checkbox" name="slack_events[]" value="<?php echo esc_attr( $se_key ); ?>"
						<?php checked( in_array( $se_key, $slack_active, true ) ); ?>
						style="accent-color:var(--gt-red)">
				<?php echo esc_html( $se_label ); ?>
			</label>
			<?php endforeach; ?>
		</div>
	</div>
</div>

<!-- ═══ REST API STATUS ══════════════════════════════════════════════════════ -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header">
		<h2 class="gt-card-title">🔧 GT BOGO REST API</h2>
		<div style="display:flex;align-items:center;gap:8px">
			<div style="width:7px;height:7px;border-radius:50%;background:<?php echo $rest_active ? '#22c55e' : '#64748b'; ?>;
						box-shadow:0 0 5px <?php echo $rest_active ? '#22c55e' : 'transparent'; ?>"></div>
			<span style="font-size:12px;color:var(--gt-subtle)"><?php echo $rest_active ? 'Active' : 'Not registered'; ?></span>
		</div>
	</div>
	<div style="font-size:12px;color:var(--gt-subtle);margin-bottom:12px;line-height:1.5">
		Base URL: <code style="background:rgba(255,255,255,0.05);padding:2px 8px;border-radius:4px;color:var(--gt-white)"><?php echo esc_html( $rest_url ); ?></code>
	</div>
	<?php
	$endpoints = array(
		array( 'GET', 'rules', 'List active rules' ),
		array( 'POST', 'rules', 'Create a rule' ),
		array( 'GET', 'customers/{id}', 'Get customer profile' ),
		array( 'GET', 'analytics', 'Revenue analytics summary' ),
		array( 'GET', 'health', 'Plugin health status' ),
	);
	?>
	<table style="width:100%;border-collapse:collapse;font-size:11px">
		<thead>
			<tr style="border-bottom:1px solid var(--gt-border)">
				<th style="padding:7px 12px;text-align:left;font-size:9px;font-weight:800;letter-spacing:.1em;text-transform:uppercase;color:var(--gt-subtle)">Method</th>
				<th style="padding:7px 12px;text-align:left;font-size:9px;font-weight:800;letter-spacing:.1em;text-transform:uppercase;color:var(--gt-subtle)">Endpoint</th>
				<th style="padding:7px 12px;text-align:left;font-size:9px;font-weight:800;letter-spacing:.1em;text-transform:uppercase;color:var(--gt-subtle)">Description</th>
			</tr>
		</thead>
		<tbody>
		<?php
		foreach ( $endpoints as $ep ) :
			$m_color = $ep[0] === 'GET' ? '#3b82f6' : ( $ep[0] === 'POST' ? '#22c55e' : '#f59e0b' );
			?>
		<tr style="border-bottom:1px solid rgba(255,255,255,0.03)">
			<td style="padding:7px 12px">
				<span style="padding:2px 7px;border-radius:4px;font-size:9px;font-weight:800;
							background:<?php echo esc_attr( $m_color ); ?>18;color:<?php echo esc_attr( $m_color ); ?>">
					<?php echo esc_html( $ep[0] ); ?>
				</span>
			</td>
			<td style="padding:7px 12px;font-family:'DM Mono','Courier New',monospace;color:var(--gt-white)">
				gtbogo/v1/<?php echo esc_html( $ep[1] ); ?>
			</td>
			<td style="padding:7px 12px;color:var(--gt-subtle)"><?php echo esc_html( $ep[2] ); ?></td>
		</tr>
		<?php endforeach; ?>
		</tbody>
	</table>
</div>

<!-- ═══ WEBHOOK DELIVERY LOG ════════════════════════════════════════════════ -->
	<?php if ( ! empty( $webhook_log ) ) : ?>
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header">
		<h2 class="gt-card-title">📋 Webhook Delivery Log</h2>
		<span style="font-size:12px;color:var(--gt-subtle)">Last 20 deliveries</span>
	</div>
	<div style="overflow-x:auto">
		<table style="width:100%;border-collapse:collapse;font-size:11px">
			<thead>
				<tr style="border-bottom:1px solid var(--gt-border)">
					<?php foreach ( array( 'Time', 'URL', 'Event', 'Status', 'Latency', 'Retries' ) as $col ) : ?>
					<th style="padding:8px 12px;text-align:left;font-size:9px;font-weight:800;letter-spacing:.1em;text-transform:uppercase;color:var(--gt-subtle)"><?php echo esc_html( $col ); ?></th>
					<?php endforeach; ?>
				</tr>
			</thead>
			<tbody>
			<?php
			foreach ( $webhook_log as $wl ) :
				$sc       = (int) ( $wl['response_code'] ?? 0 );
				$sc_color = ( $sc >= 200 && $sc < 300 ) ? '#22c55e' : ( $sc >= 400 ? '#ef4444' : '#f59e0b' );
				?>
			<tr style="border-bottom:1px solid rgba(255,255,255,0.03)">
				<td style="padding:7px 12px;color:var(--gt-subtle);font-size:10px;white-space:nowrap"><?php echo esc_html( $wl['sent_at'] ? gmdate( 'M j H:i', strtotime( $wl['sent_at'] ) ) : '—' ); ?></td>
				<td style="padding:7px 12px;color:var(--gt-subtle);font-size:10px;max-width:160px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap" title="<?php echo esc_attr( $wl['url'] ?? '' ); ?>"><?php echo esc_html( wp_parse_url( $wl['url'] ?? '', PHP_URL_HOST ) ?: '—' ); ?></td>
				<td style="padding:7px 12px;color:var(--gt-white);font-size:10px"><?php echo esc_html( $wl['event'] ?? '—' ); ?></td>
				<td style="padding:7px 12px"><span style="color:<?php echo esc_attr( $sc_color ); ?>;font-weight:700;font-size:10px"><?php echo esc_html( (string) $sc ?: '—' ); ?></span></td>
				<td style="padding:7px 12px;color:var(--gt-subtle);font-size:10px"><?php echo $wl['response_ms'] ? esc_html( $wl['response_ms'] . 'ms' ) : '—'; ?></td>
				<td style="padding:7px 12px;color:<?php echo (int) ( $wl['retry_count'] ?? 0 ) > 0 ? '#f59e0b' : 'var(--gt-subtle)'; ?>;font-size:10px"><?php echo esc_html( (string) (int) ( $wl['retry_count'] ?? 0 ) ); ?></td>
			</tr>
			<?php endforeach; ?>
			</tbody>
		</table>
	</div>
</div>
	<?php endif; ?>

<!-- ═══ MISSING INTEGRATION RECOMMENDATIONS ═════════════════════════════════ -->
	<?php
	$recommendations = array();
	if ( ! $has_mailchimp && ! $has_klaviyo ) {
		$recommendations[] = array( 'Mailchimp or Klaviyo', 'Send automatic loyalty and BOGO emails via your ESP. GT BOGO Engine can tag redeemers and fire events.' );
	}
	if ( ! $has_subscriptions ) {
		$recommendations[] = array( 'WooCommerce Subscriptions', 'Unlock subscription intelligence — recurring LTV scoring, churn prediction, and subscriber-specific deals.' );
	}
	if ( ! $redis_ok ) {
		$recommendations[] = array( 'Redis Object Cache', 'Enable Redis to dramatically reduce DB load. GT BOGO Engine uses object cache heavily for signal bus and rule evaluation.' );
	}
	?>
	<?php if ( ! empty( $recommendations ) ) : ?>
<div class="gt-card gt-animate-in" style="margin-bottom:20px;border-color:rgba(59,130,246,0.15)">
	<div class="gt-card-header"><h2 class="gt-card-title">💡 Recommended Integrations</h2></div>
		<?php foreach ( $recommendations as $rec ) : ?>
	<div style="display:flex;align-items:flex-start;gap:12px;padding:12px 0;border-bottom:1px solid rgba(255,255,255,0.04)">
		<span style="font-size:16px">💡</span>
		<div>
			<div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:3px"><?php echo esc_html( $rec[0] ); ?></div>
			<div style="font-size:12px;color:var(--gt-subtle);line-height:1.5"><?php echo esc_html( $rec[1] ); ?></div>
		</div>
	</div>
	<?php endforeach; ?>
</div>
<?php endif; ?>

<!-- Save -->
<div class="gt-card gt-animate-in">
	<div style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:16px">
		<div style="font-size:13px;color:var(--gt-subtle)">Integration settings apply to new events only — existing records are not affected.</div>
		<button type="submit" name="gtbogo_save_integrations" class="gt-btn gt-btn-primary" style="padding:12px 32px">
			💾 Save Integrations
		</button>
	</div>
</div>

</form>
<?php endif; // is_pro ?>

<script>
(function(){
window.gtIntTestEmail = function(nonce) {
	var fd = new FormData(); fd.append('action','gtbogo_test_integrations'); fd.append('nonce',nonce); fd.append('type','email');
	fetch(ajaxurl,{method:'POST',body:fd}).then(function(r){return r.json();}).then(function(resp){
		alert(resp.success ? '✓ '+resp.data : '✗ '+(resp.data||'Test failed'));
	});
};
window.gtIntTestWebhook = function(nonce) {
	var fd = new FormData(); fd.append('action','gtbogo_test_integrations'); fd.append('nonce',nonce); fd.append('type','webhook');
	fetch(ajaxurl,{method:'POST',body:fd}).then(function(r){return r.json();}).then(function(resp){
		alert(resp.success ? '✓ Webhook delivered ('+resp.data.latency+'ms)' : '✗ '+(resp.data||'Test failed'));
	});
};
})();
</script>

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