<?php
/**
 * The file of the Brands taxonomy.
 *
 * @link       https://shapedplugin.com
 * @since      1.0.0
 *
 * @package    Smart_Brands_For_Wc
 */

namespace ShapedPlugin\SmartBrands\Admin\Brands;

defined( 'ABSPATH' ) || die( 'No direct access, please!' );

/**
 * Brands migration class.
 */
class Migration {

	/**
	 * Handles the migration of brand taxonomy from 'sp_smart_brand' to 'product_brand'.
	 *
	 * @since 1.0.0
	 */
	public static function migrate_and_unregister_taxonomy() {
		$brand_taxonomy = smart_brands_get_brand_taxonomy();
		if ( 'product_brand' === $brand_taxonomy ) {
			if ( ! get_option( 'smart_brands_migration_done' ) ) {
				self::migrate_brands();
				update_option( 'smart_brands_migration_done', 1 );
			}

			add_action( 'init', array( self::class, 'unregister_old_brand_taxonomy' ), 20 );
		}
	}

	/**
	 * Migrate WooCommerce Brands from 'sp_smart_brand' to 'product_brand'
	 * Preserves parent-child term relationships.
	 */
	public static function migrate_brands() {
		$old_taxonomy = 'sp_smart_brand';
		$new_taxonomy = 'product_brand';

		$terms = get_terms(
			array(
				'taxonomy'   => $old_taxonomy,
				'hide_empty' => false,
			)
		);

		if ( empty( $terms ) || is_wp_error( $terms ) ) {
			return;
		}

		$term_map = array();

		// Create terms (no parent set yet).
		foreach ( $terms as $term ) {
			$brand_term_meta  = get_term_meta( $term->term_id, 'sp_smart_brand_taxonomy_meta', true );
			$meta_description = $term->description ?? '';

			$inserted_term = wp_insert_term(
				$term->name,
				$new_taxonomy,
				array(
					'slug'        => $term->slug,
					'description' => $meta_description,
					'parent'      => 0,
				)
			);

			if ( is_wp_error( $inserted_term ) ) {
				continue;
			}

			$new_term_id                = $inserted_term['term_id'];
			$term_map[ $term->term_id ] = $new_term_id;

			// Migrate meta.
			$old_term_logo_id = $brand_term_meta['smart_brand_term_logo']['id'] ?? '';
			$meta_banner_link = $brand_term_meta['smart_brand_term_banner_link'] ?? '';

			if ( $old_term_logo_id ) {
				update_term_meta( $new_term_id, 'thumbnail_id', $old_term_logo_id );
			}

			$new_term_meta = array(
				'smart_brand_term_banner_link' => $meta_banner_link,
			);

			update_term_meta( $new_term_id, 'sp_smart_brand_taxonomy_meta', $new_term_meta );
		}

		// Set parent terms and assign products in chunks.
		foreach ( $terms as $term ) {
			$new_term_id = $term_map[ $term->term_id ] ?? null;
			if ( ! $new_term_id ) {
				continue;
			}

			// Set parent relationship.
			if ( $term->parent && isset( $term_map[ $term->parent ] ) ) {
				wp_update_term( $new_term_id, $new_taxonomy, array( 'parent' => $term_map[ $term->parent ] ) );
			}

			// Assign products using get_objects_in_term (returns just IDs).
			$product_ids = get_objects_in_term( $term->term_id, $old_taxonomy );
			if ( empty( $product_ids ) ) {
				continue;
			}

			// Process products in chunks to prevent memory/time issues.
			$product_chunks = array_chunk( $product_ids, 200 );

			foreach ( $product_chunks as $chunk ) {
				foreach ( $chunk as $product_id ) {
					wp_set_object_terms( $product_id, $new_term_id, $new_taxonomy, true );
				}

				// Sleep between chunks.
				usleep( 20000 ); // 20ms
			}
		}
	}

	/**
	 * Unregister the old brand taxonomy after migration.
	 */
	public static function unregister_old_brand_taxonomy() {
		global $wp_taxonomies;

		$old_taxonomy = 'sp_smart_brand';

		if ( isset( $wp_taxonomies[ $old_taxonomy ] ) ) {
			unset( $wp_taxonomies[ $old_taxonomy ] );
		}
	}
}
