<?php
/**
 * Template: Stripe Payouts Section for Affiliate Portal
 *
 * @package     AffiliateWP Stripe Payouts
 * @subpackage  Templates
 * @copyright   Copyright (c) 2025, AffiliateWP, LLC
 * @license     GPL-2.0+
 * @since       2.29.0
 */

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

// Get the current affiliate.
$affiliate_id = affwp_get_affiliate_id();

// Check if Stripe is configured.
if ( ! affwp_stripe_payouts_is_configured() ) {
	return;
}

// Check platform status first.
$platform_status = affwp_stripe_payouts_check_affiliate_platform_status( $affiliate_id );

// Resolve the affiliate's Stripe state. A finished onboarding leaves a connected account ID; an
// abandoned one leaves only a pending ID. Treat pending as connected-but-incomplete so the
// affiliate can resume instead of seeing the from-scratch pitch.
$completed_account_id = affwp_stripe_payouts_get_affiliate_account_id( $affiliate_id );
$pending_account_id   = affwp_stripe_payouts_get_affiliate_pending_account_id( $affiliate_id );

$platform_changed = false;
$is_pending       = false;

if ( ! empty( $completed_account_id ) && 'invalid' === $platform_status ) {
	// A completed connection whose platform changed: force a full reconnect.
	$is_connected     = false;
	$platform_changed = true;
	$account_id       = '';
} elseif ( ! empty( $completed_account_id ) ) {
	$is_connected = true;
	$account_id   = $completed_account_id;
} elseif ( ! empty( $pending_account_id ) ) {
	$is_connected = true;
	$is_pending   = true;
	$account_id   = $pending_account_id;
} else {
	$is_connected = false;
	$account_id   = '';
}

// Get portal page URL for redirect.
$portal_url = class_exists( 'AffiliateWP_Affiliate_Portal\Core\Components\Portal' )
	? AffiliateWP_Affiliate_Portal\Core\Components\Portal::get_page_url( 'settings' )
	: home_url();

/*
 * Rendered inside the Portal's single "Payout settings" card via the
 * `affwp_portal_settings_payout_method_panel` action, after the picker and
 * payment email. We're already inside the section form's Alpine scope, so the
 * panel reads the shared `method` variable directly (no own x-data or picker
 * subscription) and shows only when Stripe is the current selection. It sits in
 * the same card as the fields above, separated only by vertical spacing.
 */

/*
 * When the picker is hidden, Alpine's `method` never syncs from $refs.payoutMethod and
 * x-show would strand this block hidden, so only gate on the selection when the picker
 * is actually rendered.
 */
$picker_visible = function_exists( 'affwp_affiliate_payout_picker_is_visible' )
	&& affwp_affiliate_payout_picker_is_visible();
?>

<div
	class="mt-6"
	<?php if ( $picker_visible ) : ?>
		x-show="method === 'stripe'"
		x-cloak
	<?php endif; ?>
>
	<?php if ( $is_connected ) : ?>
		<?php
		// A pending account is onboarding-in-progress by definition; skip the Stripe status call and
		// treat it as incomplete so the affiliate is sent back to resume.
		$is_onboarding_complete = false;
		if ( ! $is_pending ) {
			$account_status         = affwp_stripe_payouts_get_account_status( $account_id );
			$is_onboarding_complete = isset( $account_status['details_submitted'] ) && $account_status['details_submitted'];
		}

		// Incomplete account + cross-border on: let an affiliate stuck with a wrong-country account
		// start over and reconnect in their own country.
		$can_reonboard_country = ! $is_onboarding_complete
			&& function_exists( 'affwp_stripe_payouts_cross_border_enabled' )
			&& affwp_stripe_payouts_cross_border_enabled()
			&& function_exists( 'affwp_stripe_payouts_platform_supports_cross_border' )
			&& affwp_stripe_payouts_platform_supports_cross_border();
		?>

		<div class="mb-4">
			<div class="flex items-center">
				<?php if ( $is_onboarding_complete ) : ?>
					<?php \AffiliateWP\Utils\Icons::render( 'check-circle', '', [ 'class' => 'size-5 mr-2 text-green-600' ] ); ?>
				<?php else : ?>
					<?php \AffiliateWP\Utils\Icons::render( 'clock', '', [ 'class' => 'size-5 mr-2 text-yellow-500' ] ); ?>
				<?php endif; ?>
				<span class="text-sm font-medium text-gray-900">
					<?php
					echo $is_onboarding_complete
						? esc_html__( 'Stripe account connected', 'affiliate-wp' )
						: esc_html__( 'Stripe setup in progress', 'affiliate-wp' );
					?>
				</span>
			</div>
			<p class="mt-2 text-sm text-gray-500">
				<?php
				/* translators: %s: Account ID */
				printf( esc_html__( 'Account ID: %s', 'affiliate-wp' ), '<code class="px-2 py-1 bg-gray-100 rounded text-xs">' . esc_html( $account_id ) . '</code>' );
				?>
			</p>
		</div>

		<?php if ( $is_onboarding_complete ) : ?>

			<div class="flex flex-col gap-1">
				<a href="<?php echo esc_url( add_query_arg( [ 'affwp_action' => 'stripe_payouts_dashboard', 'affiliate_id' => $affiliate_id, '_wpnonce' => wp_create_nonce( 'affwp_stripe_payouts_dashboard_' . $affiliate_id ) ], $portal_url ) ); ?>"
					target="_blank"
					class="inline-flex items-center text-sm font-medium text-indigo-600 hover:text-indigo-500 transition duration-150 ease-in-out focus:outline-none">
					<?php esc_html_e( 'Access Stripe Dashboard', 'affiliate-wp' ); ?>
				</a>
				<p class="text-sm text-gray-500">
					<?php esc_html_e( 'Manage your bank account details, tax information, and other settings through your Stripe Dashboard.', 'affiliate-wp' ); ?>
				</p>
			</div>

		<?php else : ?>

			<p class="text-sm text-gray-600 mb-4">
				<?php esc_html_e( 'Your Stripe account is connected but needs to complete the onboarding process. Click "Complete Setup" to finish providing the required information for receiving payouts.', 'affiliate-wp' ); ?>
				<?php if ( $can_reonboard_country ) : ?>
					<?php esc_html_e( 'If you receive payouts in a different country, start over to choose it.', 'affiliate-wp' ); ?>
				<?php endif; ?>
			</p>
			<?php
			// Pending onboarding resumes through the connect handler (it picks the existing account
			// back up and finishes it); a completed account that Stripe later flagged uses the
			// manage/account-update link instead.
			$affwp_sp_setup_href = $is_pending
				? add_query_arg( [ 'affwp_action' => 'stripe_payouts_connect', 'affiliate_id' => $affiliate_id ], $portal_url )
				: add_query_arg( [ 'affwp_action' => 'stripe_payouts_manage', 'affiliate_id' => $affiliate_id, '_wpnonce' => wp_create_nonce( 'affwp_stripe_payouts_manage_' . $affiliate_id ) ], $portal_url );
			?>
			<div class="flex gap-3">
				<a href="<?php echo esc_url( $affwp_sp_setup_href ); ?>"
					class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
					<?php esc_html_e( 'Complete Setup', 'affiliate-wp' ); ?>
				</a>
				<?php if ( $can_reonboard_country ) : ?>
					<a href="<?php echo esc_url( add_query_arg( [ 'affwp_action' => 'stripe_payouts_disconnect', 'affiliate_id' => $affiliate_id, '_wpnonce' => wp_create_nonce( 'affwp_stripe_payouts_disconnect_' . $affiliate_id ) ], $portal_url ) ); ?>"
						class="inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
						<?php esc_html_e( 'Choose a different country', 'affiliate-wp' ); ?>
					</a>
				<?php endif; ?>
			</div>

		<?php endif; ?>

	<?php else : ?>

		<div class="mb-4">
			<div class="flex items-center">
				<?php if ( $platform_changed ) : ?>
					<?php \AffiliateWP\Utils\Icons::render( 'triangle-warning', '', [ 'class' => 'size-5 mr-2 text-yellow-500' ] ); ?>
					<span class="text-sm font-medium text-gray-900">
						<?php esc_html_e( 'Reconnection required due to platform change', 'affiliate-wp' ); ?>
					</span>

				<?php endif; ?>
			</div>
		</div>

		<?php if ( $platform_changed ) : ?>
			<div class="bg-yellow-50 rounded-lg p-4 mb-6">
				<div class="flex">
					<div class="shrink-0">
						<?php \AffiliateWP\Utils\Icons::render( 'triangle-warning', '', [ 'class' => 'size-5 text-yellow-400' ] ); ?>
					</div>
					<div class="ml-3">
						<p class="text-sm text-yellow-700">
							<?php esc_html_e( 'The site administrator has changed their Stripe account configuration. For security reasons, you need to reconnect with Stripe to continue receiving payouts. This is a one-time process to ensure your payment information remains secure.', 'affiliate-wp' ); ?>
						</p>
					</div>
				</div>
			</div>
		<?php else : ?>
			<div id="affwp-stripe-pitch" class="bg-blue-50 rounded-lg p-4 mb-6"
				x-show="country && ( serviceable.length === 0 || serviceable.indexOf( country.toUpperCase() ) !== -1 )"
				x-cloak>
				<div class="flex">
					<div class="shrink-0">
						<?php \AffiliateWP\Utils\Icons::render( 'circle-info', '', [ 'class' => 'size-5 text-blue-400' ] ); ?>
					</div>
					<div class="ml-3">
						<p class="text-sm text-blue-700">
							<?php esc_html_e( 'To receive your referral payouts, we\'ll set up a secure Stripe account for you. This allows us to send payments directly to your bank account. Stripe will guide you through a quick verification process to ensure secure payments.', 'affiliate-wp' ); ?>
						</p>
					</div>
				</div>
			</div>
		<?php endif; ?>

		<div>
			<?php
			// Full payout-country question: the affiliate's answer decides whether Stripe can serve them.
			$affwp_sp_countries = function_exists( 'affwp_get_country_list' ) ? affwp_get_country_list() : array();

			$affwp_sp_serviceable = array();
			if ( function_exists( 'affwp_stripe_payouts_get_domestic_country' ) ) {
				$affwp_sp_domestic = affwp_stripe_payouts_get_domestic_country();
				if ( is_string( $affwp_sp_domestic ) && '' !== $affwp_sp_domestic ) {
					$affwp_sp_serviceable[] = strtoupper( $affwp_sp_domestic );
				}
			}
			if ( function_exists( 'affwp_stripe_payouts_cross_border_enabled' )
				&& function_exists( 'affwp_stripe_payouts_platform_supports_cross_border' )
				&& function_exists( 'affwp_stripe_payouts_get_supported_countries' )
				&& affwp_stripe_payouts_cross_border_enabled()
				&& affwp_stripe_payouts_platform_supports_cross_border()
			) {
				$affwp_sp_serviceable = array_merge( $affwp_sp_serviceable, array_map( 'strtoupper', array_keys( affwp_stripe_payouts_get_supported_countries() ) ) );
			}
			$affwp_sp_serviceable = array_values( array_unique( $affwp_sp_serviceable ) );

			$affwp_sp_current   = function_exists( 'affwp_get_affiliate_payout_country' ) ? affwp_get_affiliate_payout_country( $affiliate_id ) : '';
			$affwp_sp_suggested = function_exists( 'affwp_stripe_payouts_get_domestic_country' ) ? affwp_stripe_payouts_get_domestic_country() : '';
			$affwp_sp_suggested = ( is_string( $affwp_sp_suggested ) && isset( $affwp_sp_countries[ $affwp_sp_suggested ] ) ) ? $affwp_sp_suggested : '';
			$affwp_sp_connect_base   = add_query_arg( array( 'affwp_action' => 'stripe_payouts_connect', 'affiliate_id' => $affiliate_id ), $portal_url );
			$affwp_sp_is_serviceable = ( '' !== $affwp_sp_current && in_array( $affwp_sp_current, $affwp_sp_serviceable, true ) );
			$affwp_sp_initial_href   = $affwp_sp_is_serviceable ? add_query_arg( 'affwp_stripe_country', $affwp_sp_current, $affwp_sp_connect_base ) : $affwp_sp_connect_base;
			?>
			<div class="space-y-3">
				<div>
					<label for="affwp-stripe-country" class="block text-sm font-medium text-gray-700 mb-1">
						<?php esc_html_e( 'Which country do you receive payouts in?', 'affiliate-wp' ); ?>
					</label>
					<select id="affwp-stripe-country"
						x-model="country"
						x-ref="affwpCountrySelect"
						data-ajaxurl="<?php echo esc_url( admin_url( 'admin-ajax.php' ) ); ?>"
						data-nonce="<?php echo esc_attr( wp_create_nonce( 'affwp_save_payout_country' ) ); ?>"
						class="form-select block w-full rounded-md border-gray-300 bg-white text-sm text-gray-900 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
						<option value="" <?php selected( '', $affwp_sp_current ); ?>><?php esc_html_e( 'Select your country…', 'affiliate-wp' ); ?></option>
						<?php if ( '' !== $affwp_sp_suggested ) : ?>
							<optgroup label="<?php esc_attr_e( 'Suggested', 'affiliate-wp' ); ?>">
								<option value="<?php echo esc_attr( $affwp_sp_suggested ); ?>" <?php selected( $affwp_sp_suggested, $affwp_sp_current ); ?>><?php echo esc_html( $affwp_sp_countries[ $affwp_sp_suggested ] ); ?></option>
							</optgroup>
						<?php endif; ?>
						<optgroup label="<?php esc_attr_e( 'All countries', 'affiliate-wp' ); ?>">
							<?php foreach ( $affwp_sp_countries as $affwp_sp_code => $affwp_sp_name ) : ?>
								<option value="<?php echo esc_attr( $affwp_sp_code ); ?>" <?php selected( (string) $affwp_sp_code, (string) $affwp_sp_current ); ?>><?php echo esc_html( $affwp_sp_name ); ?></option>
							<?php endforeach; ?>
						</optgroup>
					</select>
					<p class="mt-2 text-sm text-gray-600" x-show="! country" x-cloak>
						<?php esc_html_e( 'Choose the country where you receive payouts to continue.', 'affiliate-wp' ); ?>
					</p>
					<div class="mt-2 rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700"
						role="alert"
						x-show="country && serviceable.length && serviceable.indexOf( country.toUpperCase() ) === -1"
						x-cloak>
						<span x-text="nopeTpl.replace( '%s', $refs.affwpCountrySelect && $refs.affwpCountrySelect.selectedOptions.length ? $refs.affwpCountrySelect.selectedOptions[0].text : country )"></span>
						<button type="button"
							style="background:none;border:0;padding:0;margin:0;color:inherit;font:inherit;text-decoration:underline;cursor:pointer;"
							x-show="switchTo"
							x-cloak
							@click="method = switchTo; if ( $refs.payoutMethod ) { $refs.payoutMethod.value = switchTo } ; $dispatch( 'affwp-payout-method-changed', switchTo )"
							x-text="switchTpl.replace( '%s', switchToLabel )"></button>
						<span x-show="! switchTo && paidViaLabel" x-cloak x-text="viaTpl.replace( '%s', paidViaLabel )"></span>
						<span x-show="! switchTo && ! paidViaLabel" x-cloak x-text="deadEndMsg"></span>
					</div>
				</div>
				<a id="affwp-stripe-connect-link"
					x-show="country && ( serviceable.length === 0 || serviceable.indexOf( country.toUpperCase() ) !== -1 )"
					x-cloak
					:href="'<?php echo esc_js( $affwp_sp_connect_base ); ?>&affwp_stripe_country=' + encodeURIComponent( country.toUpperCase() )"
					class="inline-flex items-center px-6 py-3 border border-transparent text-base font-medium rounded-md shadow-sm text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
					<svg class="mr-3 h-5 w-5" viewBox="0 0 24 24" fill="currentColor">
						<path d="M13.976 9.15c-2.172-.806-3.356-1.426-3.356-2.409 0-.831.683-1.305 1.901-1.305 2.227 0 4.515.858 6.09 1.631l.89-5.494C18.252.274 15.697 0 12.165 0 9.667 0 7.589.654 6.104 1.872 4.56 3.147 3.757 4.992 3.757 7.218c0 4.039 2.467 5.76 6.476 7.219 2.585.92 3.445 1.574 3.445 2.583 0 .98-.84 1.545-2.354 1.545-1.875 0-4.965-.921-6.99-2.109l-.9 5.555C5.175 22.99 8.385 24 11.714 24c2.641 0 4.843-.624 6.328-1.813 1.664-1.305 2.525-3.236 2.525-5.732 0-4.128-2.524-5.851-6.591-7.305z"/>
					</svg>
					<?php esc_html_e( 'Set Up Stripe Payouts', 'affiliate-wp' ); ?>
				</a>
			</div>
			<script>
			// Persist the payout country on change (the Portal has no profile-form submit for it).
			// All reveals are Alpine (x-model="country"); this only writes the value via AJAX.
			( function () {
				var sel = document.getElementById( 'affwp-stripe-country' );
				if ( ! sel ) { return; }
				sel.addEventListener( 'change', function () {
					var url = sel.dataset.ajaxurl, nonce = sel.dataset.nonce;
					if ( ! url || ! nonce ) { return; }
					var body = new URLSearchParams();
					body.append( 'action', 'affwp_save_payout_country' );
					body.append( 'nonce', nonce );
					body.append( 'country', ( sel.value || '' ).toUpperCase() );
					fetch( url, { method: 'POST', credentials: 'same-origin', body: body } );
				} );
			} )();
			</script>
		</div>

	<?php endif; ?>
</div>
