<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * Scan & update navigation menu item labels.
 *
 * @since 2.2.0
 */
class AI_Magic_Menus_Scanner {

    /**
     * Collect all nav menu item titles.
     *
     * @return array
     */
    public function get_items() {
        $items = array();

        $menus = wp_get_nav_menus();
        if ( empty( $menus ) || is_wp_error( $menus ) ) {
            return $items;
        }

        foreach ( $menus as $menu ) {
            $menu_items = wp_get_nav_menu_items( $menu->term_id );
            if ( empty( $menu_items ) ) {
                continue;
            }

            foreach ( $menu_items as $menu_item ) {
                $label = isset( $menu_item->title ) ? $menu_item->title : $menu_item->post_title;
                if ( ! is_string( $label ) ) {
                    continue;
                }
                $raw = trim( wp_strip_all_tags( $label ) );
                if ( $raw === '' || strlen( $raw ) < 2 ) {
                    continue;
                }

                $items[] = array(
                    'id'    => $menu_item->ID,
                    'value' => $label,
                );
            }
        }

        return $items;
    }

    /**
     * Apply AI-generated labels back to nav menu items.
     *
     * @param array $items
     * @param array $new_values
     * @return void
     */
    public function apply_new_values( array $items, array $new_values ) {

        foreach ( $items as $index => $item ) {
            if ( ! isset( $new_values[ $index ] ) ) {
                continue;
            }

            $new_label = $new_values[ $index ];
            $post_arr  = array(
                'ID'         => $item['id'],
                'post_title' => $new_label,
            );

            wp_update_post( $post_arr );
        }
    }

}
