<?php

namespace includes;

use includes\utils\WTV_Customer_Visma_DB;

class WTV_Migrate{

    /**
     * @param $upgrader_object
     * @param $options
     */
    public static function wp_update_completed( $upgrader_object, $options ) {

        if( $options['action'] == 'update' && $options['type'] == 'plugin' && isset( $options['plugins'] ) ) {
            foreach( $options['plugins'] as $plugin ) {
                if( $plugin == 'woocommerce-visma-integration/plugin.php' ) {
                    self::maybe_update_db();
                }
            }
        }
    }

    /**
     *
     */
    public static function maybe_update_db(){
        $db_version = self::get_db_version();

        if ( $db_version === 1.0 ){
            self::update_db();
            self::update_db_version( 2.0 );
        }

	    if ( version_compare( $db_version, '235', '<' ) ) {
		    self::update_to_235();
		    self::update_db_version( '235' );
	    }

		if ( version_compare( $db_version, '241', '<' ) ) {
		    self::update_to_241();
		    self::update_db_version( '241' );
	    }
    }

    /**
     *
     */
    private static function update_db() {
        $license_key = get_option( 'wetail_license_key' );
		if ( ! empty( $license_key ) ){
			update_option( 'wetail_visma_license_key', $license_key );
		}
		if ( empty( get_option( 'visma_sync_order_method' ) ) ){
			if ( get_option( 'visma_sync_orders' ) ) {
				update_option( 'visma_sync_order_method', 'create_orders' );
			} else {
				update_option( 'visma_sync_order_method', 'create_vouchers' );
			}
			delete_option( 'visma_sync_orders' );
		}
    }
    /**
     *
     */
    private static function update_to_241() {
        $customer_unique_identifier = get_option( 'visma_customer_unique_identifier' );
		if ( ! empty( $customer_unique_identifier ) ){
			update_option( 'visma_unique_customer_identifier', $customer_unique_identifier );
		}
    }

    /**
     * @param $version
     */
    private static function update_db_version( $version ) {
        update_option( 'visma_db_version', $version );
    }

    /***
     * @return float|int
     */
    private static function get_db_version() {

        $db_version = (int)get_option( 'visma_db_version' );

        if ( ! $db_version ) {
            return 1.0;
        }
        return $db_version;

    }

	/**
	 * Migrates customer data from WordPress options table to the custom database structure.
	 *
	 * This method retrieves customer records stored as WordPress options, validates the email
	 * addresses, and then moves the data into the designated custom database table. It also
	 * cleans up migrated entries by deleting them from the WordPress options table. Log messages
	 * are created for diagnostic purposes, including migration progress and any errors encountered.
	 *
	 * @return void
	 * @since 2.3.5
	 * @clickup https://app.clickup.com/t/86973ptw6
	 */
	private static function update_to_235() {
		wtv_write_log( 'Migration: Starting migration to version 2.3.5' );

		//region customers db CU-86973ptw6
		// Temporarily remove backward compatibility filters
		remove_filter( 'pre_option', array( '\includes\utils\WTV_Customer_Visma_DB', 'handle_visma_customer_option' ), 10 );
		remove_filter( 'pre_update_option', array( '\includes\utils\WTV_Customer_Visma_DB', 'handle_visma_customer_update' ), 10 );
		$customer_db = WTV_Customer_Visma_DB::get_instance();
		$customer_db->create_table();

		global $wpdb;
		$query   = $wpdb->prepare(
			"SELECT option_name, option_value FROM {$wpdb->options} WHERE option_name LIKE %s",
			'visma_customer_%@%' );
		$options = $wpdb->get_results( $query );
		wtv_write_log( 'Migration: Found ' . count( $options ) . ' customers to migrate' );
		foreach ( $options as $option ) {
			$email = str_replace( 'visma_customer_', '', $option->option_name );

			if ( ! filter_var( $email, FILTER_VALIDATE_EMAIL ) ) {
				continue;
			}
			if ( $customer_db->create_entry( $email, $option->option_value ) ) {
				delete_option( $option->option_name );
			} else {
				wtv_write_log( 'Migration: Failed to process customer: ' . $option->option_value );
			}
		}
		wtv_write_log( 'Migration: Finished migrating customers' );
		add_filter( 'pre_option', array( '\includes\utils\WTV_Customer_Visma_DB', 'handle_visma_customer_option' ), 10, 3 );
		add_filter( 'pre_update_option', array( '\includes\utils\WTV_Customer_Visma_DB', 'handle_visma_customer_update' ), 10, 3 );
		//endregion

		wtv_write_log( 'Migration: Finished migrating to version 2.3.5' );
	}
}
