<?php
/**
 * Nav menu location cleanup handlers.
 *
 * @package WPR_Translate
 */

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

if ( ! function_exists( 'wpr_translation_cleanup_nav_menu_locations_on_delete' ) ) {
    /**
     * Removes deleted menus from the stored language-aware assignments.
     *
     * @param int $menu_id Deleted menu identifier.
     */
    function wpr_translation_cleanup_nav_menu_locations_on_delete( $menu_id ) {
        // Normalize the menu ID.
        $menu_id = absint( $menu_id );

        if ( $menu_id <= 0 ) {
            // Invalid menu ID.
            return;
        }

        // Load stored locations and remove the deleted menu ID.
        $stored  = wpr_translation_get_stored_nav_menu_locations();
        $changed = false;

        foreach ( $stored as $location => $languages ) {
            if ( ! is_array( $languages ) ) {
                continue;
            }

            foreach ( $languages as $code => $assigned_menu_id ) {
                if ( (int) $assigned_menu_id === $menu_id ) {
                    // Remove the deleted menu from this language assignment.
                    unset( $stored[ $location ][ $code ] );
                    $changed = true;
                }
            }

            if ( isset( $stored[ $location ] ) && empty( $stored[ $location ] ) ) {
                // Remove empty location entries.
                unset( $stored[ $location ] );
                $changed = true;
            }
        }

        if ( ! $changed ) {
            // Nothing to update.
            return;
        }

        // Persist updated locations and re-sync translations.
        wpr_translation_update_nav_menu_locations_storage( $stored );
        wpr_translation_sync_nav_menu_translations_from_locations( $stored );
    }

    add_action( 'wp_delete_nav_menu', 'wpr_translation_cleanup_nav_menu_locations_on_delete', 20 );
}
