<?php
namespace Elex\MultiVendor;

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

class Migration {

	/**
	 * Rename unprefixed option keys to the elex_mv_ namespace.
	 * Safe to run multiple times — only copies when old key exists.
	 * Guarded by a version flag so it runs once per codebase version.
	 */
	public static function migrate_option_names(): void {
		$migration_version = '1.0';
		if ( get_option( 'elex_mv_option_migration_version' ) === $migration_version ) {
			return;
		}

		$basename = plugin_basename( ELEX_MULTI_VENDOR_MAIN_FILE );

		$old_to_new = array(
			'admin_installation_params'                   => 'elex_mv_admin_installation_params',
			'splitted_packages'                           => 'elex_mv_splitted_packages',
			'admin_orders_value_set_as_admin'             => 'elex_mv_admin_orders_value_set',
			'all_admin_related_detail_set_as_vendor_date' => 'elex_mv_admin_detail_set_as_vendor_date',
			
			// Review component options
			$basename . '_activation_date'                => 'elex_mv_' . $basename . '_activation_date',
			$basename . '_troubleshoot_never_ask_again'   => 'elex_mv_' . $basename . '_troubleshoot_never_ask_again',
			$basename . '_review_never_ask_again'         => 'elex_mv_' . $basename . '_review_never_ask_again',
			$basename . '_review_will_do_it_later'        => 'elex_mv_' . $basename . '_review_will_do_it_later',
		);

		foreach ( $old_to_new as $old => $new ) {
			$value = get_option( $old );
			if ( false !== $value ) {
				update_option( $new, $value );
				delete_option( $old );
			}
		}

		update_option( 'elex_mv_option_migration_version', $migration_version );
	}

	/**
	 * Rename unprefixed post meta keys to the elex_mv_ namespace.
	 * Safe to run multiple times — only updates rows where old key still exists.
	 * Guarded by a version flag so it runs once per codebase version.
	 */
	public static function migrate_meta_keys(): void {
		global $wpdb;

		$migration_version = '1.0';
		if ( get_option( 'elex_mv_meta_key_migration_version' ) === $migration_version ) {
			return;
		}

		$old_to_new = array(
			// Product meta
			'store_id'                                     => 'elex_mv_store_id',
			'commission_type'                              => 'elex_mv_commission_type',
			'views_count'                                  => 'elex_mv_views_count',
			'rejection_message'                            => 'elex_mv_rejection_message',
			'currency_code'                                => 'elex_mv_currency_code',
			'commission'                                   => 'elex_mv_commission',
			// Vendor store profile meta
			'title'                                        => 'elex_mv_title',
			'user_name'                                    => 'elex_mv_user_name',
			'user_id'                                      => 'elex_mv_user_id',
			'phone_number'                                 => 'elex_mv_phone_number',
			'dial_code'                                    => 'elex_mv_dial_code',
			'country_iso'                                  => 'elex_mv_country_iso',
			'email'                                        => 'elex_mv_email',
			'address1'                                     => 'elex_mv_address1',
			'address2'                                     => 'elex_mv_address2',
			'city'                                         => 'elex_mv_city',
			'state'                                        => 'elex_mv_state',
			'postal_code'                                  => 'elex_mv_postal_code',
			'country'                                      => 'elex_mv_country',
			'paypal_email'                                 => 'elex_mv_paypal_email',
			'store_commission'                             => 'elex_mv_store_commission',
			'is_setup_finished'                            => 'elex_mv_is_setup_finished',
			'last_settlement_date'                         => 'elex_mv_last_settlement_date',
			'creation_date'                                => 'elex_mv_creation_date',
			'global_capabilities'                          => 'elex_mv_global_capabilities',
			'post_banner_id'                               => 'elex_mv_post_banner_id',
			'banner_image_text'                            => 'elex_mv_banner_image_text',
			'name_to_show_on_product'                      => 'elex_mv_name_to_show_on_product',
			'price_to_show_on_product'                     => 'elex_mv_price_to_show_on_product',
			'show_all_categories'                          => 'elex_mv_show_all_categories',
			'coupon_notification'                          => 'elex_mv_coupon_notification',
			'verify_user_review'                           => 'elex_mv_verify_user_review',
			'store_slug'                                   => 'elex_mv_store_slug',
			'enabling_shipping_method_plugins'             => 'elex_mv_enabling_shipping_method_plugins',
			'override_credentials'                         => 'elex_mv_override_credentials',
			// Vendor store financial meta
			'vendor_earning'                               => 'elex_mv_vendor_earning',
			'vendor_refund_amount'                         => 'elex_mv_vendor_refund_amount',
			'vendor_last_settlement_refund'                => 'elex_mv_vendor_last_settlement_refund',
			'vendor_total_sales'                           => 'elex_mv_vendor_total_sales',
			'vendor_total_earning'                         => 'elex_mv_vendor_total_earning',
			'admin_earning'                                => 'elex_mv_admin_earning',
			'total_product_count'                          => 'elex_mv_total_product_count',
			// Vendor store capability meta
			'apply_vendor_commission_switch'               => 'elex_mv_apply_vendor_commission_switch',
			'category_commission_switch_vendor'            => 'elex_mv_category_commission_switch_vendor',
			'product_commission_switch_vendor'             => 'elex_mv_product_commission_switch_vendor',
			'categories_selected_for_commission'           => 'elex_mv_categories_selected_for_commission',
			'products_selected_for_commission'             => 'elex_mv_products_selected_for_commission',
			'category_commission_vendor'                   => 'elex_mv_category_commission_vendor',
			'product_commission_vendor'                    => 'elex_mv_product_commission_vendor',
			'vendor_to_sell_without_approval'              => 'elex_mv_vendor_to_sell_without_approval',
			'vendor_to_use_flat_rate_service_set_by_admin' => 'elex_mv_vendor_to_use_flat_rate_service_set_by_admin',
			'vendor_to_change_order_status'                => 'elex_mv_vendor_to_change_order_status',
			'vendor_to_generate_coupons'                   => 'elex_mv_vendor_to_generate_coupons',
			'vendor_to_create_category'                    => 'elex_mv_vendor_to_create_category',
			'show_vendor_detail_on_woocom_store_page'      => 'elex_mv_show_vendor_detail_on_woocom_store_page',
			'show_vendor_detail_on_woocom_product_page'    => 'elex_mv_show_vendor_detail_on_woocom_product_page',
			'vendor_to_allow_vendor_shipping'              => 'elex_mv_vendor_to_allow_vendor_shipping',
			'vendor_to_override_creds'                     => 'elex_mv_vendor_to_override_creds',
			'vendor_to_choose_ship_services'               => 'elex_mv_vendor_to_choose_ship_services',
			// Order meta
			'has_sub_order'                                => 'elex_mv_has_sub_order',
			'ship_fee_beared_by'                           => 'elex_mv_ship_fee_beared_by',
			'admin_commission_from_product'                => 'elex_mv_admin_commission_from_product',
			'admin_commission_refund_amount_products'      => 'elex_mv_admin_commission_refund_amount_products',
			'refund_amount_product_to_vendor'              => 'elex_mv_refund_amount_product_to_vendor',
			'refunded_amount_product'                      => 'elex_mv_refunded_amount_product',
			'vendor_sales'                                 => 'elex_mv_vendor_sales',
			'total_shipping'                               => 'elex_mv_total_shipping',
			'full_refund_amount'                           => 'elex_mv_full_refund_amount',
			'refund_amount'                                => 'elex_mv_refund_amount',
			'mv_order_shipping_refund_amount_vendor'       => 'elex_mv_order_shipping_refund_amount_vendor',
			'mv_item_full_refund'                          => 'elex_mv_item_full_refund',
			'mv_item_partial_refund_amount'                => 'elex_mv_item_partial_refund_amount',
			'mv_item_full_refund_amount'                   => 'elex_mv_item_full_refund_amount',
			'mv_item_partial_refund'                       => 'elex_mv_item_partial_refund',
			// Coupon meta
			'coupon_title'                                 => 'elex_mv_coupon_title',
			'validity_from'                                => 'elex_mv_validity_from',
			'vendor_id'                                    => 'elex_mv_vendor_id',
		);

		$hpos_table        = $wpdb->prefix . 'wc_orders_meta';
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		$hpos_table_exists = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $hpos_table ) ) === $hpos_table;

		$order_keys = array(
			'has_sub_order',
			'ship_fee_beared_by',
			'admin_commission_from_product',
			'admin_commission_refund_amount_products',
			'refund_amount_product_to_vendor',
			'refunded_amount_product',
			'vendor_sales',
			'total_shipping',
			'full_refund_amount',
			'refund_amount',
			'mv_order_shipping_refund_amount_vendor',
			'mv_item_full_refund',
			'mv_item_partial_refund_amount',
			'mv_item_full_refund_amount',
			'mv_item_partial_refund',
		);

		foreach ( $old_to_new as $old => $new ) {
			$update_tables = array( $wpdb->postmeta );
			if ( in_array( $old, $order_keys, true ) && $hpos_table_exists ) {
				$update_tables[] = $hpos_table;
			}

			foreach ( $update_tables as $table ) {
				// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
				$wpdb->update(
					$table,
					array( 'meta_key' => $new ),
					array( 'meta_key' => $old )
				);
			}
		}

		// Suffix keys need a custom query with LIKE to update keys containing dynamic IDs.
		$suffix_keys = array(
			'order_splitted_'                             => 'elex_mv_order_splitted_',
			'commission_cut_for_product_id_'              => 'elex_mv_commission_cut_for_product_id_',
			'commission_cut_after_refund_for_product_id_' => 'elex_mv_commission_cut_after_refund_for_product_id_',
			'vendor_earned_for_product_id_'               => 'elex_mv_vendor_earned_for_product_id_',
		);

		foreach ( $suffix_keys as $old_prefix => $new_prefix ) {
			$update_tables = array( $wpdb->postmeta );
			if ( $hpos_table_exists ) {
				$update_tables[] = $hpos_table;
			}

			foreach ( $update_tables as $table ) {
				// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
				$wpdb->query(
					$wpdb->prepare(
						"UPDATE {$table} SET meta_key = CONCAT(%s, SUBSTRING(meta_key, %d)) WHERE meta_key LIKE %s",
						$new_prefix,
						strlen( $old_prefix ) + 1,
						$wpdb->esc_like( $old_prefix ) . '%'
					)
				);
			}
		}

		update_option( 'elex_mv_meta_key_migration_version', $migration_version );
	}

	public static function settlement_history_table() {
		global $wpdb;
	$table_name          = 'elex_mv_payment_settlement_history';
		$charset_collate = $wpdb->get_charset_collate();
		$sql             = "CREATE TABLE if not exists $wpdb->base_prefix{$table_name} (
    id int(9) NOT NULL AUTO_INCREMENT,
    vendor_id bigint(20) UNSIGNED NOT NULL,
    vendor_amount decimal(10,2),
    commission_type varchar(10) NOT NULL,
    commission_amount decimal(10,2) NOT NULL,
    settlement_date date NOT NULL,
    settlement_mode varchar(10) NOT NULL,
    transaction_id varchar(60),
    created_at datetime NOT NULL,
    note varchar(600),
    PRIMARY KEY  (id)
    ) $charset_collate;";

		require_once ABSPATH . 'wp-admin/includes/upgrade.php' ;
		dbDelta( $sql );

	add_option( 'elex_mv_redirect_after_activation_option', true );
		if ( ! get_option( 'elex_mv_installation_date' ) ) {
			$currentdate = new \Datetime( 'now' );
			add_option( 'elex_mv_installation_date', $currentdate->format( 'Y-m-d' ) );
		}
	}
}
