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

/**
 * Meta Box Subscription Payments
 *
 * @author    Wpayme <hi@wpayme.com>
 * @copyright 2024-2025 Wpayme
 * @license   GPL-3.0-or-later
 * @package   Wpayme\WordPress\Pay
 * @var \Wpayme\WordPress\Pay\Plugin $plugin Plugin.
 * @var \Wpayme\WordPress\Pay\Subscriptions\Subscription $subscription Subscription.
 */

use Wpayme\WordPress\Pay\Payments\PaymentStatus;
use Wpayme\WordPress\Pay\Plugin;
use Wpayme\WordPress\Pay\Subscriptions\SubscriptionStatus;

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

$wpayme_subscription_id = $subscription->get_id();

if ( null === $wpayme_subscription_id ) {
	return;
}

$wpayme_payments = $subscription->get_payments();

$wpayme_data = [];

foreach ( $wpayme_payments as $payment ) {
	$wpayme_periods = (array) $payment->get_periods();

	/**
	 * A payment can be for multiple and different subscription periods.
	 * Here we only want to show the periods of this subscription and
	 * therefore we filter out other periods.
	 */
	$wpayme_periods = \array_filter(
		$wpayme_periods,
		function ( $wpayme_period ) use ( $subscription ) {
			return ( $subscription->get_id() === $wpayme_period->get_phase()->get_subscription()->get_id() );
		}
	);

	if ( 0 === count( $wpayme_periods ) ) {
		$wpayme_key = 'payment-' . $payment->get_id();

		$wpayme_data[ $wpayme_key ] = (object) [
			'date'     => $payment->get_date(),
			'payments' => [ $payment ],
			'period'   => null,
		];
	}

	foreach ( $wpayme_periods as $wpayme_period ) {
		$wpayme_key = 'period-' . $wpayme_period->get_start_date()->getTimestamp();

		if ( ! array_key_exists( $wpayme_key, $wpayme_data ) ) {
			$wpayme_data[ $wpayme_key ] = (object) [
				'date'     => $payment->get_date(),
				'payments' => [],
				'period'   => $wpayme_period,
			];
		}

		$wpayme_data[ $wpayme_key ]->payments[] = $payment;
	}
}

foreach ( $wpayme_data as $wpayme_item ) {
	usort(
		$wpayme_item->payments,
		function ( $a, $b ) {
			return $a->get_date() <=> $b->get_date();
		}
	);

	$wpayme_item->first = reset( $wpayme_item->payments );

	if ( false !== $wpayme_item->first ) {
		$wpayme_item->date = $wpayme_item->first->get_date();
	}

	$wpayme_statuses = array_map(
		function ( $payment ) {
			return $payment->get_status();
		},
		$wpayme_item->payments
	);

	$wpayme_item->can_retry = ! ( in_array( PaymentStatus::OPEN, $wpayme_statuses, true ) || in_array( PaymentStatus::SUCCESS, $wpayme_statuses, true ) );
}

usort(
	$wpayme_data,
	function ( $a, $b ) {
		return $b->date <=> $a->date;
	}
);

if ( 0 === count( $wpayme_payments ) ) : ?>

	<?php esc_html_e( 'No payments found.', 'wpayme' ); ?>

<?php else : ?>

	<table class="wpayme-pay-table widefat">
		<thead>
			<tr>
				<th scope="col">
					<span class="wpayme-pay-tip wpayme-pay-icon wpayme-pay-status" title="<?php esc_attr_e( 'Status', 'wpayme' ); ?>"><?php esc_html_e( 'Status', 'wpayme' ); ?></span>
				</th>
				<th scope="col"><?php esc_html_e( 'Period', 'wpayme' ); ?></th>
				<th scope="col"><?php esc_html_e( 'Payment', 'wpayme' ); ?></th>
				<th scope="col"><?php esc_html_e( 'Transaction', 'wpayme' ); ?></th>
				<th scope="col"><?php esc_html_e( 'Amount', 'wpayme' ); ?></th>
				<th scope="col"><?php esc_html_e( 'Date', 'wpayme' ); ?></th>
			</tr>
		</thead>

		<tbody>

			<?php

			$wpayme_next_payment_date = $subscription->get_next_payment_date();

			$wpayme_next_payment_delivery_date = $subscription->get_next_payment_delivery_date();

			$wpayme_next_period = $subscription->get_next_period();

			$wpayme_gateway = Plugin::get_gateway( (int) $subscription->get_config_id() );

			$wpayme_allow_next_period_statuses = [ SubscriptionStatus::OPEN, SubscriptionStatus::ACTIVE, SubscriptionStatus::FAILURE ];

			if ( null !== $wpayme_next_period && \in_array( $subscription->get_status(), $wpayme_allow_next_period_statuses, true ) && null !== $wpayme_gateway && $wpayme_gateway->supports( 'recurring' ) ) :

				?>

				<tr>
					<td>&nbsp;</td>
					<td><?php echo \esc_html( $wpayme_next_period->human_readable_range() ); ?></td>
					<td colspan="2">
						<?php

						if ( in_array( $subscription->get_source(), [ 'woocommerce' ], true ) && null !== $wpayme_next_payment_date ) :

							echo wp_kses_post(
								sprintf(
									/* translators: %s: next payment date */
									__( 'Will be created on %s', 'wpayme' ),
									\esc_html( $wpayme_next_payment_date->format_i18n( __( 'D j M Y', 'wpayme' ) ) )
								)
							);

						elseif ( null !== $wpayme_next_payment_delivery_date ) :

							$wpayme_create_next_payment_url = \wp_nonce_url(
								\add_query_arg(
									\urlencode_deep(
										[
											'period_payment' => true,
											'subscription_id' => $subscription->get_id(),
											'sequence_number' => $wpayme_next_period->get_phase()->get_sequence_number(),
											'start_date' => $wpayme_next_period->get_start_date()->format( DATE_ATOM ),
											'end_date'   => $wpayme_next_period->get_end_date()->format( DATE_ATOM ),
										]
									),
									\get_edit_post_link( $wpayme_subscription_id )
								),
								'wpayme_period_payment_' . $subscription->get_id()
							);

							echo wp_kses_post(
								sprintf(
									/* translators: 1: next payment delivery date, 2: create next period payment anchor */
									__( 'Will be created on %1$s or %2$s', 'wpayme' ),
									\esc_html( $wpayme_next_payment_delivery_date->format_i18n( __( 'D j M Y', 'wpayme' ) ) ),
									\sprintf(
										'<a href="%1$s">%2$s</a>',
										\esc_url( $wpayme_create_next_payment_url ),
										\esc_html( \__( 'create now', 'wpayme' ) )
									)
								)
							);

						endif;

						?>
					</td>
					<td><?php echo \esc_html( $wpayme_next_period->get_amount()->format_i18n() ); ?></td>
					<td>—</td>
				</tr>

				<?php

			endif;

			foreach ( $wpayme_data as $wpayme_item ) :
				foreach ( $wpayme_item->payments as $payment ) :
					$wpayme_payment_id         = $payment->get_id();
					$wpayme_payments_post_type = get_post_type( $wpayme_payment_id );

					?>

					<tr>
						<td>
							<?php
							// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
							do_action( 'manage_' . $wpayme_payments_post_type . '_posts_custom_column', 'wpayme_payment_status', $wpayme_payment_id );
							?>
						</td>
						<td>
							<?php

							if ( null !== $wpayme_item->period ) :
								$wpayme_prefix = ( $payment === $wpayme_item->first ? '' : '⌙ ' );

								echo esc_html( $wpayme_prefix . $wpayme_item->period->human_readable_range() );

							endif;

							?>
						</td>
						<td>
							<?php
							// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
							do_action( 'manage_' . $wpayme_payments_post_type . '_posts_custom_column', 'wpayme_payment_title', $wpayme_payment_id );
							?>
						</td>
						<td>
							<?php
							// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
							do_action( 'manage_' . $wpayme_payments_post_type . '_posts_custom_column', 'wpayme_payment_transaction', $wpayme_payment_id );
							?>
						</td>
						<td>
							<?php
							// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
							do_action( 'manage_' . $wpayme_payments_post_type . '_posts_custom_column', 'wpayme_payment_amount', $wpayme_payment_id );
							?>
						</td>
						<td>
							<?php
							// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
							do_action( 'manage_' . $wpayme_payments_post_type . '_posts_custom_column', 'wpayme_payment_date', $wpayme_payment_id );
							?>
						</td>
					</tr>

					<?php if ( null !== $wpayme_item->period && $payment === $wpayme_item->first && $wpayme_item->can_retry && $plugin->subscriptions_module->can_retry_payment( $payment ) ) : ?>

						<tr>
							<td>&nbsp;</td>
							<td colspan="6">
								<?php

								$wpayme_action_url = \wp_nonce_url(
									\add_query_arg(
										\urlencode_deep(
											[
												'period_payment' => true,
												'subscription_id' => $subscription->get_id(),
												'sequence_number' => $wpayme_item->period->get_phase()->get_sequence_number(),
												'start_date' => $wpayme_item->period->get_start_date()->format( DATE_ATOM ),
												'end_date' => $wpayme_item->period->get_end_date()->format( DATE_ATOM ),
											]
										),
										\get_edit_post_link( $wpayme_subscription_id )
									),
									'wpayme_period_payment_' . $subscription->get_id()
								);

								\printf(
									'<p><a class="button" href="%s">%s</a></p>',
									\esc_url( $wpayme_action_url ),
									\esc_html(
										sprintf(
											/* translators: %d: payment ID */
											__( 'Retry payment #%d', 'wpayme' ),
											$wpayme_payment_id
										)
									)
								);

								?>
							</td>
						</tr>

					<?php endif; ?>

				<?php endforeach; ?>

			<?php endforeach; ?>

		</tbody>
	</table>

<?php endif; ?>
