<?php

/**
 * PeachPay PayPal Connect
 *
 * @package PeachPay
 */

defined('PEACHPAY_ABSPATH') || exit;

$manual_credentials = PeachPay_PayPal_Integration::get_manual_credentials();
$is_connected       = PeachPay_PayPal_Integration::connected();
?>
<div class="flex-col payment-provider-header <?php echo esc_attr($is_connected ? 'is-connected' : ''); ?>">
	<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/paypal/small-white.svg')); ?>" />
			<?php esc_html_e('PayPal Account', 'peachpay-for-woocommerce'); ?>
		</div>

		<?php if ($is_connected) : ?>
			<div class="flex-col gap-12 connected-info">
				<div class="flex-row gap-8 ai-center connected-success">
					<?php if (peachpay_is_test_mode()) : ?>
						<?php esc_html_e('PayPal sandbox account is connected!', 'peachpay-for-woocommerce'); ?>
					<?php else : ?>
						<?php esc_html_e('Your PayPal account is connected!', 'peachpay-for-woocommerce'); ?>
					<?php endif; ?>
					<img src="<?php echo esc_attr(peachpay_url('public/img/checkmark-green.svg')); ?>" />
				</div>
				<span class="account-info">
					<?php if (peachpay_is_test_mode()) : ?>
						<?php esc_html_e('Make test payments following', 'peachpay-for-woocommerce'); ?> <a href="https://developer.paypal.com/tools/sandbox/card-testing/" target="_blank"><?php esc_html_e('these instructions', 'peachpay-for-woocommerce'); ?></a>.
					<?php else : ?>
						<?php esc_html_e('Client ID:', 'peachpay-for-woocommerce'); ?>
						<span><?php echo esc_html(! empty($manual_credentials['client_id']) ? substr($manual_credentials['client_id'], 0, 20) . '...' : ''); ?></span>
					<?php endif; ?>
				</span>
			</div>
		<?php else : ?>
			<div class="flex-col provider-description">
				<p>
					<span><?php esc_html_e("If you have a regular PayPal account, you'll be asked to upgrade to a business account. Not using PayPal yet? PayPal is accepted in over 200 countries and allows shoppers from almost anywhere to buy from you.", 'peachpay-for-woocommerce'); ?></span>
					<span><?php esc_html_e('With PayPal you will be able to connect the following payment methods:', 'peachpay-for-woocommerce'); ?></span>
				</p>
				<div class="method-icons">
					<?php
					foreach (PeachPay_PayPal_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_connected) : ?>
			<a class="update-payment-button button-primary-filled-medium" href="<?php echo esc_url(PeachPay_PayPal_Advanced::get_url()); ?>">
				<?php esc_html_e('Advanced settings', 'peachpay-for-woocommerce'); ?>
			</a>
			<a class="unlink-payment-button button-error-outlined-medium" href="<?php echo esc_url(admin_url('admin.php?page=peachpay&tab=payment&unlink_paypal_manual#paypal')); ?>">
				<?php esc_html_e('Disconnect PayPal', 'peachpay-for-woocommerce'); ?>
			</a>
		<?php else : ?>
			<div class="pp-credentials-wrap" style="width: 100%;">
				<p class="pp-credentials-intro">
					<?php esc_html_e('Enter your PayPal API credentials. You can find these in your PayPal Developer Dashboard.', 'peachpay-for-woocommerce'); ?>
				</p>

				<form id="paypal-credentials-form" method="post">
					<?php wp_nonce_field('peachpay_paypal_ajax_save', 'peachpay_paypal_ajax_nonce'); ?>

					<div class="pp-credentials-row">
						<div class="pp-credentials-fields">
							<div class="pp-form-field">
								<label for="paypal_client_id">
									<?php esc_html_e('Client ID', 'peachpay-for-woocommerce'); ?>
									<span class="required">*</span>
								</label>
								<input type="text" id="paypal_client_id" name="paypal_client_id"
									value="<?php echo esc_attr(isset($manual_credentials['client_id']) ? $manual_credentials['client_id'] : ''); ?>"
									placeholder="<?php esc_attr_e('Enter your Client ID', 'peachpay-for-woocommerce'); ?>"
									required />
							</div>
							<div class="pp-form-field">
								<label for="paypal_client_secret">
									<?php esc_html_e('Client Secret', 'peachpay-for-woocommerce'); ?>
									<span class="required">*</span>
								</label>
								<input type="password" id="paypal_client_secret" name="paypal_client_secret"
									value=""
									placeholder="<?php esc_attr_e('Enter your Client Secret', 'peachpay-for-woocommerce'); ?>"
									required autocomplete="off" />
							</div>
							<div class="pp-credentials-actions">
								<button type="button" id="paypal-save-btn" class="button-primary-filled-medium">
									<?php esc_html_e('Save & Connect', 'peachpay-for-woocommerce'); ?>
								</button>
							</div>
						</div>
						<div class="pp-credentials-sidebar">
							<div class="pp-info-box">
								<strong><?php esc_html_e('How to get your API credentials', 'peachpay-for-woocommerce'); ?></strong>
								<ol>
									<li><?php esc_html_e('Go to', 'peachpay-for-woocommerce'); ?> <a href="https://developer.paypal.com/dashboard/applications/live" target="_blank" rel="noopener noreferrer"><?php esc_html_e('PayPal Developer Dashboard', 'peachpay-for-woocommerce'); ?></a></li>
									<li><?php esc_html_e('Log in with your PayPal Business account', 'peachpay-for-woocommerce'); ?></li>
									<li><?php esc_html_e('Go to "Apps & Credentials" and create a new app or select an existing one', 'peachpay-for-woocommerce'); ?></li>
									<li><?php esc_html_e('Copy the Client ID and Secret key', 'peachpay-for-woocommerce'); ?></li>
								</ol>
							</div>
						</div>
					</div>
				</form>
			</div>
		<?php endif; ?>
	</div>

	<div class="provider-info">
		<div class="info-icon icon-18"></div>
		<span>
			<?php esc_html_e('Learn more about', 'peachpay-for-woocommerce'); ?>
			<a href="https://www.paypal.com/us/business/accept-payments/checkout" target="_blank"><?php esc_html_e('payment methods', 'peachpay-for-woocommerce'); ?></a>
			<?php esc_html_e('powered by PayPal and any associated', 'peachpay-for-woocommerce'); ?>
			<a href="https://www.paypal.com/us/webapps/mpp/merchant-fees" target="_blank"><?php esc_html_e('fees', 'peachpay-for-woocommerce'); ?></a>
		</span>
	</div>
</div>

<script>
	jQuery(document).ready(function($) {
		// The parent settings form validates these fields on "Save changes".
		// Skip browser validation here; PayPal credentials are validated via AJAX.
		$('#submit').attr('formnovalidate', 'formnovalidate');

		$('#paypal-save-btn').on('click', function(e) {
			e.preventDefault();

			var clientId = $('#paypal_client_id').val().trim();
			var clientSecret = $('#paypal_client_secret').val().trim();
			var nonce = $('#peachpay_paypal_ajax_nonce').val();

			if (!clientId || !clientSecret) {
				window.PeachPayAdminNotices?.show('error', 'error', '<?php echo esc_js(__('Both Client ID and Client Secret are required.', 'peachpay-for-woocommerce')); ?>', true);
				return;
			}

			var submitBtn = $(this);
			var originalText = submitBtn.text();
			submitBtn.prop('disabled', true);
			submitBtn.text('<?php echo esc_js(__('Saving...', 'peachpay-for-woocommerce')); ?>');

			window.PeachPayAdminNotices?.show('info', 'saving-changes', '<?php echo esc_js(__('Validating and saving PayPal credentials...', 'peachpay-for-woocommerce')); ?>');

			$.post(
				typeof ajaxurl !== 'undefined' ? ajaxurl : '<?php echo esc_js(admin_url('admin-ajax.php')); ?>', {
					action: 'peachpay_save_paypal_credentials',
					paypal_client_id: clientId,
					paypal_client_secret: clientSecret,
					peachpay_paypal_ajax_nonce: nonce
				},
				function(response) {
					if (response && response.success) {
						window.PeachPayAdminNotices?.show('success', 'saved-changes', response.data && response.data.message ? response.data.message : '<?php echo esc_js(__('PayPal credentials saved successfully!', 'peachpay-for-woocommerce')); ?>');

						setTimeout(function() {
							location.reload();
						}, 1000);
					} else {
						submitBtn.prop('disabled', false);
						submitBtn.text(originalText);
						window.PeachPayAdminNotices?.show('error', 'error', response && response.data && response.data.message ? response.data.message : '<?php echo esc_js(__('Invalid PayPal credentials. Please check and try again.', 'peachpay-for-woocommerce')); ?>', true);
					}
				}
			).fail(function() {
				submitBtn.prop('disabled', false);
				submitBtn.text(originalText);
				window.PeachPayAdminNotices?.show('error', 'error', '<?php echo esc_js(__('Unable to save PayPal credentials right now. Please try again.', 'peachpay-for-woocommerce')); ?>', true);
			});
		});
	});
</script>