<?php
/**
 * MenuX Free — Data Migration
 * @package MenuX
 */

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

function menux_maybe_migrate() {
    if (get_option('menux_migrated_to_v7')) return;

    $logged = get_option('menux_menu_logged', array());
    $guest  = get_option('menux_menu_guest', array());
    $merged = array();

    if (!empty($logged) && is_array($logged)) {
        foreach ($logged as $item) {
            $item['visibility'] = 'logged_in';
            $merged[] = $item;
        }
    }
    if (!empty($guest) && is_array($guest)) {
        foreach ($guest as $item) {
            $item['visibility'] = 'logged_out';
            $merged[] = $item;
        }
    }
    if (!empty($merged)) {
        update_option('menux_menu_items', $merged);
    }
    delete_option('menux_menu_logged');
    delete_option('menux_menu_guest');
    update_option('menux_migrated_to_v7', true);
}
add_action('admin_init', 'menux_maybe_migrate');

/**
 * Flush version-keyed caches when the plugin files are updated.
 * Ensures changes such as the built-in EN/IT/RU language set take effect
 * immediately after an upgrade instead of waiting for transients to expire.
 */
function menux_maybe_flush_on_upgrade() {
    if ( get_option( 'menux_installed_version' ) === MENUX_VERSION ) return;
    delete_transient( 'menux_supported_languages' );
    if ( function_exists( 'menux_invalidate_css_cache' ) ) {
        menux_invalidate_css_cache();
    }
    update_option( 'menux_installed_version', MENUX_VERSION );
}
add_action( 'admin_init', 'menux_maybe_flush_on_upgrade' );

