<?php
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound

/**
 * Subscription mandate.
 *
 * @author    Wpayme <hi@wpayme.com>
 * @copyright 2024-2025 Wpayme
 * @license   GPL-3.0-or-later
 * @package   Wpayme\WordPress\Pay
 */

use Wpayme\WordPress\Pay\Cards;
use Wpayme\WordPress\Pay\Core\PaymentMethods;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

if ( ! isset( $subscription ) ) {
	return;
}

if ( ! isset( $gateway ) ) {
	return;
}

if ( ! class_exists( '\Wpayme\WordPress\Mollie\Client' ) ) {
	return;
}

$wpayme_pay_mollie_customer_id = $subscription->get_meta( 'mollie_customer_id' );

if ( empty( $wpayme_pay_mollie_customer_id ) ) {
	include \get_404_template();

	exit;
}

$wpayme_pay_api_key = \get_post_meta( $subscription->config_id, '_wpayme_gateway_mollie_api_key', true );

$wpayme_pay_client = new \Wpayme\WordPress\Mollie\Client( $wpayme_pay_api_key );

/**
 * Mandates.
 *
 * @link https://docs.mollie.com/reference/v2/mandates-api/list-mandates
 */
$wpayme_pay_mollie_customer_mandates = [];

// phpcs:disable Generic.CodeAnalysis.EmptyStatement.DetectedCatch

try {
	$wpayme_pay_response = $wpayme_pay_client->get_mandates( $wpayme_pay_mollie_customer_id );

	if (
		property_exists( $wpayme_pay_response, '_embedded' )
			&&
		property_exists( $wpayme_pay_response->_embedded, 'mandates' )
	) {
		$wpayme_pay_mollie_customer_mandates = $wpayme_pay_response->_embedded->mandates;
	}
} catch ( \Exception $wpayme_pay_exception ) {
	/**
	 * Nothing to do.
	 *
	 * Retrieval of customer mandates could fail for example when the configuration
	 * has changed and the customer is invalid now. We cannot retrieve mandates, but
	 * it should still be possible to add a new payment method to the subscription.
	 */
}

// phpcs:enable Generic.CodeAnalysis.EmptyStatement.DetectedCatch

$wpayme_pay_subscription_mandate_id = $subscription->get_meta( 'mollie_mandate_id' );

// Set current subscription mandate as first item.
$wpayme_pay_current_mandate = wp_list_filter( $wpayme_pay_mollie_customer_mandates, [ 'id' => $wpayme_pay_subscription_mandate_id ] );

if ( is_array( $wpayme_pay_current_mandate ) ) {
	unset( $wpayme_pay_mollie_customer_mandates[ key( $wpayme_pay_current_mandate ) ] );

	$wpayme_pay_mollie_customer_mandates = array_merge( $wpayme_pay_current_mandate, $wpayme_pay_mollie_customer_mandates );
}

?>
<!DOCTYPE html>

<html <?php language_attributes(); ?>>
	<head>
		<meta charset="<?php bloginfo( 'charset' ); ?>" />

		<meta name="viewport" content="width=device-width, initial-scale=1.0">

		<title><?php esc_html_e( 'Change subscription payment method', 'wpayme' ); ?></title>

		<?php wp_print_styles( 'wpayme-pay-subscription-mandate' ); ?>
	</head>

	<body>
		<div class="wpayme-pay-redirect-page">
			<div class="wpayme-pay-redirect-container">

				<h1>
					<?php \esc_html_e( 'Change subscription payment method', 'wpayme' ); ?>
				</h1>

				<?php if ( count( $mollie_customer_mandates ) > 0 ) : ?>

					<p>
						<?php \esc_html_e( 'Select an existing payment method or add a new one.', 'wpayme' ); ?>
					</p>

					<div class="pp-card-slider-container">
						<div class="pp-card-slider-wrapper">
							<form method="post">
								<h2>
									<?php \esc_html_e( 'Select existing payment method', 'wpayme' ); ?>
								</h2>

								<div class="pp-card-slider alignleft">
									<?php

									$cards = new Cards();

									foreach ( $mollie_customer_mandates as $mandate ) :
										if ( 'valid' !== $mandate->status ) {
											continue;
										}

										$card_name      = '';
										$account_number = null;
										$account_label  = null;
										$bic_or_brand   = null;
										$logo_url       = null;

										switch ( $mandate->method ) {
											case 'creditcard':
												$card_name      = $mandate->details->cardHolder;
												$account_number = str_pad( $mandate->details->cardNumber, 16, '*', \STR_PAD_LEFT );
												$account_label  = _x( 'Card Number', 'Card selector', 'wpayme' );

												$bic_or_brand = $mandate->details->cardLabel;

												break;
											case 'directdebit':
												$card_name      = $mandate->details->consumerName;
												$account_number = $mandate->details->consumerAccount;
												$account_label  = _x( 'Account Number', 'Card selector', 'wpayme' );

												$bic_or_brand = substr( $mandate->details->consumerAccount, 4, 4 );

												break;
										}

										// Split account number in chunks.
										if ( null !== $account_number ) {
											$account_number = \chunk_split( $account_number, 4, ' ' );
										}

										$card_title = '';

										$classes = [ 'pp-card' ];

										$bg_color = 'purple';

										$card = $cards->get_card( $bic_or_brand );

										// Set card brand specific details.
										if ( null !== $card ) {
											$card_title = $card['title'];

											$classes[] = 'brand-' . $card['brand'];

											$logo_url = $cards->get_card_logo_url( $card['brand'] );

											$bg_color = 'transparent';
										}

										?>

										<div class="pp-card-container">
											<div class="<?php echo esc_attr( implode( ' ', $classes ) ); ?>" style="background: <?php echo \esc_attr( $bg_color ); ?>;">
												<div class="pp-card__background"></div>

												<div class="pp-card__content">
													<input class="pp-card__input" name="wpayme_pay_subscription_mandate" value="<?php echo esc_attr( $mandate->id ); ?>" type="radio" />

													<div class="pt-card__indicator"></div>

													<h3 class="pp-card__title"><?php echo esc_html( $card_title ); ?></h3>

													<figure class="pp-card__logo">
														<?php if ( null !== $logo_url ) : ?>

															<img class="pp-card__logo__img" src="<?php echo esc_url( $logo_url ); ?>" alt="<?php echo esc_attr( $card_title ); ?>" />

														<?php endif; ?>
													</figure>

													<dl class="pp-card__name">
														<dt class="pp-card__label"><?php echo esc_html_x( 'Name', 'Card selector', 'wpayme' ); ?></dt>
														<dd class="pp-card__value"><?php echo esc_html( $card_name ); ?></dd>
													</dl>

													<dl class="pp-card__number">
														<dt class="pp-card__label"><?php echo esc_html( (string) $account_label ); ?></dt>
														<dd class="pp-card__value"><?php echo esc_html( (string) $account_number ); ?></dd>
													</dl>
												</div>
											</div>
										</div>

									<?php endforeach; ?>

								</div>

								<p>
									<?php wp_nonce_field( 'wpayme_pay_update_subscription_mandate', 'wpayme_pay_nonce' ); ?>

									<input type="submit" value="<?php esc_attr_e( 'Use selected payment method', 'wpayme' ); ?>" />
								</p>
							</form>
						</div>
					</div>

				<?php endif; ?>

				<div class="pp-new-payment-method-container">
					<div class="pp-new-payment-method-wrapper">
						<form method="post">
							<h2>
								<?php \esc_html_e( 'Add new payment method', 'wpayme' ); ?>
							</h2>

							<label>
								<p>
									<?php esc_html_e( 'Select payment method for verification payment.', 'wpayme' ); ?>
								</p>

								<select name="wpayme_pay_subscription_payment_method">
									<?php

									$wpayme_pay_payment_methods = $gateway->get_payment_methods(
										[
											'status'   => [ '', 'active' ],
											'supports' => 'recurring',
										]
									);

									/*
									 * Filter out payment methods with required fields,
									 * as these are not supported for now.
									 *
									 * @link https://github.com/wpayme/wp-wpayme-pay/issues/361
									 */
									$wpayme_pay_payment_methods = array_filter(
										$wpayme_pay_payment_methods->get_array(),
										function ( $wpayme_pay_payment_method ) {
											$wpayme_pay_required_fields = array_filter(
												$wpayme_pay_payment_method->get_fields(),
												function ( $wpayme_pay_field ) {
													return $wpayme_pay_field->is_required();
												}
											);

											return 0 === count( $wpayme_pay_required_fields );
										}
									);

									foreach ( $wpayme_pay_payment_methods as $wpayme_pay_payment_method ) {
										$wpayme_pay_payment_method_id = $wpayme_pay_payment_method->get_id();

										$wpayme_pay_name = $wpayme_pay_payment_method->get_name();
										$wpayme_pay_name = ( '' === $wpayme_pay_name ) ? $wpayme_pay_payment_method_id : $wpayme_pay_name;

										printf(
											'<option value="%s">%s</option>',
											esc_attr( $wpayme_pay_payment_method_id ),
											esc_html( $wpayme_pay_name )
										);
									}

									?>
								</select>
							</label>

							<p>
								<?php wp_nonce_field( 'wpayme_pay_update_subscription_mandate', 'wpayme_pay_nonce' ); ?>

								<input type="submit" value="<?php esc_attr_e( 'Pay', 'wpayme' ); ?>" />
							</p>
						</form>
					</div>
				</div>
			</div>
		</div>

		<?php wp_print_scripts( 'wpayme-pay-subscription-mandate' ); ?>
	</body>
</html>
