<?php
/**
 * Subscription Management Widget - Render Methods
 *
 * @package GGM_Commerce
 */

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

/**
 * Render the premium widget content.
 *
 * @param \GGM_Commerce_Widget_Subscription_Management $widget The widget instance.
 */
function ggmc_subscription_management_render_premium_content( $widget ) {
	$settings = $widget->get_settings_for_display();

	if ( ! is_user_logged_in() ) {
		echo '<div class="ggmc-subscription-login-required">';
		echo '<p>' . esc_html( $settings['login_message'] ) . '</p>';
		echo '</div>';
		return;
	}

	$sub_manager   = GGM_Commerce_Subscriptions::instance();
	$sub_settings  = GGM_Commerce_Subscriptions::get_settings();
	$current_user  = wp_get_current_user();
	$subscriptions = $sub_manager->get_customer_subscriptions_by_email( $current_user->user_email );

	if ( empty( $subscriptions ) ) {
		echo '<div class="ggmc-subscription-empty">';
		echo '<p>' . esc_html( $settings['empty_message'] ) . '</p>';
		echo '</div>';
		return;
	}

	$statuses        = GGM_Commerce_Subscriptions::get_statuses();
	$billing_periods = GGM_Commerce_Subscriptions::get_billing_periods();
	$status_classes  = array(
		'active'         => 'ggmc-sub-active',
		'trial'          => 'ggmc-sub-trial',
		'paused'         => 'ggmc-sub-paused',
		'cancelled'      => 'ggmc-sub-cancelled',
		'on_hold'        => 'ggmc-sub-on-hold',
		'pending'        => 'ggmc-sub-pending',
		'expired'        => 'ggmc-sub-expired',
		'pending_cancel' => 'ggmc-sub-pending-cancel',
		'failed_payment' => 'ggmc-sub-failed',
	);

	$nonce = wp_create_nonce( 'ggmc_subscription_action' );

	echo '<div class="ggmc-subscription-list">';

	foreach ( $subscriptions as $sub ) {
		ggmc_subscription_management_render_card( $sub, $statuses, $billing_periods, $status_classes, $sub_settings, $nonce );
	}

	echo '</div>'; // .ggmc-subscription-list

	ggmc_subscription_management_render_inline_js();
}

/**
 * Render a single subscription card.
 *
 * @param object $sub            The subscription object.
 * @param array  $statuses       Map of status key => label.
 * @param array  $billing_periods Map of period key => label.
 * @param array  $status_classes  Map of status key => CSS class.
 * @param array  $sub_settings   Plugin subscription settings.
 * @param string $nonce          The action nonce.
 */
function ggmc_subscription_management_render_card( $sub, $statuses, $billing_periods, $status_classes, $sub_settings, $nonce ) {
	$status_class = $status_classes[ $sub->status ] ?? 'ggmc-sub-pending';
	$status_label = $statuses[ $sub->status ] ?? ucfirst( str_replace( '_', ' ', $sub->status ) );
	$period_label = $billing_periods[ $sub->billing_period ] ?? $sub->billing_period;

	$cycle_text = (int) $sub->billing_interval === 1
		? ggm_commerce_format_price( $sub->recurring_total ) . '/' . rtrim( $period_label, '(s)' )
		: ggm_commerce_format_price( $sub->recurring_total ) . ' every ' . (int) $sub->billing_interval . ' ' . $period_label;

	echo '<div class="ggmc-subscription-card" data-subscription-id="' . esc_attr( $sub->id ) . '">';

	// Header.
	echo '<div class="ggmc-subscription-card-header">';
	echo '<div class="ggmc-subscription-info">';
	echo '<span class="ggmc-subscription-number">#' . esc_html( $sub->subscription_number ) . '</span>';
	echo '<span class="ggmc-subscription-badge ' . esc_attr( $status_class ) . '">' . esc_html( $status_label ) . '</span>';
	echo '</div>';
	echo '<div class="ggmc-subscription-price">' . esc_html( $cycle_text ) . '</div>';
	echo '</div>';

	// Details.
	echo '<div class="ggmc-subscription-card-body">';

	// Product name.
	global $wpdb;
	// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
	$product = $wpdb->get_row( $wpdb->prepare(
		"SELECT name FROM {$wpdb->prefix}ggmc_products WHERE id = %d",
		$sub->product_id
	) );
	if ( $product ) {
		echo '<div class="ggmc-subscription-detail"><span class="ggmc-subscription-detail-label">' . esc_html__( 'Product', 'ggm-commerce' ) . ':</span> ' . esc_html( $product->name ) . '</div>';
	}

	// Next payment date.
	if ( ! empty( $sub->next_payment_date ) && '0000-00-00 00:00:00' !== $sub->next_payment_date && in_array( $sub->status, array( 'active', 'trial' ), true ) ) {
		echo '<div class="ggmc-subscription-detail"><span class="ggmc-subscription-detail-label">' . esc_html__( 'Next Payment', 'ggm-commerce' ) . ':</span> ' . esc_html( gmdate( 'M j, Y', strtotime( $sub->next_payment_date ) ) ) . '</div>';
	}

	echo '</div>';

	// Actions.
	$actions = array();

	if ( in_array( $sub->status, array( 'active', 'trial' ), true ) ) {
		if ( $sub_settings['allow_pause'] ) {
			$actions['pause'] = __( 'Pause', 'ggm-commerce' );
		}
		if ( $sub_settings['allow_cancel'] ) {
			$actions['cancel'] = __( 'Cancel', 'ggm-commerce' );
		}
	} elseif ( 'paused' === $sub->status ) {
		$actions['resume'] = __( 'Resume', 'ggm-commerce' );
		if ( $sub_settings['allow_cancel'] ) {
			$actions['cancel'] = __( 'Cancel', 'ggm-commerce' );
		}
	} elseif ( in_array( $sub->status, array( 'cancelled', 'expired' ), true ) && $sub_settings['allow_reactivate'] ) {
		$actions['reactivate'] = __( 'Reactivate', 'ggm-commerce' );
	}

	if ( ! empty( $actions ) ) {
		echo '<div class="ggmc-subscription-actions">';
		foreach ( $actions as $action_key => $action_label ) {
			$btn_class = 'cancel' === $action_key ? 'ggmc-btn-danger' : 'ggmc-btn-primary';
			$confirm   = 'cancel' === $action_key ? ' data-confirm="' . esc_attr__( 'Are you sure you want to cancel this subscription?', 'ggm-commerce' ) . '"' : '';
			printf(
				'<button type="button" class="ggmc-subscription-action-btn %s" data-action="%s" data-nonce="%s"%s>%s</button>',
				esc_attr( $btn_class ),
				esc_attr( $action_key ),
				esc_attr( $nonce ),
				$confirm, // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- already escaped with esc_attr__() above or empty string
				esc_html( $action_label )
			);
		}
		echo '</div>';
	}

	echo '</div>'; // .ggmc-subscription-card
}

/**
 * Render the inline JS for subscription action buttons.
 */
function ggmc_subscription_management_render_inline_js() {
	?>
	<script>
	(function() {
		document.querySelectorAll('.ggmc-subscription-action-btn').forEach(function(btn) {
			btn.addEventListener('click', function(e) {
				var confirmMsg = this.getAttribute('data-confirm');
				if (confirmMsg && !confirm(confirmMsg)) return;

				var card = this.closest('.ggmc-subscription-card');
				var subId = card.getAttribute('data-subscription-id');
				var action = this.getAttribute('data-action');
				var nonce = this.getAttribute('data-nonce');

				this.disabled = true;
				this.textContent = '...';

				var data = new FormData();
				data.append('action', 'ggmc_customer_subscription_action');
				data.append('subscription_id', subId);
				data.append('subscription_action', action);
				data.append('nonce', nonce);

				fetch('<?php echo esc_url( admin_url( 'admin-ajax.php' ) ); ?>', {
					method: 'POST',
					body: data,
					credentials: 'same-origin'
				})
				.then(function(r) { return r.json(); })
				.then(function(resp) {
					if (resp.success) {
						location.reload();
					} else {
						alert(resp.data && resp.data.message ? resp.data.message : 'An error occurred.');
						btn.disabled = false;
						btn.textContent = action.charAt(0).toUpperCase() + action.slice(1);
					}
				})
				.catch(function() {
					alert('An error occurred. Please try again.');
					btn.disabled = false;
				});
			});
		});
	})();
	</script>
	<?php
}
