<?php

namespace BSD_Split_Pay_Stripe_Connect_Woo\Inc\Admin;

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


if ( ! class_exists( 'BSD_Split_Pay_Stripe_Connect_Woo_Plugin_Updates' ) ) :

	class BSD_Split_Pay_Stripe_Connect_Woo_Plugin_Updates {

		private $option;

		private $options = [];

		public function __construct() {
			require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );

			$db_option  = get_option( 'bsd_split_pay_stripe_connect_woo_back_end' );
			$db_version = null;

			if ( $db_option ) {
				$db_option  = maybe_unserialize( $db_option );
				$db_version = isset( $db_option['db_version'] ) ? $db_option['db_version'] : null;
			}

			// Get legacy options - Added in v2.6
			$legacy_option = null;
			if ( ! $db_version || $db_version == '0.0.0' ) {
				$legacy_option = get_option( 'bsd_wc_scsp_db_version' );
			}

			if ( $legacy_option ) {
				$this->options['db_version'] = $legacy_option;
			} else {
				$this->options['db_version'] = $db_version;
			}
		}

		public function bsd_scsp_check_for_db_updates() {
			$db_version = null;

			if ( ! $this->options['db_version'] ) {
				$db_version                  = '0.0.0';
				$this->options['db_version'] = $db_version;

				update_option( 'bsd_split_pay_stripe_connect_woo_back_end', $this->options );
			} else {
				$db_version = $this->options['db_version'];
			}

			$this->db_update_controller( $db_version );
		}

		private function update_db_version( $new_version ) {
			try {
				$this->options['db_version'] = $new_version;
				update_option( 'bsd_split_pay_stripe_connect_woo_back_end', $this->options );

				return true;
			} catch ( Exception $e ) {
				if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { error_log( '[BSD Split Pay for Stripe Connect] Error updating database version.' ); } // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log

				return false;
			}
		}

		private function db_update_controller( $db_version ) {
			global $wpdb;
			$table_prefix = $wpdb->prefix;

			/*
			 * 3.7.4 hardening: every migration include uses an absolute
			 * path anchored on __DIR__. Previously the controller used
			 * `include 'migrations/migration-XXX.php'` which only resolves
			 * when the working directory happens to be the same directory
			 * as this controller file. Under wp-cron / CLI / some hosting
			 * stacks (Cloudways' Breeze cron prefetcher being one) PHP's
			 * cwd is different and every include silently emits a Warning
			 * and a Fatal on the subsequent call to the missing function.
			 * Switching to __DIR__ makes the controller robust regardless
			 * of caller context. Also affects pre-existing 100/200/373
			 * migrations — those have always had the same latent bug,
			 * just never surfaced because the controller is normally
			 * triggered from an `init` hook with cwd = ABSPATH where
			 * include_path resolution happened to work via PHP's path
			 * fallback.
			 */
			$migrations_dir = __DIR__ . '/migrations/';

			/*
			 * 3.7.4 hardening: include_once (not include) for every migration.
			 * Two production scenarios would have fataled on the prior
			 * `include` form:
			 *   1. A WordPress request that hits this controller twice in the
			 *      same PHP process — e.g. a custom hook that re-triggers
			 *      bsd_scsp_check_for_db_updates after `init`, or a unit-test
			 *      harness exercising upgrade paths. PHP fatals with
			 *      "Cannot redeclare BSD_Split_Pay_Stripe_Connect_Woo\Inc\Admin\db_migration_XXX".
			 *   2. opcache misses on shared-host stacks that briefly serve
			 *      two requests in the same worker process during a deploy.
			 * include_once + the per-migration function_exists guards added
			 * in 3.7.4 (and backported here for 100/200/373) make duplicate
			 * inclusion a true no-op.
			 */
			if ( version_compare( $db_version, '1.0.0', '<' ) ) {
				include_once $migrations_dir . 'migration-100.php';

				if ( true === db_migration_100( $table_prefix ) ) {
					$this->update_db_version( '1.0.0' );
				} else {
					return;
				}
			}

			if ( version_compare( $db_version, '2.0.0', '<' ) ) {
				include_once $migrations_dir . 'migration-200.php';

				if ( true === db_migration_200( $table_prefix ) ) {
					$this->update_db_version( '2.0.0' );
				} else {
					return;
				}
			}

			// 3.7.3 (sc-7168 / Michael Burgess): backfill stripe_mode + date_created
			// for transfer-log rows written by the 3.7.0–3.7.2 namespaced engine,
			// which omitted those columns and so were invisible to the Transfers tab.
			if ( version_compare( $db_version, '3.7.3', '<' ) ) {
				include_once $migrations_dir . 'migration-373.php';

				if ( true === db_migration_373( $table_prefix ) ) {
					$this->update_db_version( '3.7.3' );
				} else {
					return;
				}
			}

			// 3.7.4 (sc-7216): reconstruct product → vendor Split Pay meta
			// silently erased by the legacy bsd_product_data_fields_save()
			// handler in 3.7.3 and earlier. The 3.7.4 release also adds the
			// bsd_spp_product_tab_rendered form-presence marker that prevents
			// future erasure; this migration is the one-time backfill for
			// data already lost. See migration-374.php for full design notes.
			if ( version_compare( $db_version, '3.7.4', '<' ) ) {
				include_once $migrations_dir . 'migration-374.php';

				if ( true === db_migration_374( $table_prefix ) ) {
					$this->update_db_version( '3.7.4' );
				} else {
					return;
				}
			}

			// 3.7.4 hotfix (Vanessa / profplaza.nl): align transfer-log stripe_mode
			// with Payment Plugins + unified resolveStripeMode() (see migration-375.php).
			if ( ! get_option( 'bsd_split_pay_375_reconciled_stripe_mode', false ) ) {
				include_once $migrations_dir . 'migration-375.php';

				if ( true !== db_migration_375( $table_prefix ) ) {
					return;
				}
			}

			// 3.7.5 — add missing indexes to bsd_scsp_transfer_log so the
			// Transfers tab is usable on sites with > 1000 transfers.
			// Pre-fix measured 5.2s TTFB at 1000 rows (full table scan); post-fix
			// is sub-200ms because every WHERE filter now hits an index.
			// See migration-376.php for the full rationale.
			if ( ! get_option( 'bsd_split_pay_376_transfer_log_indexes', false ) ) {
				include_once $migrations_dir . 'migration-376.php';

				if ( true === db_migration_376( $table_prefix ) ) {
					update_option( 'bsd_split_pay_376_transfer_log_indexes', true );
				} else {
					return;
				}
			}

			// 3.7.5 — add bsd_account_mode to the connected-accounts cache so
			// each synced/onboarded account records which Stripe mode (test vs
			// live) it was connected in. Foundation for the mode-mismatch fix
			// (dropdown filtering + pre-emptive transfer guard) that stops a
			// live key being used against a test-mode destination, and vice
			// versa. See migration-377.php for the full rationale.
			if ( ! get_option( 'bsd_split_pay_377_added_account_mode', false ) ) {
				include_once $migrations_dir . 'migration-377.php';

				if ( true === db_migration_377( $table_prefix ) ) {
					update_option( 'bsd_split_pay_377_added_account_mode', true );
				} else {
					return;
				}
			}

			// Insert next migration
		}

	}

endif; // class_exists check