<?php

/**
 * Update version.
 */
update_option('domain_for_sale_version', '3.3.1');
update_option('domain_for_sale_db_version', '3.3.1');

/**
 * Convert old data keys to new ones.
 */
function domain_for_sale_convert_old_to_new_data_3_3_1()
{
    $domain_for_sale_posts = new \WP_Query(
        array(
            'post_type'      => 'dfs_template',
            'posts_per_page' => 900,
        )
    );

    $post_ids = wp_list_pluck($domain_for_sale_posts->posts, 'ID');

    // Loop through each post ID to update the 'dfs_template_options' post meta
    foreach ($post_ids as $domain_id) {
        $template_options = get_post_meta($domain_id, 'dfs_template_options', true);

        $key_map = [
            'dfs-domainname'        => 'domain_name',
        ];

        foreach ($key_map as $old_key => $new_key) {
            $template_options[$new_key] = $template_options[$old_key] ?? '';
            unset($template_options[$old_key]);
        }

        update_post_meta($domain_id, 'dfs_template_options', $template_options);
    }
}

$options = get_option('dfs-opt');
if ($options) {
    domain_for_sale_convert_old_to_new_data_3_3_1();
}