<?php
/**
 * 3.7.4 product-recovery admin notice.
 *
 * Renders ONCE after the 3.7.4 migration runs, summarising what was recovered
 * from the transfer log and which orders couldn't be auto-recovered. The
 * notice is dismissible; dismissing it clears the flag and the option
 * `bsd_split_pay_374_recovery_stats` is retained for forensic reference.
 *
 * The merchant can re-surface the notice via wp-admin URL:
 *   admin.php?page=bsd-split-pay-stripe-connect-woo-settings&spp_show_374_recovery=1
 *
 * @since 3.7.4
 * @package BSD_Split_Pay_Stripe_Connect_Woo
 */

namespace BSD_Split_Pay_Stripe_Connect_Woo\Inc\Admin;

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

add_action( 'admin_notices', __NAMESPACE__ . '\\spp_374_render_recovery_notice' );
add_action( 'admin_init',    __NAMESPACE__ . '\\spp_374_handle_recovery_notice_dismiss' );

/**
 * Render the recovery summary once. Capability-gated to manage_options so we
 * don't leak product-level information to lower-role users.
 *
 * @return void
 */
function spp_374_render_recovery_notice(): void {
	if ( ! current_user_can( 'manage_options' ) ) {
		return;
	}

	$flag = get_option( 'bsd_split_pay_374_recovery_notice' );

	// Allow manual re-surface via querystring for support purposes.
	$force = ! empty( $_GET['spp_show_374_recovery'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended

	if ( ! $flag && ! $force ) {
		return;
	}

	$stats = get_option( 'bsd_split_pay_374_recovery_stats' );
	if ( ! is_array( $stats ) ) {
		return;
	}

	$recovered     = (int) ( $stats['products_recovered'] ?? 0 );
	$already       = (int) ( $stats['products_already_had_data'] ?? 0 );
	$scanned       = (int) ( $stats['orders_scanned'] ?? 0 );
	$unrecoverable = is_array( $stats['unrecoverable_orders'] ?? null ) ? count( $stats['unrecoverable_orders'] ) : 0;
	$products      = is_array( $stats['recovered_products'] ?? null ) ? $stats['recovered_products'] : [];

	$class = ( $recovered > 0 || $unrecoverable > 0 ) ? 'notice notice-warning is-dismissible' : 'notice notice-info is-dismissible';

	$dismiss_url = wp_nonce_url(
		add_query_arg( 'spp_374_recovery_dismiss', '1', admin_url( 'admin.php?page=bsd-split-pay-stripe-connect-woo-settings' ) ),
		'spp_374_recovery_dismiss',
		'_spp_nonce'
	);

	// 3.7.5 (PT-7): data-spp-persist-dismiss lets the admin JS persist the
	// native "X" click via AJAX (delete the visibility option) rather than
	// only hiding the DOM until refresh.
	echo '<div class="' . esc_attr( $class ) . '" data-spp-374-recovery="1" data-spp-persist-dismiss="bsd_split_pay_374_recovery_notice">';
	echo '<p><strong>' . esc_html__( 'Split Pay 3.7.4 product settings recovery', 'bsd-split-pay-stripe-connect-woo' ) . '</strong></p>';

	if ( $recovered > 0 ) {
		echo '<p>';
		printf(
			/* translators: 1: number of products recovered, 2: number of orders scanned */
			esc_html( _n(
				'Recovered Split Pay settings for %1$d product after scanning %2$d order. The vendor + percentage/amount values were reconstructed from the most recent successful Stripe transfer for each product.',
				'Recovered Split Pay settings for %1$d products after scanning %2$d orders. The vendor + percentage/amount values were reconstructed from the most recent successful Stripe transfer for each product.',
				$recovered,
				'bsd-split-pay-stripe-connect-woo'
			) ),
			(int) $recovered,
			(int) $scanned
		);
		echo '</p>';

		if ( ! empty( $products ) ) {
			$preview = array_slice( $products, 0, 10 );
			$links   = [];
			foreach ( $preview as $pid ) {
				$pid   = (int) $pid;
				$title = get_the_title( $pid );
				if ( ! $title ) { $title = '#' . $pid; }
				$links[] = '<a href="' . esc_url( get_edit_post_link( $pid ) ) . '">' . esc_html( $title ) . '</a>';
			}
			echo '<p><em>' . esc_html__( 'Sample of recovered products:', 'bsd-split-pay-stripe-connect-woo' ) . '</em> ' . wp_kses_post( implode( ', ', $links ) );
			if ( count( $products ) > count( $preview ) ) {
				echo ' ' . esc_html( sprintf(
					/* translators: %d: remaining count */
					__( '… and %d more.', 'bsd-split-pay-stripe-connect-woo' ),
					count( $products ) - count( $preview )
				) );
			}
			echo '</p>';
		}

		echo '<p>' . esc_html__( 'Each recovered product has a `_bsd_spscwt_pre_374_state` snapshot meta saved so the original (empty) state can be inspected, and a `_bsd_spscwt_recovered_in_374` marker recording which order was used as the recovery source. Please spot-check the affected products before processing new orders.', 'bsd-split-pay-stripe-connect-woo' ) . '</p>';
	} else {
		echo '<p>' . esc_html__( 'No Split Pay product settings needed recovery on this site. Either all products still have their saved vendor + percentage/amount, or the transfer log has no historical data to reconstruct from.', 'bsd-split-pay-stripe-connect-woo' ) . '</p>';
	}

	if ( $already > 0 ) {
		echo '<p>';
		printf(
			/* translators: %d: number of products skipped because they already had data */
			esc_html__( '%d products were skipped because they already had a saved vendor — recovery never overwrites existing configuration.', 'bsd-split-pay-stripe-connect-woo' ),
			(int) $already
		);
		echo '</p>';
	}

	if ( $unrecoverable > 0 ) {
		echo '<p><strong>' . esc_html(
			sprintf(
				/* translators: %d: number of orders that could not be auto-recovered */
				_n(
					'%d order had multiple products routing to multiple destinations — those products could not be auto-recovered.',
					'%d orders had multiple products routing to multiple destinations — those products could not be auto-recovered.',
					$unrecoverable,
					'bsd-split-pay-stripe-connect-woo'
				),
				$unrecoverable
			)
		) . '</strong> ' . esc_html__( 'Please review them manually using the Transfers tab and re-enter the vendor on those product Split Pay tabs as needed.', 'bsd-split-pay-stripe-connect-woo' ) . '</p>';
	}

	echo '<p><a href="' . esc_url( $dismiss_url ) . '" class="button button-secondary">' . esc_html__( 'Dismiss this notice', 'bsd-split-pay-stripe-connect-woo' ) . '</a></p>';
	echo '</div>';
}

/**
 * Handle the dismiss click. Clears the visibility flag but preserves the
 * stats option for later inspection.
 *
 * @return void
 */
function spp_374_handle_recovery_notice_dismiss(): void {
	if ( empty( $_GET['spp_374_recovery_dismiss'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		return;
	}

	if ( ! current_user_can( 'manage_options' ) ) {
		return;
	}

	if ( ! isset( $_GET['_spp_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_spp_nonce'] ) ), 'spp_374_recovery_dismiss' ) ) {
		return;
	}

	delete_option( 'bsd_split_pay_374_recovery_notice' );
	wp_safe_redirect( remove_query_arg( [ 'spp_374_recovery_dismiss', '_spp_nonce' ] ) );
	exit;
}
