<?php
/**
 * PeachPay Stripe Connect template.
 *
 * @package PeachPay
 */

defined( 'PEACHPAY_ABSPATH' ) || exit;

$is_test_mode       = peachpay_is_test_mode();
$is_configured      = PeachPay_Stripe_Credentials::is_configured();
$account            = PeachPay_Stripe_Credentials::get_account();
$webhook_url        = get_rest_url( null, 'peachpay/v1/stripe/webhook' );
$mode               = $is_test_mode ? 'test' : 'live';
$existing_pk        = PeachPay_Stripe_Credentials::get_publishable_key( $mode );
$existing_sk        = PeachPay_Stripe_Credentials::get_secret_key( $mode );
$existing_webhook   = PeachPay_Stripe_Credentials::get_webhook_secret();

?>
<div class="flex-col payment-provider-header <?php echo esc_attr( $is_configured ? 'is-connected' : '' ); ?>">
	<div>
		<div class="flex-col gap-24 w-100">
			<div class="flex-row gap-12 ai-center provider-title">
				<img src="<?php echo esc_attr( peachpay_url( 'public/img/marks/stripe/short-color.svg' ) ); ?>" />
				<?php echo esc_html_e( 'Stripe Account', 'peachpay-for-woocommerce' ); ?>
			</div>
			<!-- Stripe Status -->
			<?php if ( $is_configured ) : ?>
				<div class="flex-col gap-12 connected-info">
					<div class="flex-row gap-8 ai-center connected-success">
						<?php if ( $is_test_mode ) : ?>
							<?php echo esc_html_e( 'Your Stripe test account is connected!', 'peachpay-for-woocommerce' ); ?>
						<?php else : ?>
							<?php echo esc_html_e( 'Your Stripe account is connected!', 'peachpay-for-woocommerce' ); ?>
						<?php endif; ?>
						<img src="<?php echo esc_attr( peachpay_url( 'public/img/checkmark-green.svg' ) ); ?>"/>
					</div>
					<div class="flex-col gap-4">
						<?php if ( $is_test_mode ) : ?>
							<span class="account-info">
								<?php esc_html_e( 'Make test payments following', 'peachpay-for-woocommerce' ); ?>
								<a href="https://stripe.com/docs/testing" target="_blank"><?php esc_html_e( 'these instructions', 'peachpay-for-woocommerce' ); ?></a>.
							</span>
						<?php endif; ?>
						<?php if ( ! empty( $account['id'] ) ) : ?>
							<span class="account-info">
								<?php esc_html_e( 'Account Id:', 'peachpay-for-woocommerce' ); ?>
								<a href="https://dashboard.stripe.com/<?php echo $is_test_mode ? 'test/' : ''; ?>dashboard" target="_blank">
									<?php echo esc_html( $account['id'] ); ?>
								</a>
							</span>
						<?php endif; ?>
						<?php if ( ! empty( $account['email'] ) ) : ?>
							<span class="account-info">
								<?php esc_html_e( 'Email:', 'peachpay-for-woocommerce' ); ?> <?php echo esc_html( $account['email'] ); ?>
							</span>
						<?php endif; ?>
						<?php if ( ! empty( $account['country'] ) ) : ?>
							<span class="account-info">
								<?php esc_html_e( 'Country:', 'peachpay-for-woocommerce' ); ?> <?php echo esc_html( $account['country'] ); ?>
							</span>
						<?php endif; ?>
					</div>
				</div>
			<?php else : ?>
				<div class="flex-col provider-description">
					<p><?php esc_html_e( 'Stripe will give you the largest selection of global payment methods along with Apple Pay and Google Pay.', 'peachpay-for-woocommerce' ); ?></p>
					<div class="method-icons">
						<?php
						foreach ( PeachPay_Stripe_Integration::get_payment_gateways() as $gateway ) {
							$icon = $gateway->get_icon_url( 'small', 'color' );
							?>
							<span class="flex-row">
								<img src="<?php echo esc_attr( $icon ); ?>" alt="<?php echo esc_attr( $gateway->title ); ?>"/>
								<span class="gateway-title">
									<span><?php echo esc_attr( $gateway->title ); ?></span>
									<span>,</span>
								</span>
							</span>
							<?php
						}
						?>
					</div>
				</div>
			<?php endif; ?>
		</div>
		<div class="flex-col gap-12 ai-center buttons-container">
			<!-- Stripe Connect / Unlink buttons -->
			<?php if ( $is_configured ) : ?>
				<a class="update-payment-button button-primary-filled-medium" href="<?php echo esc_url( PeachPay_Stripe_Advanced::get_url() ); ?>">
					<?php esc_html_e( 'Advanced settings', 'peachpay-for-woocommerce' ); ?>
				</a>
				<a class="unlink-payment-button button-error-outlined-medium" href="#" id="pp-stripe-disconnect-btn">
					<?php
					esc_html_e( 'Unlink Stripe', 'peachpay-for-woocommerce' );
					?>
				</a>
			<?php else : ?>
				<a class="connect-payment-button button-primary-filled-medium" href="#" onclick="document.querySelector('#stripe_signup').classList.add('open'); return false;">
					<?php
					esc_html_e( 'Connect Stripe', 'peachpay-for-woocommerce' );
					?>
				</a>
			<?php endif; ?>
		</div>
	</div>

	<!-- Stripe Connect Modal -->
	<div id="stripe_signup" class="modal-window">
		<a href="#" class="outside-close" onclick="document.querySelector('#stripe_signup').classList.remove('open'); return false;"></a>
		<div>
			<h4><?php esc_html_e( 'Connect Stripe', 'peachpay-for-woocommerce' ); ?></h4>
			<hr>
			<a href="#" title="Cancel" class="modal-close" onclick="document.querySelector('#stripe_signup').classList.remove('open'); return false;"><?php esc_html_e( 'Cancel', 'peachpay-for-woocommerce' ); ?></a>
			
			<p style="text-align:left; margin-top: 12px;">
				<?php
				if ( $is_test_mode ) {
					esc_html_e( 'Enter your Stripe test API keys below. You can find them in your Stripe Dashboard under Developers → API keys.', 'peachpay-for-woocommerce' );
				} else {
					esc_html_e( 'Enter your Stripe live API keys below. You can find them in your Stripe Dashboard under Developers → API keys.', 'peachpay-for-woocommerce' );
				}
				?>
			</p>

			<div id="pp-stripe-credentials-message" class="pp-notice" style="display: none; margin: 12px 0;"></div>

			<form id="pp-stripe-credentials-form" style="text-align: left; margin-top: 16px;">
				<?php wp_nonce_field( 'peachpay-stripe-credentials', 'pp_stripe_credentials_nonce' ); ?>
				
				<div class="pp-form-field">
					<label for="pp_stripe_<?php echo esc_attr( $mode ); ?>_publishable_key">
						<?php esc_html_e( 'Publishable Key', 'peachpay-for-woocommerce' ); ?>
					</label>
					<input type="text" 
						id="pp_stripe_<?php echo esc_attr( $mode ); ?>_publishable_key" 
						name="<?php echo esc_attr( $mode ); ?>_publishable_key" 
						class="pp-text-input"
						placeholder="<?php echo esc_attr( $is_test_mode ? 'pk_test_...' : 'pk_live_...' ); ?>"
						value="<?php echo esc_attr( $existing_pk ); ?>"
						style="width: 100%;"
					/>
				</div>

				<div class="pp-form-field" style="margin-top: 12px;">
					<label for="pp_stripe_<?php echo esc_attr( $mode ); ?>_secret_key">
						<?php esc_html_e( 'Secret Key', 'peachpay-for-woocommerce' ); ?>
					</label>
					<input type="password" 
						id="pp_stripe_<?php echo esc_attr( $mode ); ?>_secret_key" 
						name="<?php echo esc_attr( $mode ); ?>_secret_key" 
						class="pp-text-input"
						placeholder="<?php echo esc_attr( $is_test_mode ? 'sk_test_...' : 'sk_live_...' ); ?>"
						value="<?php echo esc_attr( $existing_sk ? '••••••••••••••••' : '' ); ?>"
						style="width: 100%;"
					/>
					<span class="pp-field-description"><?php esc_html_e( 'Your secret key is encrypted and stored securely.', 'peachpay-for-woocommerce' ); ?></span>
				</div>

				<details style="margin-top: 16px;">
					<summary style="cursor: pointer; color: #666; font-size: 13px;">
						<?php esc_html_e( 'Webhook Configuration (Optional)', 'peachpay-for-woocommerce' ); ?>
					</summary>
					<div style="padding: 12px 0;">
						<div class="pp-form-field">
							<label><?php esc_html_e( 'Webhook URL', 'peachpay-for-woocommerce' ); ?></label>
							<div style="display: flex; gap: 8px; align-items: center;">
								<code style="flex: 1; padding: 8px; background: #f5f5f5; border: 1px solid #ddd; border-radius: 4px; font-size: 12px; word-break: break-all;"><?php echo esc_html( $webhook_url ); ?></code>
								<button type="button" class="button button-small" onclick="navigator.clipboard.writeText('<?php echo esc_js( $webhook_url ); ?>'); this.textContent='<?php esc_attr_e( 'Copied!', 'peachpay-for-woocommerce' ); ?>';">
									<?php esc_html_e( 'Copy', 'peachpay-for-woocommerce' ); ?>
								</button>
							</div>
							<span class="pp-field-description">
								<?php esc_html_e( 'Add this URL in your', 'peachpay-for-woocommerce' ); ?>
								<a href="https://dashboard.stripe.com/webhooks" target="_blank"><?php esc_html_e( 'Stripe Webhook settings', 'peachpay-for-woocommerce' ); ?></a>
							</span>
						</div>

						<div class="pp-form-field" style="margin-top: 12px;">
							<label for="pp_stripe_webhook_secret">
								<?php esc_html_e( 'Webhook Signing Secret', 'peachpay-for-woocommerce' ); ?>
							</label>
							<input type="password" 
								id="pp_stripe_webhook_secret" 
								name="webhook_secret" 
								class="pp-text-input"
								placeholder="whsec_..."
								value="<?php echo esc_attr( $existing_webhook ? '••••••••••••••••' : '' ); ?>"
								style="width: 100%;"
							/>
							<span class="pp-field-description"><?php esc_html_e( 'Found in your Stripe webhook endpoint settings after creation.', 'peachpay-for-woocommerce' ); ?></span>
						</div>
					</div>
				</details>

				<div class="flex-row gap-12" style="margin-top: 20px;">
					<button type="submit" class="button-primary-filled-medium" id="pp-stripe-save-credentials-btn">
						<?php echo $is_configured ? esc_html__( 'Update', 'peachpay-for-woocommerce' ) : esc_html__( 'Connect', 'peachpay-for-woocommerce' ); ?>
					</button>
					<a href="https://dashboard.stripe.com/<?php echo $is_test_mode ? 'test/' : ''; ?>apikeys" target="_blank" class="button-primary-outlined-medium">
						<?php esc_html_e( 'Get API keys', 'peachpay-for-woocommerce' ); ?>
					</a>
				</div>
			</form>
		</div>
	</div>


	<div class="provider-info">
		<div class="info-icon icon-18"></div>
		<span>
			<span><?php esc_html_e( 'Learn more about', 'peachpay-for-woocommerce' ); ?> </span>
			<a href="https://stripe.com/payments/payment-methods-guide" target="_blank"><?php esc_html_e( 'payment methods', 'peachpay-for-woocommerce' ); ?></a>
			<span> <?php esc_html_e( 'powered by Stripe and any associated', 'peachpay-for-woocommerce' ); ?> </span>
			<a href="https://stripe.com/pricing/local-payment-methods" target="_blank"><?php esc_html_e( 'fees', 'peachpay-for-woocommerce' ); ?></a>
		</span>
	</div>
</div>

<style>
.pp-form-field {
	margin-bottom: 0;
}
.pp-form-field label {
	display: block;
	font-weight: 600;
	margin-bottom: 4px;
	font-size: 13px;
}
.pp-text-input {
	width: 100%;
	padding: 8px 12px;
	border: 1px solid #ddd;
	border-radius: 4px;
	font-size: 14px;
}
.pp-text-input:focus {
	border-color: #007cba;
	box-shadow: 0 0 0 1px #007cba;
	outline: none;
}
.pp-field-description {
	display: block;
	margin-top: 4px;
	font-size: 12px;
	color: #666;
}
.pp-notice {
	padding: 10px 12px;
	border-radius: 4px;
}
.pp-notice.success {
	background: #d4edda;
	border: 1px solid #c3e6cb;
	color: #155724;
}
.pp-notice.error {
	background: #f8d7da;
	border: 1px solid #f5c6cb;
	color: #721c24;
}
</style>

<script type="text/javascript">
jQuery(document).ready(function($) {
	var maskedValue = '••••••••••••••••';
	var mode = '<?php echo esc_js( $mode ); ?>';
	
	console.log('Stripe Connect JS loaded. Mode:', mode);
	
	// Show message helper
	function showMessage($el, type, message) {
		$el.removeClass('success error')
		   .addClass(type)
		   .css({
			   'display': 'block',
			   'padding': '10px 12px',
			   'margin-bottom': '12px',
			   'border-radius': '4px',
			   'background': type === 'success' ? '#d4edda' : '#f8d7da',
			   'border': '1px solid ' + (type === 'success' ? '#c3e6cb' : '#f5c6cb'),
			   'color': type === 'success' ? '#155724' : '#721c24'
		   })
		   .text(message);
	}
	
	// Handle form submission
	function handleFormSubmit($form, $btn, $message) {
		// Debug: log all form inputs
		console.log('Form element:', $form.length ? 'found' : 'NOT FOUND');
		console.log('Form ID:', $form.attr('id'));
		console.log('Form inputs:', $form.find('input').length);
		$form.find('input').each(function() {
			console.log('  Input:', $(this).attr('name'), '=', $(this).val() ? $(this).val().substring(0, 20) + '...' : '(empty)');
		});
		
		var nonce = $form.find('input[name="pp_stripe_credentials_nonce"]').val() || 
		            $form.find('input[name="pp_stripe_update_nonce"]').val() ||
		            $form.find('input[name="_wpnonce"]').val();
		
		console.log('Form submit. Nonce found:', !!nonce, 'value:', nonce ? nonce.substring(0, 10) + '...' : 'none');
		
		if (!nonce) {
			// Try to find nonce anywhere on the page
			var pageNonce = $('input[name="pp_stripe_credentials_nonce"]').val();
			console.log('Page nonce search:', pageNonce ? 'found' : 'not found');
			if (pageNonce) {
				nonce = pageNonce;
			}
		}
		
		if (!nonce) {
			showMessage($message, 'error', 'Security token not found. Please refresh the page.');
			return;
		}
		
		var formData = {
			action: 'pp-stripe-save-credentials',
			security: nonce
		};
		
		// Get keys based on current mode - search in form first, then page-wide
		var pkField = $form.find('input[name="' + mode + '_publishable_key"]');
		var skField = $form.find('input[name="' + mode + '_secret_key"]');
		var webhookField = $form.find('input[name="webhook_secret"]');
		
		// If not found in form, search page-wide (for modal cases)
		if (!pkField.length) pkField = $('input[name="' + mode + '_publishable_key"]');
		if (!skField.length) skField = $('input[name="' + mode + '_secret_key"]');
		if (!webhookField.length) webhookField = $('input[name="webhook_secret"]');
		
		console.log('Fields found - PK:', pkField.length, 'SK:', skField.length);
		console.log('PK value:', pkField.val() ? pkField.val().substring(0, 15) + '...' : '(empty)');
		console.log('SK value:', skField.val() ? (skField.val() === maskedValue ? '(masked)' : skField.val().substring(0, 15) + '...') : '(empty)');
		
		if (pkField.length && pkField.val()) {
			formData[mode + '_publishable_key'] = pkField.val();
		}
		if (skField.length && skField.val() && skField.val() !== maskedValue) {
			formData[mode + '_secret_key'] = skField.val();
		}
		if (webhookField.length && webhookField.val() && webhookField.val() !== maskedValue) {
			formData['webhook_secret'] = webhookField.val();
		}
		
		console.log('Sending data:', Object.keys(formData));
		
		$btn.prop('disabled', true).text('Connecting...');
		$message.hide();
		
		$.ajax({
			url: ajaxurl,
			type: 'POST',
			data: formData,
			success: function(response) {
				console.log('Response:', response);
				$btn.prop('disabled', false).text('Connect');
				
				if (response.success) {
					showMessage($message, 'success', response.data.message || 'Connected successfully!');
					setTimeout(function() { location.reload(); }, 1500);
				} else {
					showMessage($message, 'error', response.data.message || 'An error occurred');
				}
			},
			error: function(xhr, status, error) {
				console.error('AJAX error:', status, error);
				$btn.prop('disabled', false).text('Connect');
				showMessage($message, 'error', 'Request failed: ' + error);
			}
		});
	}
	
	// Modal form - use event delegation for dynamically loaded content
	$(document).on('submit', '#pp-stripe-credentials-form', function(e) {
		e.preventDefault();
		console.log('Modal form submitted');
		handleFormSubmit($(this), $(this).find('button[type="submit"]'), $('#pp-stripe-credentials-message'));
	});
	
	// Handle Enter key in Stripe form inputs - submit only Stripe form, not page form
	$(document).on('keydown', '#pp-stripe-credentials-form input', function(e) {
		if (e.key === 'Enter' || e.keyCode === 13) {
			e.preventDefault();
			e.stopPropagation();
			$('#pp-stripe-credentials-form').trigger('submit');
		}
	});
	
	// Also add click handler on button in case form submit doesn't work
	$(document).on('click', '#pp-stripe-save-credentials-btn', function(e) {
		e.preventDefault();
		console.log('Save button clicked');
		
		// Find the form - try multiple methods
		var $form = $(this).closest('form');
		console.log('Form via closest:', $form.length ? 'found' : 'not found');
		
		if (!$form.length) {
			$form = $('#pp-stripe-credentials-form');
			console.log('Form via ID:', $form.length ? 'found' : 'not found');
		}
		
		if (!$form.length) {
			// Try to find form in modal
			$form = $('#stripe_signup form');
			console.log('Form in modal:', $form.length ? 'found' : 'not found');
		}
		
		var $message = $(this).closest('.modal-window').find('.pp-notice');
		if (!$message.length) {
			$message = $('#pp-stripe-credentials-message');
		}
		
		handleFormSubmit($form, $(this), $message);
	});
	
	// Disconnect button
	$('#pp-stripe-disconnect-btn').on('click', function(e) {
		e.preventDefault();
		
		if (!confirm('<?php echo esc_js( __( 'Are you sure you want to disconnect your Stripe account? This will remove all stored API keys.', 'peachpay-for-woocommerce' ) ); ?>')) {
			return;
		}
		
		var $btn = $(this);
		$btn.addClass('loading').text('Disconnecting...');
		
		$.post(ajaxurl, {
			action: 'pp-stripe-disconnect',
			security: '<?php echo esc_js( wp_create_nonce( 'peachpay-stripe-credentials' ) ); ?>'
		}, function(response) {
			if (response.success) {
				location.reload();
			} else {
				alert(response.data.message || 'Failed to disconnect');
				$btn.removeClass('loading').text('Unlink Stripe');
			}
		}).fail(function() {
			alert('Request failed. Please try again.');
			$btn.removeClass('loading').text('Unlink Stripe');
		});
	});
});
</script>
