<?php
$affiliate              = affwp_get_affiliate();
$affiliate_id           = $affiliate->affiliate_id;
$affiliate_user_id      = $affiliate->user_id;
$payment_email          = affwp_get_affiliate_payment_email( $affiliate_id );
$payouts_service_meta   = affwp_get_affiliate_meta( $affiliate_id, 'payouts_service_account', true );

$effective_method = function_exists( 'affwp_get_affiliate_usable_payout_method' )
	? affwp_get_affiliate_usable_payout_method( $affiliate_id )
	: '';

$picker_methods = function_exists( 'affwp_get_payout_methods_for_display' )
	? affwp_get_payout_methods_for_display( 'affiliate' )
	: array();

/*
 * Picker renders when "Allow affiliates to choose" is on AND at least two
 * affiliate-selectable methods exist. With fewer than two, there's nothing
 * to choose between — the toggle becomes inert and the affiliate falls
 * through to the regular status line showing the resolver's effective method.
 */
$picker_visible = function_exists( 'affwp_affiliate_payout_picker_is_visible' )
	&& affwp_affiliate_payout_picker_is_visible();

/*
 * Alpine `method` must mirror the picker's selected option (it's the x-model target and drives the
 * per-method reveals), NOT the resolver's effective method. When the resolver downgrades a selection
 * it can't honor (e.g. Stripe for an unserviceable country), the picker still shows the affiliate's
 * saved choice, so seeding from the effective method would hide that method's sub-fields (the country
 * field, the Stripe section) even though the picker shows the method selected.
 */
$picker_payload        = function_exists( 'affwp_get_affiliate_picker_options' )
	? affwp_get_affiliate_picker_options( $affiliate_id )
	: array();
// With a picker, mirror its selected option; without one, the affiliate is on (and can't change)
// the resolved effective method.
$alpine_initial_method = ( $picker_visible && isset( $picker_payload['current_value'] ) )
	? (string) $picker_payload['current_value']
	: (string) $effective_method;

// Country is part of the same Alpine state so the Stripe reveals (country field, connect gate) are
// driven by one model. Seeded from the saved payout country.
$alpine_initial_country = function_exists( 'affwp_get_affiliate_payout_country' )
	? (string) affwp_get_affiliate_payout_country( $affiliate_id )
	: '';

/**
 * Alpine state for the "How you'll be paid" block, emitted as JSON x-data (no methods, no `$store`)
 * so it evaluates under both the core Alpine and any older Alpine an add-on bundles on this page
 * (e.g. the Affiliate Portal). Methods inject method-specific data here: the Stripe integration adds
 * its serviceable-country allowlist, connect URL, and error template so the country field and connect
 * gate read one source.
 *
 * @since 2.34.0
 *
 * @param array $data         Base state (method, country) plus empty defaults integrations fill.
 * @param int   $affiliate_id Affiliate ID.
 */
$payout_alpine = apply_filters(
	'affwp_affiliate_area_payout_alpine_data',
	array(
		'method'           => $alpine_initial_method,
		'country'          => $alpine_initial_country,
		'serviceable'      => array(),
		'connectBase'      => '',
		'nopeTpl'          => '',
		'switchTo'         => '',
		'switchToLabel'    => '',
		'paidViaLabel'     => '',
		'switchTpl'        => '',
		'viaTpl'           => '',
		'deadEndMsg'       => '',
	),
	$affiliate_id
);
?>

<div
	id="affwp-affiliate-dashboard-profile"
	class="affwp-tab-content"
	x-data="<?php echo esc_attr( wp_json_encode( $payout_alpine ) ); ?>"
>

	<h4><?php esc_html_e( "How you'll be paid", 'affiliate-wp' ); ?></h4>

	<form id="affwp-affiliate-dashboard-profile-form" class="affwp-form" method="post">

		<?php if ( $picker_visible && function_exists( 'affwp_affiliate_area_render_payout_method_field' ) ) : ?>
			<?php affwp_affiliate_area_render_payout_method_field( $affiliate_id, $affiliate_user_id ); ?>
		<?php elseif ( '' !== $effective_method ) : ?>
			<p class="affwp-payout-method-status">
				<?php
				// Always names the effective method, including Manual.
				$affiliate_label = function_exists( 'affwp_get_payout_method_affiliate_label' )
					? affwp_get_payout_method_affiliate_label( $effective_method )
					: ucfirst( str_replace( array( '_', '-' ), ' ', $effective_method ) );

				echo esc_html( $affiliate_label ) . '.';
				?>
			</p>
		<?php endif; ?>

		<?php
		// Country sits after the method picker because it's a Stripe sub-question (the field reveals
		// only when Stripe is selected). When Stripe is the only method the picker is absent, so this
		// becomes the first field naturally.
		?>
		<?php if ( function_exists( 'affwp_affiliate_area_render_payout_country_field' ) ) : ?>
			<?php affwp_affiliate_area_render_payout_country_field( $affiliate_id, $affiliate_user_id ); ?>
		<?php endif; ?>

		<?php
		$store_credit_could_apply = ( 'store_credit' === $effective_method )
			|| ( $picker_visible && isset( $picker_methods['store_credit'] ) );

		if ( $store_credit_could_apply ) :
			$balance = '';
			if ( function_exists( '\AffiliateWP\Core\Payouts\Methods\StoreCredit\affwp_store_credit_balance' ) ) {
				$balance = (string) \AffiliateWP\Core\Payouts\Methods\StoreCredit\affwp_store_credit_balance( array( 'affiliate_id' => $affiliate_id ) );
			} elseif ( function_exists( 'affwp_store_credit_balance' ) ) {
				$balance = (string) affwp_store_credit_balance( array( 'affiliate_id' => $affiliate_id ) );
			}
			if ( '' !== $balance ) :
				?>
				<div
					class="affwp-payout-method-context affwp-payout-method-context--active"
					x-show="method === 'store_credit'"
					x-cloak
				>
					<span class="affwp-payout-method-context__heading">
						<?php esc_html_e( 'Store Credit', 'affiliate-wp' ); ?>
					</span>
					<p class="affwp-payout-method-context__detail">
						<?php
						printf(
							/* translators: %s: Formatted store credit balance (e.g. $42.00). */
							esc_html__( 'Available balance: %s', 'affiliate-wp' ),
							'<strong>' . esc_html( $balance ) . '</strong>'
						);
						?>
					</p>
				</div>
				<?php
			endif;
		endif;
		?>

		<?php
		/**
		 * Fires inside the affiliate area's "How you'll be paid" section, between the
		 * method status / picker and the per-method contextual fields (balance, email).
		 * Integrations like Stripe Payouts hook in here to render their method-specific
		 * status block.
		 *
		 * @since 2.33.0
		 *
		 * @param int $affiliate_id      Affiliate ID.
		 * @param int $affiliate_user_id User ID.
		 */
		do_action( 'affwp_affiliate_dashboard_payments_section', $affiliate_id, $affiliate_user_id );
		?>

		<?php if ( affwp_affiliate_needs_payment_email( $affiliate_id ) ) : ?>
			<?php
			$paypal_email_desc  = __( 'Payouts are sent to the email on your PayPal account.', 'affiliate-wp' );
			$manual_email_desc  = __( 'Your site admin will use this address to pay you.', 'affiliate-wp' );
			$generic_email_desc = __( 'Where your payouts will be sent.', 'affiliate-wp' );

			// Visibility follows affwp_get_payment_email_methods(), so any email-needing method reveals the field, not just paypal/manual.
			$email_x_show = affwp_payment_email_methods_alpine_condition( 'method' );
			?>
			<div
				class="affwp-wrap affwp-payment-email-wrap"
				<?php if ( '' !== $email_x_show ) : ?>
					x-show="<?php echo esc_attr( $email_x_show ); ?>"
					x-cloak
				<?php endif; ?>
			>
				<label for="affwp-payment-email"><?php _e( 'Your Payment Email', 'affiliate-wp' ); ?></label>
				<input id="affwp-payment-email" type="email" name="payment_email" value="<?php echo esc_attr( $payment_email ); ?>" />
				<p class="affwp-payment-email-desc description">
					<span x-show="method === 'paypal'" x-cloak><?php echo esc_html( $paypal_email_desc ); ?></span>
					<span x-show="method === 'manual'" x-cloak><?php echo esc_html( $manual_email_desc ); ?></span>
					<span x-show="method !== 'paypal' && method !== 'manual'" x-cloak><?php echo esc_html( $generic_email_desc ); ?></span>
				</p>
			</div>
		<?php endif; ?>

		<?php if ( affwp_email_referral_notifications( absint( $affiliate_id ) ) ) : ?>

			<h4><?php _e( 'Notification Settings', 'affiliate-wp' ); ?></h4>

			<div class="affwp-wrap affwp-send-notifications-wrap">
				<input id="affwp-referral-notifications" type="checkbox" name="referral_notifications" value="1" <?php checked( true, get_user_meta( $affiliate_user_id, 'affwp_referral_notifications', true ) ); ?>/>
				<label for="affwp-referral-notifications"><?php _e( 'Enable New Referral Notifications', 'affiliate-wp' ); ?></label>
			</div>
		<?php endif; ?>

		<?php
		/**
		 * Fires immediately prior to the profile submit button in the affiliate area.
		 *
		 * @since 1.0
		 *
		 * @param int    $affiliate_id      Affiliate ID.
		 * @param string $affiliate_user_id The user of the currently logged-in affiliate.
		 */
		do_action( 'affwp_affiliate_dashboard_before_submit', $affiliate_id, $affiliate_user_id ); ?>

		<div class="affwp-save-profile-wrap">
			<input type="hidden" name="affwp_action" value="update_profile_settings" />
			<input type="hidden" name="affiliate_id" value="<?php echo absint( $affiliate_id ); ?>" />
			<?php wp_nonce_field( 'affwp_update_profile_settings_nonce', 'affwp_update_profile_settings_nonce' ); ?>
			<input type="submit" class="button" value="<?php esc_attr_e( 'Save Profile Settings', 'affiliate-wp' ); ?>" />
		</div>

	</form>

	<?php
	$ps_could_apply = $picker_visible || ( 'payouts-service' === $effective_method );

	if ( affwp_is_payouts_service_enabled() && $ps_could_apply ) :
		?>
		<div
			id="affwp-affiliate-dashboard-payouts-service"
			class="affwp-tab-content"
			x-show="method === 'payouts-service'"
			x-cloak
		>
			<?php

			if ( isset( $payouts_service_meta['status'] ) && 'payout_method_added' === $payouts_service_meta['status'] ) {

				affiliate_wp()->templates->get_template_part( 'payouts/payout-method' );

			} elseif ( isset( $payouts_service_meta['status'] ) && 'account_created' === $payouts_service_meta['status'] ) {

				affiliate_wp()->templates->get_template_part( 'payouts/add-payout-method' );

			} else {

				affiliate_wp()->templates->get_template_part( 'payouts/register' );

			}

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

</div>
