<?php
/**
 * PeachPay Square Connect
 *
 * @package PeachPay
 */

defined( 'PEACHPAY_ABSPATH' ) || exit;

$is_test_mode  = peachpay_is_test_mode();
$is_configured = PeachPay_Square_Credentials::is_configured();
$account       = PeachPay_Square_Credentials::get_account();
$webhook_url   = get_rest_url( null, 'peachpay/v1/square/webhook' );
$mode          = $is_test_mode ? 'test' : 'live';
$existing_pk   = PeachPay_Square_Credentials::get_publishable_key( $mode );
$existing_sk   = PeachPay_Square_Credentials::get_secret_key( $mode );
$existing_webhook_secret = PeachPay_Square_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/square/short.svg' ) ); ?>" />
				<?php esc_html_e( 'Square Account', 'peachpay-for-woocommerce' ); ?>
			</div>
			<!-- Square 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 esc_html_e( 'Your Square sandbox account is connected!', 'peachpay-for-woocommerce' ); ?>
						<?php else : ?>
							<?php esc_html_e( 'Your Square 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://developer.squareup.com/docs/devtools/sandbox/payments" target="_blank"><?php esc_html_e( 'these instructions', 'peachpay-for-woocommerce' ); ?></a>.
							</span>
						<?php endif; ?>
						<?php if ( ! empty( $account['business_name'] ) ) : ?>
							<span class="account-info">
								<?php esc_html_e( 'Business Name:', 'peachpay-for-woocommerce' ); ?>
								<span><?php echo esc_html( $account['business_name'] ); ?></span>
							</span>
						<?php endif; ?>
						<?php if ( ! empty( $account['country'] ) ) : ?>
							<span class="account-info">
								<?php esc_html_e( 'Country:', 'peachpay-for-woocommerce' ); ?>
								<span><?php echo esc_html( $account['country'] ); ?></span>
							</span>
						<?php endif; ?>
						<?php if ( ! empty( $account['currency'] ) ) : ?>
							<span class="account-info">
								<?php esc_html_e( 'Currency:', 'peachpay-for-woocommerce' ); ?>
								<span><?php echo esc_html( $account['currency'] ); ?></span>
							</span>
						<?php endif; ?>
					</div>
				</div>
			<?php else : ?>
				<div class="flex-col provider-description">
					<p>
						<span><?php esc_html_e( 'Not sure if Square is right for you?', 'peachpay-for-woocommerce' ); ?></span>
						<span><?php esc_html_e( 'Square is good for merchants who sell online and in a physical store. It\'s also good if you sell items that are usually risky for other payment processors.', 'peachpay-for-woocommerce' ); ?></span>
						<span><?php esc_html_e( 'With Square you will be able to connect the following payment methods:', 'peachpay-for-woocommerce' ); ?></span>
					</p>
					<div class="method-icons">
						<?php
						foreach ( PeachPay_Square_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">
			<?php if ( $is_configured ) : ?>
				<a class="unlink-payment-button button-error-outlined-medium" href="#" id="pp-square-disconnect-btn">
					<?php esc_html_e( 'Unlink Square', 'peachpay-for-woocommerce' ); ?>
				</a>
			<?php else : ?>
				<a class="connect-payment-button button-primary-filled-medium" href="#" onclick="document.querySelector('#square_signup').classList.add('open'); return false;">
					<?php esc_html_e( 'Connect Square', 'peachpay-for-woocommerce' ); ?>
				</a>
			<?php endif; ?>
		</div>
	</div>

	<!-- Square Connect Modal -->
	<div id="square_signup" class="modal-window">
		<a href="#" class="outside-close" onclick="document.querySelector('#square_signup').classList.remove('open'); return false;"></a>
		<div>
			<h4><?php esc_html_e( 'Connect Square', 'peachpay-for-woocommerce' ); ?></h4>
			<hr>
			<a href="#" title="Cancel" class="modal-close" onclick="document.querySelector('#square_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 Square sandbox API keys below. You can find them in your Square Developer Dashboard under your application.', 'peachpay-for-woocommerce' );
				} else {
					esc_html_e( 'Enter your Square live API keys below. You can find them in your Square Developer Dashboard under your application.', 'peachpay-for-woocommerce' );
				}
				?>
			</p>

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

			<form id="pp-square-credentials-form" style="text-align: left; margin-top: 16px;">
				<?php wp_nonce_field( 'peachpay-square-credentials', 'pp_square_credentials_nonce' ); ?>
				
				<div class="pp-form-field">
					<label for="pp_square_<?php echo esc_attr( $mode ); ?>_publishable_key">
						<?php esc_html_e( 'Application ID', 'peachpay-for-woocommerce' ); ?>
					</label>
					<input type="text" 
						id="pp_square_<?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 ? 'sandbox-sq0idb-...' : 'sq0idp-...' ); ?>"
						value="<?php echo esc_attr( $existing_pk ); ?>"
						style="width: 100%;"
					/>
				</div>

				<div class="pp-form-field" style="margin-top: 12px;">
					<label for="pp_square_<?php echo esc_attr( $mode ); ?>_secret_key">
						<?php esc_html_e( 'Access Token', 'peachpay-for-woocommerce' ); ?>
					</label>
					<input type="password" 
						id="pp_square_<?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 ? 'EAAAl...' : 'EAAAl...' ); ?>"
						value="<?php echo esc_attr( $existing_sk ? '••••••••••••••••' : '' ); ?>"
						style="width: 100%;"
					/>
					<span class="pp-field-description"><?php esc_html_e( 'Your access token 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 Square webhook settings.', 'peachpay-for-woocommerce' ); ?></span>
						</div>

						<div class="pp-form-field" style="margin-top: 12px;">
							<label for="pp_square_webhook_secret">
								<?php esc_html_e( 'Webhook Signature Key', 'peachpay-for-woocommerce' ); ?>
							</label>
							<input type="password"
								id="pp_square_webhook_secret"
								name="webhook_secret"
								class="pp-text-input"
								placeholder="whsec_..."
								value="<?php echo esc_attr( $existing_webhook_secret ? '••••••••••••••••' : '' ); ?>"
								style="width: 100%;"
							/>
							<span class="pp-field-description"><?php esc_html_e( 'Used to verify incoming Square webhooks.', '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-square-save-credentials-btn">
						<?php echo $is_configured ? esc_html__( 'Update', 'peachpay-for-woocommerce' ) : esc_html__( 'Connect', 'peachpay-for-woocommerce' ); ?>
					</button>
					<a href="https://developer.squareup.com/console/en/apps" 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://squareup.com/us/en/payments" target="_blank"><?php esc_html_e( 'payment methods', 'peachpay-for-woocommerce' ); ?></a>
			<span> <?php esc_html_e( 'powered by Square and any associated', 'peachpay-for-woocommerce' ); ?> </span>
			<a href="https://squareup.com/us/en/payments/our-fees" 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 ); ?>';
	var initialButtonText = '<?php echo esc_js( $is_configured ? __( 'Update', 'peachpay-for-woocommerce' ) : __( 'Connect', 'peachpay-for-woocommerce' ) ); ?>';
	
	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);
	}
	
	function handleFormSubmit($form, $btn, $message) {
		var nonce = $form.find('input[name="pp_square_credentials_nonce"]').val() ||
		            $form.find('input[name="_wpnonce"]').val();
		
		if (!nonce) {
			var pageNonce = $('input[name="pp_square_credentials_nonce"]').val();
			if (pageNonce) {
				nonce = pageNonce;
			}
		}
		
		if (!nonce) {
			showMessage($message, 'error', 'Security token not found. Please refresh the page.');
			return;
		}
		
		var formData = {
			action: 'pp-square-save-credentials',
			security: nonce
		};
		
		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 (!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"]');
		
		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();
		}
		
		$btn.prop('disabled', true).text('<?php echo esc_js( __( 'Saving...', 'peachpay-for-woocommerce' ) ); ?>');
		$message.hide();
		
		$.ajax({
			url: ajaxurl,
			type: 'POST',
			data: formData,
			success: function(response) {
				$btn.prop('disabled', false).text(initialButtonText);
				
				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) {
				$btn.prop('disabled', false).text(initialButtonText);
				showMessage($message, 'error', 'Request failed: ' + error);
			}
		});
	}
	
	$(document).on('submit', '#pp-square-credentials-form', function(e) {
		e.preventDefault();
		handleFormSubmit($(this), $(this).find('button[type="submit"]'), $('#pp-square-credentials-message'));
	});
	
	$(document).on('keydown', '#pp-square-credentials-form input', function(e) {
		if (e.key === 'Enter' || e.keyCode === 13) {
			e.preventDefault();
			e.stopPropagation();
			$('#pp-square-credentials-form').trigger('submit');
		}
	});
	
	$(document).on('click', '#pp-square-save-credentials-btn', function(e) {
		e.preventDefault();
		
		var $form = $(this).closest('form');
		if (!$form.length) {
			$form = $('#pp-square-credentials-form');
		}
		if (!$form.length) {
			$form = $('#square_signup form');
		}
		
		var $message = $(this).closest('.modal-window').find('.pp-notice');
		if (!$message.length) {
			$message = $('#pp-square-credentials-message');
		}
		
		handleFormSubmit($form, $(this), $message);
	});
	
	$('#pp-square-disconnect-btn').on('click', function(e) {
		e.preventDefault();
		
		if (!confirm('<?php echo esc_js( __( 'Are you sure you want to disconnect your Square account? This will remove all stored API keys.', 'peachpay-for-woocommerce' ) ); ?>')) {
			return;
		}
		
		var $btn = $(this);
		$btn.addClass('loading').text('Disconnecting...');
		
		$.post(ajaxurl, {
			action: 'pp-square-disconnect',
			security: '<?php echo esc_js( wp_create_nonce( 'peachpay-square-credentials' ) ); ?>'
		}, function(response) {
			if (response.success) {
				location.reload();
			} else {
				alert(response.data.message || 'Failed to disconnect');
				$btn.removeClass('loading').text('Unlink Square');
			}
		}).fail(function() {
			alert('Request failed. Please try again.');
			$btn.removeClass('loading').text('Unlink Square');
		});
	});
});
</script>
