<?php
/**
 * Credit Migration - v1 to v2 migration helper
 *
 * Handles migration from old Ctrl system to new CreditSystem.
 * Preserves credentials, clears old caches.
 *
 * @package AIPT\Core\CreditSystem
 */

namespace AIPT\Core\CreditSystem;

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

/**
 * Credit Migration
 */
class CreditMigration
{
    private const VERSION_KEY = 'aipt_credit_system_version';
    private const CURRENT_VERSION = '2.0';

    /**
     * Run migration if needed
     */
    public static function maybeRun(): void
    {
        $version = get_option(self::VERSION_KEY, '1.0');

        if (version_compare($version, self::CURRENT_VERSION, '<')) {
            self::migrate();
            update_option(self::VERSION_KEY, self::CURRENT_VERSION, false);
        }
    }

    /**
     * Perform migration
     */
    private static function migrate(): void
    {

        $oldTransients = [
            'aipt_ctrl_balance_cache',
            'aipt_ctrl_costs_cache',
            'aipt_ctrl_local_summary',
            'aipt_ctrl_balance',
            'aipt_ctrl_costs',
            'aipt_ctrl_system_status',
            'aipt_ctrl_sync_lock'
        ];

        foreach ($oldTransients as $key) {
            delete_transient($key);
        }

        $oldOptions = [
            'aipt_ctrl_system_version',
            'aipt_show_troubleshoot_modal',
            'aipt_ctrl_summary',
            'aipt_ctrl_last_sync',
            'aipt_ctrl_sync_error'
        ];

        foreach ($oldOptions as $key) {
            delete_option($key);
        }

        $oldApiKey = get_option('aipt_ctrl_api_key');
        $oldSecretKey = get_option('aipt_ctrl_secret_key');

        if (!empty($oldApiKey) && empty(get_option('aipt_credit_api_key'))) {
            update_option('aipt_credit_api_key', $oldApiKey, false);
        }

        if (!empty($oldSecretKey) && empty(get_option('aipt_credit_secret_key'))) {
            update_option('aipt_credit_secret_key', $oldSecretKey, false);
        }

        $oldRegistered = get_option('aipt_ctrl_registered');
        if ($oldRegistered && empty(get_option('aipt_credit_registered'))) {
            update_option('aipt_credit_registered', true, false);
        }

        delete_option('aipt_credit_local_usage');

    }

    /**
     * Check if migration is needed
     *
     * @return bool
     */
    public static function needsMigration(): bool
    {
        $version = get_option(self::VERSION_KEY, '1.0');
        return version_compare($version, self::CURRENT_VERSION, '<');
    }

    /**
     * Get current version
     *
     * @return string
     */
    public static function getVersion(): string
    {
        return get_option(self::VERSION_KEY, '1.0');
    }

    /**
     * Force re-migration (for troubleshooting)
     */
    public static function forceReMigrate(): void
    {
        delete_option(self::VERSION_KEY);
        self::maybeRun();
    }
}
