<?php
defined('ABSPATH') || exit;

/*

Update auf 1.1.8 → kopieren
Update auf 1.1.9 → alte ssb_ löschen
Update auf 1.2.0, 1.2.1, 2.0.0 → nichts mehr bzgl. ssb_

*/


if (!defined('IV1WPT_DB_VERSION_OPTION')) {
    define('IV1WPT_DB_VERSION_OPTION', 'iv1wpt_db_version');
}

add_action('plugins_loaded', 'iv1wpt_run_migrations', 0);

function iv1wpt_run_migrations(): void {
    $installed_version = get_option(IV1WPT_DB_VERSION_OPTION, '0.0.0');

    if (version_compare($installed_version, IV1WPT_VERSION, '>=')) {
        return;
    }

    // Bis 1.1.8: alte ssb_-Optionen nach iv1wpt_ kopieren
    if (version_compare($installed_version, '1.1.8', '<')) {
        iv1wpt_migrate_ssb_options_to_iv1wpt();
    }

    // Ab 1.1.9: alte ssb_-Optionen entfernen
    if (version_compare($installed_version, '1.1.9', '<') && version_compare(IV1WPT_VERSION, '1.1.9', '>=')) {
        iv1wpt_remove_old_ssb_options();
    }

    update_option(IV1WPT_DB_VERSION_OPTION, IV1WPT_VERSION, false);
}

function iv1wpt_migrate_ssb_options_to_iv1wpt(): void {
    global $wpdb;

    $old_options = $wpdb->get_results(
        $wpdb->prepare(
            "SELECT option_name, autoload 
             FROM {$wpdb->options} 
             WHERE option_name LIKE %s",
            $wpdb->esc_like('ssb_') . '%'
        )
    );

    if (empty($old_options)) {
        return;
    }

    foreach ($old_options as $option) {
        $old_name = (string) $option->option_name;
        $new_name = preg_replace('/^ssb_/', 'iv1wpt_', $old_name);

        if (empty($new_name) || $new_name === $old_name) {
            continue;
        }

        if (get_option($new_name, null) !== null) {
            continue;
        }

        $value = get_option($old_name);

        add_option(
            $new_name,
            $value,
            '',
            $option->autoload === 'yes'
        );
    }
}

function iv1wpt_remove_old_ssb_options(): void {
    global $wpdb;

    $old_options = $wpdb->get_col(
        $wpdb->prepare(
            "SELECT option_name 
             FROM {$wpdb->options} 
             WHERE option_name LIKE %s",
            $wpdb->esc_like('ssb_') . '%'
        )
    );

    if (empty($old_options)) {
        return;
    }

    foreach ($old_options as $old_name) {
        $new_name = preg_replace('/^ssb_/', 'iv1wpt_', $old_name);

        // Nur löschen, wenn die neue Option existiert
        if ($new_name && get_option($new_name, null) !== null) {
            delete_option($old_name);
        }
    }
}