<?php

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

    use AC_SYNC\Includes\Classes\Api\Action_Wear_API;
    use AC_SYNC\Includes\Classes\Logger\Action_Wear_Log as Log;
    use AC_SYNC\Includes\Classes\Sync\Action_Wear_Sync as Sync;

    class Action_Wear_Sql_Version_1_2_0 extends Action_Wear_Sql_Version_Abstract implements Action_Wear_Sql_Version_Interface
    {
        public static function versioningScript()
        {
            // A. Fetch token code if missing
            $apikey = get_option('_ACTIONWEAR_APIKEY');
            if (!empty($apikey) && empty(get_option('_ACTIONWEAR_TOKEN_CODE'))) {
                try {
                    $result = Action_Wear_API::isValidApikey($apikey);
                    if ($result) {
                        Log::write("Migration 1.2.0: Token code recovered successfully", Log::INFO, Log::CONTEXT_GENERAL);
                    } else {
                        Log::write("Migration 1.2.0: API key validation returned false", Log::WARNING, Log::CONTEXT_GENERAL);
                    }
                } catch (\Throwable $th) {
                    Log::write("Migration 1.2.0: Failed to fetch token code - " . $th->getMessage(), Log::ERROR, Log::CONTEXT_GENERAL);
                }
            }

            // B. Safe defaults for order sync (existing users only)
            if (get_option('_ACTIONWEAR_ORDER_SYNC_TRIGGER') === false) {
                update_option('_ACTIONWEAR_ORDER_SYNC_TRIGGER', 'disabled');
            }
            if (get_option('_ACTIONWEAR_ORDER_TEST_MODE') === false) {
                update_option('_ACTIONWEAR_ORDER_TEST_MODE', 1);
            }

            // C. Initialize version tracking for What's New overlay
            add_option('_ACTIONWEAR_LAST_SEEN_VERSION', '');

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