<?php

namespace BSD_Split_Pay_Stripe_Connect_Woo\Inc\Admin;

defined( 'ABSPATH' ) || exit;

/**
 * Reconcile transfer-log stripe_mode with the active gateway (Payment Plugins
 * vs official WooCommerce Stripe).
 *
 * Symptom (Vanessa Provs / profplaza.nl, May 21 2026): Transfers succeeded in
 * Stripe but the Transfers tab stayed empty on 3.7.4. Rows were often logged
 * with stripe_mode=test (webhook livemode / PP test checkout) while the tab
 * queried live from woocommerce_stripe_settings only.
 *
 * This migration re-stamps NULL/empty rows and rows whose mode differs from
 * TransferLogger::resolveStripeMode() so the admin list and writes agree.
 *
 * @since 3.7.4 (second hotfix)
 */
if ( ! function_exists( __NAMESPACE__ . '\\db_migration_375' ) ) {
	function db_migration_375( $table_prefix ) {
		try {
			global $wpdb;

			$table = $table_prefix . 'bsd_scsp_transfer_log';

			if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) ) !== $table ) {
				return true;
			}

			$mode = 'live';
			if ( class_exists( '\SplitPay\Core\TransferLogger' ) ) {
				$mode = \SplitPay\Core\TransferLogger::resolveStripeMode();
			} else {
				$pp_settings = get_option( 'woocommerce_stripe_api_settings' );
				if ( is_array( $pp_settings ) && ! empty( $pp_settings['mode'] ) ) {
					$mode = ( $pp_settings['mode'] === 'test' ) ? 'test' : 'live';
				} else {
					$settings = get_option( 'woocommerce_stripe_settings' );
					if ( is_array( $settings ) && isset( $settings['testmode'] ) && $settings['testmode'] === 'yes' ) {
						$mode = 'test';
					}
				}
			}

			$wpdb->query(
				$wpdb->prepare(
					"UPDATE {$table} SET stripe_mode = %s WHERE stripe_mode IS NULL OR stripe_mode = ''",
					$mode
				)
			);

			// PT-fix-3.7.5 (security #11A): the original migration RELABELED
			// rows from the opposite mode → resolved mode when visible_count
			// was zero. Combined with resolveStripeMode's WC-settings-based
			// guess being wrong on sk_test sites whose WC settings say live,
			// this PERMANENTLY corrupted historical data: real-test rows got
			// relabeled live (or vice versa) and the sentinel option blocked
			// the migration from re-running to fix it. IRREVERSIBLE.
			//
			// New behaviour: re-stamp ONLY rows where stripe_mode is NULL
			// or empty string (those have no authoritative source tag, so
			// using the migration-time resolved mode is the best we can do).
			// Rows that already have a 'test' or 'live' tag are AUTHORITATIVE
			// — they were stamped at write-time when we knew the actual
			// gateway mode. The Transfers tab is the read-time consumer
			// that needed fixing, not the write-time data — and that read-time
			// fix is now to surface BOTH modes via the tab's filter UI
			// rather than silently rewriting history.
			$wpdb->query(
				"UPDATE `{$table}` SET stripe_mode = 'test' WHERE stripe_mode IS NULL OR stripe_mode = ''"
					. " AND (charge_id LIKE 'ch_test_%' OR transfer_id LIKE 'tr_test_%')"
			);
			$wpdb->query(
				"UPDATE `{$table}` SET stripe_mode = 'live' WHERE stripe_mode IS NULL OR stripe_mode = ''"
			);

			update_option( 'bsd_split_pay_375_reconciled_stripe_mode', $mode );

			return true;
		} catch ( \Exception $e ) {
			error_log( '[BSD Split Pay] Error executing database migration: ' . __FUNCTION__ . ' — ' . $e->getMessage() );

			return false;
		}
	}
}
