<?php
/**
 * Database Migration Handler
 * 
 * Migrates old "vh_" prefixed options to new "varihu_" prefix
 * 
 * @package VariationHub
 * @since 1.0.0
 */

namespace VariationHub;

defined('ABSPATH') || exit;

class Migration {
    
    /**
     * Migration version
     */
    const MIGRATION_VERSION = '1.0.0';
    
    /**
     * Run all pending migrations
     */
    public static function run() {
        $current_migration = get_option('varihu_migration_version', '0.0.0');
        
        // Skip if already migrated
        if (version_compare($current_migration, self::MIGRATION_VERSION, '>=')) {
            return;
        }
        
        // Run migration
        self::migrate_vh_to_varihu();
        
        // Update migration version
        update_option('varihu_migration_version', self::MIGRATION_VERSION, false);
    }
    
    /**
     * Migrate vh_* options to varihu_*
     */
    private static function migrate_vh_to_varihu() {
        global $wpdb;
        
        // Define option mappings
        $option_mappings = [
            // License options
            'vh_license_data' => 'varihu_license_data',
            'vh_license_key' => 'varihu_license_key',
            'vh_license_tier' => 'varihu_license_tier',
            'vh_license_expires' => 'varihu_license_expires',
            
            // Cache options
            'vh_cache_db_version' => 'varihu_cache_db_version',
            'vh_cache_last_sync' => 'varihu_cache_last_sync',
            'vh_cache_sync_status' => 'varihu_cache_sync_status',
            
            // Activation option
            'vh_activated' => 'varihu_activated',
        ];
        
        // Migrate options
        foreach ($option_mappings as $old_key => $new_key) {
            $value = get_option($old_key, null);
            
            if ($value !== null) {
                // Copy to new key
                update_option($new_key, $value, false);
                
                // Delete old key
                delete_option($old_key);
            }
        }
        
        // Migrate transients (vh_security_incident_*, vh_license_attempts_*)
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- One-time migration, no need for caching
        $transients = $wpdb->get_results(
            "SELECT option_name, option_value 
            FROM {$wpdb->options} 
            WHERE option_name LIKE '_transient_vh_security_incident_%' 
               OR option_name LIKE '_transient_vh_license_attempts_%'",
            ARRAY_A
        );
        
        foreach ($transients as $transient) {
            $old_name = $transient['option_name'];
            
            // Extract transient key (remove _transient_ prefix)
            if (strpos($old_name, '_transient_') === 0) {
                $old_key = substr($old_name, strlen('_transient_'));
                
                // Replace vh_ with varihu_
                $new_key = str_replace('vh_', 'varihu_', $old_key);
                
                // Get transient value and timeout
                $value = get_transient($old_key);
                $timeout = get_option('_transient_timeout_' . $old_key, 0);
                
                if ($value !== false) {
                    // Calculate remaining time
                    $remaining_time = $timeout - time();
                    
                    if ($remaining_time > 0) {
                        // Set new transient with remaining time
                        set_transient($new_key, $value, $remaining_time);
                    }
                    
                    // Delete old transient
                    delete_transient($old_key);
                }
            }
        }
        
        // Migrate Action Scheduler cron jobs
        if (function_exists('as_has_scheduled_action') && function_exists('as_schedule_recurring_action')) {
            // vh_cache_sync_batch → varihu_cache_sync_batch
            $old_hook = 'vh_cache_sync_batch';
            $new_hook = 'varihu_cache_sync_batch';
            
            // Get all scheduled actions with old hook
            $actions = as_get_scheduled_actions([
                'hook' => $old_hook,
                'status' => 'pending',
                'per_page' => -1,
            ]);
            
            foreach ($actions as $action_id => $action) {
                // Get action args and timestamp
                $args = $action->get_args();
                $timestamp = $action->get_schedule()->get_date()->getTimestamp();
                
                // Schedule new action with same args
                as_schedule_single_action($timestamp, $new_hook, $args, 'variation-hub');
                
                // Unschedule old action
                as_unschedule_action($old_hook, $args);
            }
            
            // vh_validate_license_daily → varihu_validate_license_daily
            $old_daily_hook = 'vh_validate_license_daily';
            $new_daily_hook = 'varihu_validate_license_daily';
            
            // This is typically a recurring action, so we need to check if it exists
            // and recreate it with the new hook name
            if (as_has_scheduled_action($old_daily_hook)) {
                as_unschedule_all_actions($old_daily_hook);
                
                // Reschedule with new hook (will be done by License_Manager init)
                // No need to manually schedule, the plugin will handle it on next init
            }
        }
    }
}
