<?php

namespace BSD_Split_Pay_Stripe_Connect_Woo\Inc\Admin;

defined( 'ABSPATH' ) || exit;

/**
 * Backfill stripe_mode and date_created for transfer-log rows written by the
 * 3.7.0/3.7.1/3.7.2 namespaced TransferEngine.
 *
 * Symptom (Michael Burgess, sc-7168, May 17 2026): Transfers admin tab was
 * empty even though Stripe-side transfers had succeeded. Root cause: the
 * namespaced TransferEngine::recordResult() omitted stripe_mode (and other
 * audit columns) from its insert payload. The Transfers tab filters
 * WHERE stripe_mode = %s — rows with NULL stripe_mode were invisible.
 *
 * This migration:
 *   1. Updates any row with NULL/empty stripe_mode to the current site's
 *      Stripe mode ('test' or 'live'), derived from the WC Stripe gateway
 *      settings. This is best-effort; rows from a prior different mode will
 *      be tagged with the current mode. The alternative (leaving them
 *      invisible) is worse — merchants asked for reconciliation visibility,
 *      not perfect historical mode attribution.
 *   2. Stamps NULL/'0000-00-00 00:00:00' date_created with the current time
 *      so the Transfers tab ORDER BY date_created DESC actually orders.
 *
 * @since 3.7.3
 */
if ( ! function_exists( __NAMESPACE__ . '\\db_migration_373' ) ) {
	function db_migration_373( $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;
			}

			/*
			 * Defensive column-add. The legacy integration_source + source_order_id
			 * columns are normally added by BSD_SCA::update_log_table_integration_source()
			 * on the `plugins_loaded` hook, BUT only when WC + a Stripe gateway plugin
			 * are both active (see bsd_scsp_check_requirements()). On sites that
			 * activated SPP before activating their Stripe gateway — or on
			 * WC-only test/dev installs — those columns can be missing.
			 *
			 * The 3.7.0+ namespaced TransferLogger::logTransfer() ALWAYS includes
			 * 'integration_source' in its insert payload (default 'woocommerce'),
			 * so a missing column silently broke every transfer-log insert with
			 * `Unknown column 'integration_source' in 'field list'`. Pair that
			 * with the silent-swallow bug we just fixed in TransferLogger and
			 * you get Michael Burgess's empty Transfers tab AND a class of
			 * fresh-install regressions.
			 *
			 * Adding the columns here makes the migration controller (which
			 * runs on every `init`, independent of which gateways are active)
			 * the single source of truth for this schema.
			 */
			$columns = $wpdb->get_col( "SHOW COLUMNS FROM {$table}", 0 );
			$columns = is_array( $columns ) ? array_map( 'strval', $columns ) : [];

			if ( ! in_array( 'integration_source', $columns, true ) ) {
				$wpdb->query( "ALTER TABLE {$table} ADD COLUMN `integration_source` VARCHAR(30) DEFAULT 'woocommerce' NOT NULL" );
			}
			if ( ! in_array( 'source_order_id', $columns, true ) ) {
				$wpdb->query( "ALTER TABLE {$table} ADD COLUMN `source_order_id` VARCHAR(50) DEFAULT NULL" );
			}

			$settings = get_option( 'woocommerce_stripe_settings' );
			$mode     = ( is_array( $settings ) && isset( $settings['testmode'] ) && $settings['testmode'] === 'yes' )
				? 'test'
				: 'live';

			$now = current_time( 'mysql', true );

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

			$wpdb->query( $wpdb->prepare(
				"UPDATE {$table} SET date_created = %s WHERE date_created IS NULL OR date_created = '0000-00-00 00:00:00'",
				$now
			) );

			$wpdb->query( $wpdb->prepare(
				"UPDATE {$table} SET date_modified = %s WHERE date_modified IS NULL OR date_modified = '0000-00-00 00:00:00'",
				$now
			) );

			// Set the legacy migration's option marker so the plugins_loaded
			// hook doesn't try to re-run its ALTER (which would noop, but the
			// duplicate work is wasteful + the legacy code's $wpdb->query call
			// isn't wrapped in IF NOT EXISTS).
			update_option( 'bsd_log_table_integration_source', '1.0' );

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

			return false;
		}
	}
}
