<?php

namespace AC_SYNC\Includes\Classes\Sql\Version {
    if (!defined('ABSPATH'))
        exit;

    use AC_SYNC\Includes\Classes\Logger\Action_Wear_Log as Log;
    use AC_SYNC\Includes\Classes\Product\Action_Wear_Product as Product;
    use AC_SYNC\Includes\Classes\Sync\Action_Wear_Sync as Sync;

    class Action_Wear_Sql_Version_1_2_1 extends Action_Wear_Sql_Version_Abstract implements Action_Wear_Sql_Version_Interface
    {
        public static function versioningScript()
        {
            global $wpdb;

            // A. Repopulate actionwear_products if table is empty
            $count = (int) $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}actionwear_products");

            if ($count === 0) {
                $apikey = get_option('_ACTIONWEAR_APIKEY');
                if (!empty($apikey)) {
                    try {
                        @set_time_limit(300);
                        @ini_set('memory_limit', '512M');
                        Product::generateProducts();
                        $new_count = (int) $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}actionwear_products");
                        Log::write("Migration 1.2.1: Repopulated actionwear_products with {$new_count} products", Log::INFO, Log::CONTEXT_GENERAL);
                    } catch (\Throwable $th) {
                        Log::write("Migration 1.2.1: Failed to repopulate products - " . $th->getMessage(), Log::ERROR, Log::CONTEXT_GENERAL);
                    }
                } else {
                    Log::write("Migration 1.2.1: Skipped repopulation - no API key configured", Log::WARNING, Log::CONTEXT_GENERAL);
                }
            } else {
                Log::write("Migration 1.2.1: actionwear_products already has {$count} rows, skipping repopulation", Log::INFO, Log::CONTEXT_GENERAL);
            }

            // B. Align wc_created with actual WooCommerce products
            try {
                $result = Sync::alignWcCreated();
                Log::write("Migration 1.2.1: wc_created aligned - marked={$result['marked']}, reset={$result['reset']}", Log::INFO, Log::CONTEXT_GENERAL);
            } catch (\Throwable $th) {
                Log::write("Migration 1.2.1: Failed to align wc_created - " . $th->getMessage(), Log::ERROR, Log::CONTEXT_GENERAL);
            }
        }
    }
}
