<?php

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

use SplitPay\Core\IntegrationRegistry;
use SplitPay\Core\ConnectedAccounts;
use SplitPay\Core\UpgradeCTA;

$registry     = IntegrationRegistry::getInstance();
$integrations = $registry->getAll();
$accounts     = new ConnectedAccounts();
$total_accounts = count( $accounts->getStoredAccounts() );

$manage_stripe_urls = [
	'wc_stripe'                 => admin_url( 'admin.php?page=wc-settings&tab=checkout&section=stripe&panel=settings' ),
	'wc_stripe_payment_plugins' => admin_url( 'admin.php?page=wc-settings&tab=checkout&section=stripe_api' ),
	'fluentcart_stripe'         => admin_url( 'admin.php?page=fluent-cart#/settings/payments/stripe' ),
];

?>
<style>
.spp-integrations-wrap { max-width: 900px; margin-top: 20px; }
.spp-integrations-wrap .spp-integrations-summary { background: #fff; border: 1px solid #c3c4c7; border-radius: 4px; padding: 20px 24px; margin-bottom: 20px; }
.spp-integrations-wrap .spp-integrations-summary h3 { margin: 0 0 8px; font-size: 15px; color: #1d2327; }
.spp-integrations-wrap .spp-integrations-summary p { margin: 4px 0; color: #50575e; font-size: 13px; padding-left: 0; }
.spp-integrations-wrap .spp-integrations-summary a { display: inline-block; margin-top: 10px; text-decoration: none; font-weight: 500; }
.spp-integrations-wrap .spp-pro-banner { background: linear-gradient(135deg, #f0f0f1 0%, #e8edf3 100%); border: 1px solid #c3c4c7; border-left: 4px solid #2271b1; border-radius: 4px; padding: 16px 24px; margin-bottom: 20px; display: flex; align-items: center; justify-content: space-between; }
.spp-integrations-wrap .spp-pro-banner p { margin: 0; color: #1d2327; font-size: 13px; padding-left: 0; }
.spp-integrations-wrap .spp-integration-cards { display: flex; flex-direction: column; gap: 16px; }
.spp-integrations-wrap .spp-integration-card { background: #fff; border: 1px solid #c3c4c7; border-radius: 4px; padding: 20px 24px; }
.spp-integrations-wrap .spp-card-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 8px; }
.spp-integrations-wrap .spp-card-header h3 { margin: 0; font-size: 15px; color: #1d2327; }
.spp-integrations-wrap .spp-badge { display: inline-block; padding: 2px 10px; border-radius: 12px; font-size: 12px; font-weight: 500; line-height: 1.6; }
.spp-integrations-wrap .spp-badge-active { background: #d4edda; color: #155724; }
.spp-integrations-wrap .spp-badge-inactive { background: #e2e4e7; color: #50575e; }
.spp-integrations-wrap .spp-badge-not-found { background: #f8d7da; color: #721c24; }
.spp-integrations-wrap .spp-card-description { margin: 0 0 8px; color: #50575e; font-size: 13px; padding-left: 0; }
.spp-integrations-wrap .spp-card-version { margin: 0 0 14px; color: #646970; font-size: 12px; padding-left: 0; }
.spp-integrations-wrap .spp-gateway-cards { margin: 14px 0; display: flex; flex-direction: column; gap: 10px; }
.spp-integrations-wrap .spp-gateway-card { background: #f6f7f7; border: 1px solid #dcdcde; border-radius: 4px; padding: 14px 18px; }
.spp-integrations-wrap .spp-gateway-card h4 { margin: 0 0 8px; font-size: 13px; color: #1d2327; }
.spp-integrations-wrap .spp-gateway-details { display: flex; flex-wrap: wrap; gap: 16px; margin-bottom: 10px; }
.spp-integrations-wrap .spp-gateway-details span { font-size: 12px; color: #50575e; }
.spp-integrations-wrap .spp-gateway-actions { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; }
.spp-integrations-wrap .spp-gateway-actions .button { font-size: 12px; }
.spp-integrations-wrap .spp-sync-status { font-size: 12px; margin-left: 4px; }
.spp-integrations-wrap .spp-card-actions { margin-top: 14px; display: flex; gap: 8px; }
.spp-integrations-wrap .spp-settings-overlay { display: none; margin-top: 12px; padding: 14px 18px; background: #fff; border: 1px solid #c3c4c7; border-radius: 4px; }
.spp-integrations-wrap .spp-settings-overlay.spp-open { display: block; }
.spp-integrations-wrap .spp-settings-overlay h5 { margin: 0 0 10px; font-size: 13px; }
.spp-integrations-wrap .spp-settings-overlay .spp-setting-row { display: flex; align-items: center; gap: 10px; margin-bottom: 8px; font-size: 12px; color: #50575e; }
.spp-integrations-wrap .spp-settings-overlay .spp-setting-row strong { min-width: 100px; }
.spp-integrations-wrap .spp-settings-overlay .spp-overlay-actions { display: flex; gap: 6px; margin-top: 12px; }
</style>

<div class="spp-integrations-wrap">

	<div class="spp-integrations-summary">
		<h3><?php esc_html_e( 'Connected Accounts', 'bsd-split-pay-stripe-connect-woo' ); ?></h3>
		<p>
			<?php
			printf(
				/* translators: %d = number of synced Stripe accounts. */
				esc_html__( '%d synced Stripe accounts', 'bsd-split-pay-stripe-connect-woo' ),
				(int) $total_accounts
			);
			?>
		</p>
		<?php if ( ! empty( $integrations ) ) : ?>
			<p>
				<?php
				global $wpdb;
				$parts = [];
				foreach ( $integrations as $integration ) {
					$int_id = $integration->getId();
					if ( $int_id === 'woocommerce' ) {
						$simple_count = (int) $wpdb->get_var(
							"SELECT COUNT( DISTINCT p.ID ) FROM {$wpdb->posts} p
							INNER JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id
							WHERE p.post_type = 'product' AND p.post_status = 'publish'
							AND pm.meta_key = '_bsd_spscwt_product_connected_account'
							AND pm.meta_value != '' AND pm.meta_value != 'a:0:{}'"
						);
						$variable_count = (int) $wpdb->get_var(
							"SELECT COUNT( DISTINCT p.post_parent ) FROM {$wpdb->posts} p
							INNER JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id
							WHERE p.post_type = 'product_variation'
							AND pm.meta_key = '_bsd_spscwt_product_connected_account'
							AND pm.meta_value != '' AND pm.meta_value != 'a:0:{}'"
						);
						$count = $simple_count + $variable_count;
					} elseif ( $int_id === 'fluentcart' ) {
						$from_postmeta = (int) $wpdb->get_var(
							"SELECT COUNT( DISTINCT p.ID ) FROM {$wpdb->posts} p
							INNER JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id
							WHERE p.post_type = 'fluent-products' AND p.post_status = 'publish'
							AND pm.meta_key = '_bsd_spscwt_product_connected_account'
							AND pm.meta_value != '' AND pm.meta_value != 'a:0:{}'"
						);
						$from_native = 0;
						if ( $wpdb->get_var( "SHOW TABLES LIKE '{$wpdb->prefix}fct_product_meta'" ) ) {
						$from_native = (int) $wpdb->get_var(
							"SELECT COUNT( DISTINCT object_id ) FROM {$wpdb->prefix}fct_product_meta
							WHERE meta_key = 'split_pay_connect' AND meta_value != ''"
						);
						}
						$count = max( $from_postmeta, $from_native );
					} else {
						$count = 0;
					}
					$parts[] = esc_html( $integration->getName() ) . ': ' . (int) $count
						. ' ' . esc_html__( 'products configured', 'bsd-split-pay-stripe-connect-woo' );
				}
				echo wp_kses_post( implode( ' &nbsp;|&nbsp; ', $parts ) );
				?>
			</p>
		<?php endif; ?>
		<a href="<?php echo esc_url( admin_url( 'admin.php?page=bsd-split-pay-stripe-connect-woo-settings&tab=main' ) ); ?>">
			<?php esc_html_e( 'Manage Transfer Settings', 'bsd-split-pay-stripe-connect-woo' ); ?> &rarr;
		</a>
	</div>

	<?php
	$platformIds = [];
	foreach ( $integrations as $int ) {
		if ( ! $int->isActive() ) {
			continue;
		}
		foreach ( $int->getGatewayAdapters() as $gw ) {
			if ( ! $gw->isActive() ) {
				continue;
			}
			try {
				$pid = $gw->getPlatformAccountId();
				if ( ! empty( $pid ) ) {
					$platformIds[ $gw->getName() ] = $pid;
				}
			} catch ( \Throwable $e ) {
				// Skip
			}
		}
	}
	$uniquePlatforms = array_unique( array_values( $platformIds ) );
	if ( count( $uniquePlatforms ) > 1 ) : ?>
		<div class="notice notice-warning" style="margin: 0 0 16px; padding: 12px 16px;">
			<p><strong><?php esc_html_e( 'Platform Account Notice', 'bsd-split-pay-stripe-connect-woo' ); ?></strong></p>
			<p><?php esc_html_e( 'Your payment gateways are connected to different Stripe platform accounts. Transfers will only succeed when the connected account belongs to the same Stripe platform that processed the payment.', 'bsd-split-pay-stripe-connect-woo' ); ?></p>
			<ul style="margin: 8px 0 0 16px; list-style: disc;">
				<?php foreach ( $platformIds as $gwName => $pid ) : ?>
					<li><?php echo esc_html( $gwName . ': ' . $pid ); ?></li>
				<?php endforeach; ?>
			</ul>
		</div>
	<?php endif; ?>

	<?php // PRO banner moved to Global Transfer Settings tab ?>

	<?php if ( ! empty( $integrations ) ) : ?>
		<div class="spp-integration-cards">
			<?php foreach ( $integrations as $integration ) :
				$is_active    = $integration->isActive();
				$is_installed = $integration->isInstalled();

				if ( $is_active ) {
					$badge_class = 'spp-badge-active';
					$badge_label = __( 'Active', 'bsd-split-pay-stripe-connect-woo' );
				} elseif ( $is_installed ) {
					$badge_class = 'spp-badge-inactive';
					$badge_label = __( 'Inactive', 'bsd-split-pay-stripe-connect-woo' );
				} else {
					$badge_class = 'spp-badge-not-found';
					$badge_label = __( 'Not Found', 'bsd-split-pay-stripe-connect-woo' );
				}

				$gateways   = method_exists( $integration, 'getAllGatewayCandidates' )
					? $integration->getAllGatewayCandidates()
					: $integration->getGatewayAdapters();
				$plugin_url = $integration->getPluginUrl();
			?>
				<div class="spp-integration-card">
					<div class="spp-card-header">
						<h3><?php echo esc_html( $integration->getName() ); ?></h3>
						<span class="spp-badge <?php echo esc_attr( $badge_class ); ?>"><?php echo esc_html( $badge_label ); ?></span>
					</div>
					<p class="spp-card-description"><?php echo esc_html( $integration->getDescription() ); ?></p>
					<p class="spp-card-version">
						<?php /* translators: %s = integration version string. */ printf( esc_html__( 'Version: %s', 'bsd-split-pay-stripe-connect-woo' ), esc_html( $integration->getVersion() ) ); ?>
					</p>

					<?php if ( ! empty( $gateways ) ) : ?>
						<div class="spp-gateway-cards">
							<?php foreach ( $gateways as $gateway ) :
								$gw_id      = $gateway->getId();
								$gw_active  = $gateway->isActive();
								$secret_key = $gw_active ? $gateway->getSecretKey() : '';
								$manage_url = $manage_stripe_urls[ $gw_id ] ?? '';

								if ( $gw_active ) {
									$gw_status_label = __( 'Active', 'bsd-split-pay-stripe-connect-woo' );
									$gw_mode         = $gateway->isTestMode() ? __( 'Test', 'bsd-split-pay-stripe-connect-woo' ) : __( 'Live', 'bsd-split-pay-stripe-connect-woo' );
								} else {
									$gw_status_label = __( 'Not Installed', 'bsd-split-pay-stripe-connect-woo' );
									$gw_mode         = '';
								}

								if ( ! empty( $secret_key ) && strlen( $secret_key ) > 4 ) {
									$masked_key = '••••' . substr( $secret_key, -4 );
								} elseif ( ! empty( $secret_key ) ) {
									$masked_key = '••••';
								} else {
									$masked_key = $gw_active ? __( 'Not configured', 'bsd-split-pay-stripe-connect-woo' ) : '—';
								}

								$overlay_id = 'spp-overlay-' . esc_attr( $gw_id );
							?>
								<div class="spp-gateway-card" <?php echo ! $gw_active ? 'style="filter:grayscale(1);"' : ''; ?>><?php /* 3.7.5 a11y (WCAG 2.1 AA 1.4.3): inactive gateway cards use grayscale, not opacity:0.7, so the status/API-key text keeps its contrast. */ ?>
									<h4><?php echo esc_html( $gateway->getName() ); ?></h4>
									<div class="spp-gateway-details">
										<span><?php /* translators: %s = gateway status label. */ printf( esc_html__( 'Status: %s', 'bsd-split-pay-stripe-connect-woo' ), esc_html( $gw_status_label ) ); ?></span>
										<?php if ( ! empty( $gw_mode ) ) : ?>
											<span><?php /* translators: %s = gateway mode (test or live). */ printf( esc_html__( 'Mode: %s', 'bsd-split-pay-stripe-connect-woo' ), esc_html( $gw_mode ) ); ?></span>
										<?php endif; ?>
										<span><?php /* translators: %s = masked API key. */ printf( esc_html__( 'API Key: %s', 'bsd-split-pay-stripe-connect-woo' ), esc_html( $masked_key ) ); ?></span>
									</div>
									<div class="spp-gateway-actions">
										<?php if ( $gw_active ) : ?>
											<button type="button" class="button spp-toggle-settings-btn" data-target="<?php echo esc_attr( $overlay_id ); ?>">
												<?php esc_html_e( 'Settings', 'bsd-split-pay-stripe-connect-woo' ); ?>
											</button>
											<?php if ( ! empty( $manage_url ) ) : ?>
												<a href="<?php echo esc_url( $manage_url ); ?>" class="button"><?php esc_html_e( 'Manage Stripe', 'bsd-split-pay-stripe-connect-woo' ); ?></a>
											<?php endif; ?>
											<button type="button" class="button spp-sync-webhook-btn"
													data-gateway="<?php echo esc_attr( $gw_id ); ?>"
													data-nonce="<?php echo esc_attr( wp_create_nonce( 'spp_sync_webhook' ) ); ?>">
												<?php esc_html_e( 'Sync Webhooks', 'bsd-split-pay-stripe-connect-woo' ); ?>
											</button>
											<span class="spp-sync-status" role="status" aria-live="polite"></span>
										<?php else : ?>
											<?php if ( ! empty( $manage_url ) ) : ?>
												<a href="<?php echo esc_url( $manage_url ); ?>" class="button"><?php esc_html_e( 'Install Plugin', 'bsd-split-pay-stripe-connect-woo' ); ?></a>
											<?php endif; ?>
										<?php endif; ?>
									</div>

									<?php if ( $gw_active ) :
								$_ao_key_map = [
									'wc_stripe'                 => [ 'spp_wc_stripe_test_secret_key', 'spp_wc_stripe_live_secret_key', 'stripe_test_api_secret_key', 'stripe_api_secret_key' ],
									'wc_stripe_payment_plugins' => [ 'spp_pp_stripe_test_secret_key', 'spp_pp_stripe_live_secret_key' ],
									'fluentcart_stripe'         => [ 'spp_fc_stripe_test_secret_key', 'spp_fc_stripe_live_secret_key' ],
								];
								$auto_open = false;
								if ( isset( $_ao_key_map[ $gw_id ] ) ) {
									$_ao = $_ao_key_map[ $gw_id ];
									$_ao_test = get_option( $_ao[0], '' );
									$_ao_live = get_option( $_ao[1], '' );
									if ( empty( $_ao_test ) && isset( $_ao[2] ) ) {
										$_ao_test = get_option( $_ao[2], '' );
									}
									if ( empty( $_ao_live ) && isset( $_ao[3] ) ) {
										$_ao_live = get_option( $_ao[3], '' );
									}
									$auto_open = empty( $_ao_test ) || empty( $_ao_live );
								}
								?>
								<div id="<?php echo esc_attr( $overlay_id ); ?>" class="spp-settings-overlay<?php echo $auto_open ? ' spp-open' : ''; ?>">
										<h5><?php echo esc_html( $gateway->getName() ); ?> &mdash; <?php esc_html_e( 'Settings', 'bsd-split-pay-stripe-connect-woo' ); ?></h5>
										<div class="spp-setting-row">
											<strong><?php esc_html_e( 'Gateway Key:', 'bsd-split-pay-stripe-connect-woo' ); ?></strong>
											<span><?php echo esc_html( $masked_key ); ?> <em style="color:#646970;">(<?php esc_html_e( 'read from plugin', 'bsd-split-pay-stripe-connect-woo' ); ?>)</em></span>
										</div>
										<div class="spp-setting-row">
											<strong><?php esc_html_e( 'Mode:', 'bsd-split-pay-stripe-connect-woo' ); ?></strong>
											<span><?php echo esc_html( $gw_mode ); ?></span>
										</div>
										<?php
										$spp_key_options = [
											'wc_stripe'                 => [ 'spp_wc_stripe_test_secret_key', 'spp_wc_stripe_live_secret_key' ],
											'wc_stripe_payment_plugins' => [ 'spp_pp_stripe_test_secret_key', 'spp_pp_stripe_live_secret_key' ],
											'fluentcart_stripe'         => [ 'spp_fc_stripe_test_secret_key', 'spp_fc_stripe_live_secret_key' ],
										];
										if ( isset( $spp_key_options[ $gw_id ] ) ) :
											$pk_test_opt = $spp_key_options[ $gw_id ][0];
											$pk_live_opt = $spp_key_options[ $gw_id ][1];
											$pk_test_key = get_option( $pk_test_opt, '' );
											$pk_live_key = get_option( $pk_live_opt, '' );

											if ( $gw_id === 'wc_stripe' && empty( $pk_test_key ) ) {
												$pk_test_key = get_option( 'stripe_test_api_secret_key', '' );
											}
											if ( $gw_id === 'wc_stripe' && empty( $pk_live_key ) ) {
												$pk_live_key = get_option( 'stripe_api_secret_key', '' );
											}

											$pk_is_test = $gateway->isTestMode();

											$pk_test_masked = ( ! empty( $pk_test_key ) && strlen( $pk_test_key ) > 8 )
												? substr( $pk_test_key, 0, 7 ) . '••••' . substr( $pk_test_key, -4 ) : '';
											$pk_live_masked = ( ! empty( $pk_live_key ) && strlen( $pk_live_key ) > 8 )
												? substr( $pk_live_key, 0, 7 ) . '••••' . substr( $pk_live_key, -4 ) : '';
										?>
										<?php
										/*
										 * 3.7.5 (sc-7242): only show the "Platform Secret Key Required" warning
										 * when the key for the CURRENT mode (test or live) is actually missing.
										 * Previously this notice rendered unconditionally — customers (e.g.
										 * Margaret Winans on flameoflove.us) saw it even after saving their keys,
										 * which made it look like nothing they did was working.
										 */
										$pk_current_mode_key = $pk_is_test ? $pk_test_key : $pk_live_key;
										$pk_show_warning     = empty( $pk_current_mode_key );
										if ( $pk_show_warning ) :
										?>
										<div style="margin-top:8px;padding:10px 14px;background:#fff3cd;border:1px solid #ffc107;border-radius:4px;">
											<strong style="color:#856404;"><?php esc_html_e( 'Platform Secret Key Required', 'bsd-split-pay-stripe-connect-woo' ); ?></strong>
											<p style="margin:4px 0 0;font-size:12px;color:#856404;">
												<?php
												printf(
													/* translators: %s is "test" or "live" — describes which mode's key is missing */
													esc_html__( 'Enter your Stripe platform %s secret key (from Stripe Dashboard > Developers > API keys) to enable transfers, webhook syncing, and connected account management for this gateway.', 'bsd-split-pay-stripe-connect-woo' ),
													$pk_is_test ? esc_html__( 'test', 'bsd-split-pay-stripe-connect-woo' ) : esc_html__( 'live', 'bsd-split-pay-stripe-connect-woo' )
												);
												?>
											</p>
										</div>
										<?php endif; ?>
										<div class="spp-setting-row" style="flex-direction:column;align-items:flex-start;gap:8px;margin-top:10px;">
											<div class="spp-key-field-group" style="width:100%;">
												<label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">
													<?php esc_html_e( 'Test Mode Secret Key:', 'bsd-split-pay-stripe-connect-woo' ); ?>
													<?php if ( ! empty( $pk_test_key ) ) : ?><span style="background:#d4edda;color:#155724;padding:1px 6px;border-radius:3px;font-size:10px;font-weight:500;margin-left:4px;"><?php esc_html_e( 'ACTIVE', 'bsd-split-pay-stripe-connect-woo' ); ?></span><?php endif; ?>
													<?php if ( $pk_is_test ) : ?><span style="background:#cce5ff;color:#004085;padding:1px 6px;border-radius:3px;font-size:10px;font-weight:500;margin-left:4px;"><?php esc_html_e( 'CURRENT MODE', 'bsd-split-pay-stripe-connect-woo' ); ?></span><?php endif; ?>
												</label>
												<?php if ( ! empty( $pk_test_masked ) ) : ?>
													<span style="font-size:11px;color:#50575e;"><?php echo esc_html( $pk_test_masked ); ?></span><br>
												<?php endif; ?>
												<input type="text" class="spp-platform-key-input" autocomplete="off" style="width:100%;max-width:400px;font-size:12px;margin-top:2px;"
													   data-option="<?php echo esc_attr( $pk_test_opt ); ?>"
													   placeholder="sk_test_..." value="" />
												<button type="button" class="button button-small spp-save-platform-key-btn" style="margin-top:4px;"
														data-nonce="<?php echo esc_attr( wp_create_nonce( 'spp_save_platform_key' ) ); ?>">
													<?php esc_html_e( 'Save Test Key', 'bsd-split-pay-stripe-connect-woo' ); ?>
												</button>
												<span class="spp-key-status" role="status" aria-live="polite" style="font-size:12px;margin-left:6px;"></span>
											</div>
											<div class="spp-key-field-group" style="width:100%;margin-top:6px;">
												<label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">
													<?php esc_html_e( 'Live Mode Secret Key:', 'bsd-split-pay-stripe-connect-woo' ); ?>
													<?php if ( ! empty( $pk_live_key ) ) : ?><span style="background:#d4edda;color:#155724;padding:1px 6px;border-radius:3px;font-size:10px;font-weight:500;margin-left:4px;"><?php esc_html_e( 'ACTIVE', 'bsd-split-pay-stripe-connect-woo' ); ?></span><?php endif; ?>
													<?php if ( ! $pk_is_test ) : ?><span style="background:#cce5ff;color:#004085;padding:1px 6px;border-radius:3px;font-size:10px;font-weight:500;margin-left:4px;"><?php esc_html_e( 'CURRENT MODE', 'bsd-split-pay-stripe-connect-woo' ); ?></span><?php endif; ?>
												</label>
												<?php if ( ! empty( $pk_live_masked ) ) : ?>
													<span style="font-size:11px;color:#50575e;"><?php echo esc_html( $pk_live_masked ); ?></span><br>
												<?php endif; ?>
												<input type="text" class="spp-platform-key-input" autocomplete="off" style="width:100%;max-width:400px;font-size:12px;margin-top:2px;"
													   data-option="<?php echo esc_attr( $pk_live_opt ); ?>"
													   placeholder="sk_live_..." value="" />
												<button type="button" class="button button-small spp-save-platform-key-btn" style="margin-top:4px;"
														data-nonce="<?php echo esc_attr( wp_create_nonce( 'spp_save_platform_key' ) ); ?>">
													<?php esc_html_e( 'Save Live Key', 'bsd-split-pay-stripe-connect-woo' ); ?>
												</button>
												<span class="spp-key-status" role="status" aria-live="polite" style="font-size:12px;margin-left:6px;"></span>
											</div>
										</div>
										<?php endif; ?>
										<div class="spp-overlay-actions">
											<button type="button" class="button spp-sync-accounts-btn"
													data-gateway="<?php echo esc_attr( $gw_id ); ?>"
													data-nonce="<?php echo esc_attr( wp_create_nonce( 'spp_sync_accounts' ) ); ?>">
												<?php esc_html_e( 'Sync Connected Accounts', 'bsd-split-pay-stripe-connect-woo' ); ?>
											</button>
											<button type="button" class="button spp-clear-accounts-btn"
													data-nonce="<?php echo esc_attr( wp_create_nonce( 'spp_clear_accounts' ) ); ?>">
												<?php esc_html_e( 'Clear Synced Accounts', 'bsd-split-pay-stripe-connect-woo' ); ?>
											</button>
											<span class="spp-accounts-status" role="status" aria-live="polite"></span>
										</div>
									</div>
								<?php endif; ?>
								</div>
							<?php endforeach; ?>
						</div>
					<?php endif; ?>

					<div class="spp-card-actions">
						<?php if ( ! empty( $plugin_url ) ) : ?>
							<a href="<?php echo esc_url( $plugin_url ); ?>" class="button" target="_blank" rel="noopener noreferrer">
								<?php esc_html_e( 'View Docs', 'bsd-split-pay-stripe-connect-woo' ); ?>
							</a>
						<?php endif; ?>
					</div>
				</div>
			<?php endforeach; ?>
		</div>
	<?php else : ?>
		<div style="background:#fff;border:1px solid #c3c4c7;border-radius:4px;padding:40px 24px;text-align:center;color:#50575e;">
			<p><?php esc_html_e( 'No integrations registered yet.', 'bsd-split-pay-stripe-connect-woo' ); ?></p>
		</div>
	<?php endif; ?>

</div>
<script>
jQuery(document).ready(function($) {
	$('.spp-toggle-settings-btn').on('click', function() {
		var target = $(this).data('target');
		$('#' + target).toggleClass('spp-open');
	});

	$('.spp-sync-webhook-btn').on('click', function() {
		var btn = $(this);
		var status = btn.siblings('.spp-sync-status');
		btn.prop('disabled', true);
		status.text('Syncing...').css('color', '');
		$.post(ajaxurl, {
			action: 'spp_sync_gateway_webhooks',
			gateway_id: btn.data('gateway'),
			_wpnonce: btn.data('nonce')
		}, function(r) {
			btn.prop('disabled', false);
			status.text(r.success ? (r.data.message || 'Done') : (r.data.message || 'Failed'))
				  .css('color', r.success ? '#46b450' : '#dc3232');
		}).fail(function() {
			btn.prop('disabled', false);
			status.text('Request failed.').css('color', '#dc3232');
		});
	});

	$('.spp-sync-accounts-btn').on('click', function() {
		var btn = $(this);
		var status = btn.siblings('.spp-accounts-status');
		btn.prop('disabled', true);
		status.text('Syncing accounts...').css('color', '');
		$.post(ajaxurl, {
			action: 'spp_sync_gateway_accounts',
			gateway_id: btn.data('gateway'),
			_wpnonce: btn.data('nonce')
		}, function(r) {
			btn.prop('disabled', false);
			status.text(r.success ? (r.data.message || 'Done') : (r.data.message || 'Failed'))
				  .css('color', r.success ? '#46b450' : '#dc3232');
		}).fail(function() {
			btn.prop('disabled', false);
			status.text('Request failed.').css('color', '#dc3232');
		});
	});

	$('.spp-clear-accounts-btn').on('click', function() {
		if (!confirm('Clear all synced accounts? This will not remove transfer settings.')) return;
		var btn = $(this);
		var status = btn.siblings('.spp-accounts-status');
		btn.prop('disabled', true);
		status.text('Clearing...').css('color', '');
		$.post(ajaxurl, {
			action: 'clear_accounts',
			_wpnonce: btn.data('nonce')
		}, function(r) {
			btn.prop('disabled', false);
			status.text('Accounts cleared.').css('color', '#46b450');
			setTimeout(function() { location.reload(); }, 1000);
		}).fail(function() {
			btn.prop('disabled', false);
			status.text('Request failed.').css('color', '#dc3232');
		});
	});

	$('.spp-save-platform-key-btn').on('click', function() {
		var btn = $(this);
		// 3.7.5 (PT-8) — scope to the immediate field-group wrapper so the
		// Save Live button doesn't read the (empty) Test input. Before PT-8 the
		// selector was '.spp-setting-row' which contains BOTH test + live
		// groups; jQuery .val() then returned the first input's empty value
		// and the click bounced with "Enter a key first."
		var wrap = btn.closest('.spp-key-field-group');
		var input = wrap.find('.spp-platform-key-input');
		var status = wrap.find('.spp-key-status');
		var key = input.val().trim();
		var option = input.data('option');
		if (!key) { status.text('Enter a key first.').css('color', '#dc3232'); return; }
		btn.prop('disabled', true);
		status.text('Saving...').css('color', '');
		$.post(ajaxurl, {
			action: 'spp_save_gateway_key',
			option_name: option,
			key_value: key,
			_wpnonce: '<?php echo esc_js( wp_create_nonce( "spp_save_gateway_key" ) ); ?>'
		}, function(r) {
			btn.prop('disabled', false);
			input.val('');
			if (r.success) {
				status.text(r.data.message || 'Saved!').css('color', '#46b450');
				setTimeout(function() { location.reload(); }, 1000);
			} else {
				status.text(r.data.message || 'Failed.').css('color', '#dc3232');
			}
		}).fail(function() {
			btn.prop('disabled', false);
			status.text('Request failed.').css('color', '#dc3232');
		});
	});
});
</script>
