<?php

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

class SEO_Fury_Migration {

    private $migration_version = '0.2.0';

    /**
     * Map of old option names (my_seo_*) to new option names (seo_fury_*).
     * Used for individual option migration on older installs that still have my_seo_* keys.
     */
    private $options_map = array(
        'my_seo_robots_enabled' => 'seo_fury_robots_enabled',
        'my_seo_robots_content' => 'seo_fury_robots_content',
        'my_seo_robots_user_agents' => 'seo_fury_robots_user_agents',
        'my_seo_robots_crawl_delay' => 'seo_fury_robots_crawl_delay',
        'my_seo_robots_use_dynamic_vars' => 'seo_fury_robots_use_dynamic_vars',

        'my_seo_sitemap_enabled' => 'seo_fury_sitemap_enabled',
        'my_seo_sitemap_post_types' => 'seo_fury_sitemap_post_types',
        'my_seo_sitemap_post_types_settings' => 'seo_fury_sitemap_post_types_settings',
        'my_seo_sitemap_include_images' => 'seo_fury_sitemap_include_images',
        'my_seo_sitemap_exclude_urls' => 'seo_fury_sitemap_exclude_urls',
        'my_seo_sitemap_additional_urls' => 'seo_fury_sitemap_additional_urls',
        'my_seo_html_sitemap_slug' => 'seo_fury_html_sitemap_slug',
        'my_seo_html_sitemap_post_types' => 'seo_fury_html_sitemap_post_types',

        'my_seo_indexnow_api_key' => 'seo_fury_indexnow_api_key',
        'my_seo_indexnow_search_engine' => 'seo_fury_indexnow_search_engine',
        'my_seo_indexnow_auto_submit' => 'seo_fury_indexnow_auto_submit',
        'my_seo_indexnow_auto_delete' => 'seo_fury_indexnow_auto_delete',

        'my_seo_transliterate_urls' => 'seo_fury_transliterate_urls',

        'my_seo_robots_meta_index' => 'seo_fury_robots_meta_index',
        'my_seo_robots_meta_noindex' => 'seo_fury_robots_meta_noindex',
        'my_seo_robots_meta_nofollow' => 'seo_fury_robots_meta_nofollow',
        'my_seo_robots_meta_noarchive' => 'seo_fury_robots_meta_noarchive',
        'my_seo_robots_meta_noimageindex' => 'seo_fury_robots_meta_noimageindex',
        'my_seo_robots_meta_nosnippet' => 'seo_fury_robots_meta_nosnippet',
        'my_seo_robots_meta_max_snippet' => 'seo_fury_robots_meta_max_snippet',
        'my_seo_robots_meta_max_video_preview' => 'seo_fury_robots_meta_max_video_preview',
        'my_seo_robots_meta_max_image_preview' => 'seo_fury_robots_meta_max_image_preview',
        'my_seo_noindex_empty_archives' => 'seo_fury_noindex_empty_archives',
        'my_seo_title_separator' => 'seo_fury_title_separator',
        'my_seo_title_capitalize' => 'seo_fury_title_capitalize',
        'my_seo_twitter_card_type' => 'seo_fury_twitter_card_type',

        'my_seo_license_key' => 'seo_fury_license_key',
        'my_seo_license_status' => 'seo_fury_license_status',
        'my_seo_license_plan' => 'seo_fury_license_plan',
        'my_seo_license_domain' => 'seo_fury_license_domain',
        'my_seo_license_activated_at' => 'seo_fury_license_activated_at',
        'my_seo_license_last_checked' => 'seo_fury_license_last_checked',
        'my_seo_license_data' => 'seo_fury_license_data',

        'my_seo_404_max_logs' => 'seo_fury_404_max_logs',

        'my_seo_plugin_db_version' => 'seo_fury_db_version',

        'my_seo_integrity_manifest' => 'seo_fury_integrity_manifest',

        'my_seo_ai_api_key' => 'seo_fury_ai_api_key',
        'my_seo_ai_model' => 'seo_fury_ai_model',
        'my_seo_ai_key_anthropic' => 'seo_fury_ai_key_anthropic',
        'my_seo_ai_model_anthropic' => 'seo_fury_ai_model_anthropic',

        'my_seo_google_indexing_enabled' => 'seo_fury_google_indexing_enabled',
        'my_seo_google_indexing_credentials' => 'seo_fury_google_indexing_credentials',

        'my_seo_htaccess_enabled' => 'seo_fury_htaccess_enabled',
        'my_seo_htaccess_rules' => 'seo_fury_htaccess_rules',

        'my_seo_woocommerce_enabled' => 'seo_fury_woocommerce_enabled',

        'my_seo_seo_images_enabled' => 'seo_fury_seo_images_enabled',
        'my_seo_seo_images_alt_template' => 'seo_fury_seo_images_alt_template',
        'my_seo_seo_images_title_template' => 'seo_fury_seo_images_title_template',

        'my_seo_breadcrumbs_enabled' => 'seo_fury_breadcrumbs_enabled',
        'my_seo_breadcrumbs_separator' => 'seo_fury_breadcrumbs_separator',
        'my_seo_breadcrumbs_home_text' => 'seo_fury_breadcrumbs_home_text',

        'my_seo_local_seo_enabled' => 'seo_fury_local_seo_enabled',
        'my_seo_local_seo_type' => 'seo_fury_local_seo_type',
        'my_seo_local_seo_name' => 'seo_fury_local_seo_name',
    );

    public function run_migration() {
        $current_version = get_option('seo_fury_migration_version', '0.0.0');

        // Always run these migrations (they have their own internal flags)
        $this->migrate_robots_template();
        $this->migrate_ai_key_to_centralized();

        if (version_compare($current_version, '0.2.0', '<')) {
            // v0.2.0: Bulk rename my_seo_ → seo_fury_ in database
            $this->migrate_prefix_rename();
        }

        if (version_compare($current_version, '0.1.0', '<')) {
            // v0.1.0: Individual option migration (fallback for anything missed)
            $this->migrate_options();
        }

        if (version_compare($current_version, $this->migration_version, '<')) {
            update_option('seo_fury_migration_version', $this->migration_version);
        }
    }

    /**
     * Bulk rename old prefixes in the database using SQL REPLACE.
     * This handles ALL options and post meta in one go.
     *
     * Converts:
     *   - Options: my_seo_* → seo_fury_*
     *   - Post meta: _my_seo_* → _seo_fury_*
     *   - Transients: _transient_my_seo_* → _transient_seo_fury_*
     *   - Settings groups in options autoload
     */
    private function migrate_prefix_rename() {
        if (get_option('seo_fury_prefix_migrated', false)) {
            return;
        }

        global $wpdb;

        // 1. Rename options: my_seo_* → seo_fury_*
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery
        $wpdb->query(
            $wpdb->prepare(
                "UPDATE {$wpdb->options} SET option_name = CONCAT('seo_fury_', SUBSTRING(option_name, %d)) WHERE option_name LIKE %s AND option_name NOT LIKE %s",
                strlen('my_seo_') + 1,
                $wpdb->esc_like('my_seo_') . '%',
                $wpdb->esc_like('seo_fury_') . '%'
            )
        );

        // 2. Rename post meta: _my_seo_* → _seo_fury_*
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery
        $wpdb->query(
            $wpdb->prepare(
                "UPDATE {$wpdb->postmeta} SET meta_key = CONCAT('_seo_fury_', SUBSTRING(meta_key, %d)) WHERE meta_key LIKE %s AND meta_key NOT LIKE %s",
                strlen('_my_seo_') + 1,
                $wpdb->esc_like('_my_seo_') . '%',
                $wpdb->esc_like('_seo_fury_') . '%'
            )
        );

        // 3. Rename transients: _transient_my_seo_* → _transient_seo_fury_*
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery
        $wpdb->query(
            $wpdb->prepare(
                "UPDATE {$wpdb->options} SET option_name = REPLACE(option_name, '_transient_my_seo_', '_transient_seo_fury_') WHERE option_name LIKE %s",
                $wpdb->esc_like('_transient_my_seo_') . '%'
            )
        );

        // 4. Rename transient timeouts
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery
        $wpdb->query(
            $wpdb->prepare(
                "UPDATE {$wpdb->options} SET option_name = REPLACE(option_name, '_transient_timeout_my_seo_', '_transient_timeout_seo_fury_') WHERE option_name LIKE %s",
                $wpdb->esc_like('_transient_timeout_my_seo_') . '%'
            )
        );

        // 5. Rename user meta if any
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery
        $wpdb->query(
            $wpdb->prepare(
                "UPDATE {$wpdb->usermeta} SET meta_key = CONCAT('_seo_fury_', SUBSTRING(meta_key, %d)) WHERE meta_key LIKE %s AND meta_key NOT LIKE %s",
                strlen('_my_seo_') + 1,
                $wpdb->esc_like('_my_seo_') . '%',
                $wpdb->esc_like('_seo_fury_') . '%'
            )
        );

        update_option('seo_fury_prefix_migrated', true);
    }

    /**
     * Migrate old robots.txt template to modern best-practice version.
     * Only auto-replaces if the stored content matches the old default exactly.
     */
    private function migrate_robots_template() {
        if (get_option('seo_fury_robots_template_migrated', false)) {
            return;
        }

        // Check both old and new option names
        $stored = get_option('seo_fury_robots_content', '');
        if (empty($stored)) {
            $stored = get_option('my_seo_robots_content', '');
        }

        if (empty($stored)) {
            update_option('seo_fury_robots_template_migrated', true);
            return;
        }

        // Detect old default template by checking for unique old patterns
        $is_old_default = (
            strpos($stored, '# Robots.txt for {site_url}') !== false
            && strpos($stored, 'Disallow: /wp-includes/') !== false
            && strpos($stored, 'Disallow: /wp-content/plugins/') !== false
            && strpos($stored, 'User-agent: Yandex') !== false
        );

        if ($is_old_default) {
            // User never customized — safe to replace with new template
            delete_option('seo_fury_robots_content');
            delete_option('my_seo_robots_content');
        }

        update_option('seo_fury_robots_template_migrated', true);
    }

    /**
     * Migrate existing Anthropic API key from ai-content module to centralized ai-keys.
     */
    private function migrate_ai_key_to_centralized() {
        if (get_option('seo_fury_ai_key_migrated', false)) {
            return;
        }

        $old_key = get_option('seo_fury_ai_api_key', '');
        if (empty($old_key)) {
            $old_key = get_option('my_seo_ai_api_key', '');
        }

        if (!empty($old_key) && empty(get_option('seo_fury_ai_key_anthropic', ''))) {
            update_option('seo_fury_ai_key_anthropic', $old_key);
        }

        // Migrate model selection
        $old_model = get_option('seo_fury_ai_model', '');
        if (empty($old_model)) {
            $old_model = get_option('my_seo_ai_model', '');
        }

        if (!empty($old_model) && empty(get_option('seo_fury_ai_model_anthropic', ''))) {
            update_option('seo_fury_ai_model_anthropic', $old_model);
        }

        update_option('seo_fury_ai_key_migrated', true);
    }

    /**
     * Fallback: migrate individual options one by one.
     * This catches anything that the bulk SQL rename might have missed.
     */
    private function migrate_options() {
        $migrated_count = 0;
        $skipped_count = 0;

        foreach ($this->options_map as $old_key => $new_key) {
            $old_value = get_option($old_key, null);

            if ($old_value === null) {
                $skipped_count++;
                continue;
            }

            $new_value = get_option($new_key, null);

            if ($new_value !== null) {
                $skipped_count++;
                continue;
            }

            update_option($new_key, $old_value);
            delete_option($old_key);
            $migrated_count++;
        }
    }

    public function rollback_migration() {
        global $wpdb;

        // Rollback bulk prefix rename: seo_fury_* → my_seo_*
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery
        $wpdb->query(
            $wpdb->prepare(
                "UPDATE {$wpdb->options} SET option_name = CONCAT('my_seo_', SUBSTRING(option_name, %d)) WHERE option_name LIKE %s",
                strlen('seo_fury_') + 1,
                $wpdb->esc_like('seo_fury_') . '%'
            )
        );

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery
        $wpdb->query(
            $wpdb->prepare(
                "UPDATE {$wpdb->postmeta} SET meta_key = CONCAT('_my_seo_', SUBSTRING(meta_key, %d)) WHERE meta_key LIKE %s",
                strlen('_seo_fury_') + 1,
                $wpdb->esc_like('_seo_fury_') . '%'
            )
        );

        delete_option('seo_fury_migration_version');
        delete_option('seo_fury_prefix_migrated');
    }
}
