<?php
/**
 * MenuX Free — Import from WordPress native menu
 * AJAX endpoints used by the "Import WP" tab in the admin builder.
 * @package MenuX
 */

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

add_action( 'wp_ajax_menux_get_wp_menus',   'menux_ajax_get_wp_menus' );
add_action( 'wp_ajax_menux_import_wp_menu', 'menux_ajax_import_wp_menu' );

/**
 * Returns all registered WordPress menus (name + item count).
 */
function menux_ajax_get_wp_menus() {
	if ( ! current_user_can( 'manage_options' ) ) wp_die( 'Unauthorized' );
	check_ajax_referer( 'menux_import_wp_menu_nonce', 'nonce' );

	$menus = wp_get_nav_menus();
	$result = array();
	foreach ( $menus as $menu ) {
		$result[] = array(
			'id'    => $menu->term_id,
			'name'  => $menu->name,
			'count' => $menu->count,
		);
	}
	wp_send_json_success( $result );
}

/**
 * Converts a WordPress native menu into the MenuX item tree and returns it.
 */
function menux_ajax_import_wp_menu() {
	if ( ! current_user_can( 'manage_options' ) ) wp_die( 'Unauthorized' );
	check_ajax_referer( 'menux_import_wp_menu_nonce', 'nonce' );

	$menu_id = isset( $_POST['menu_id'] ) ? absint( $_POST['menu_id'] ) : 0;
	if ( ! $menu_id ) {
		wp_send_json_error( array( 'message' => 'Invalid menu ID' ) );
		return;
	}

	$raw_items = wp_get_nav_menu_items( $menu_id );
	if ( ! $raw_items || is_wp_error( $raw_items ) ) {
		wp_send_json_error( array( 'message' => 'Could not load menu items' ) );
		return;
	}

	$tree = menux_build_wp_menu_tree( $raw_items, 0 );
	wp_send_json_success( array( 'items' => $tree ) );
}

/**
 * Recursively converts a flat array of WP_Post nav-menu items into
 * the nested tree format expected by the MenuX JS builder.
 *
 * @param WP_Post[] $items     Flat list from wp_get_nav_menu_items().
 * @param int       $parent_id ID of the parent item (0 = top level).
 * @return array
 */
function menux_build_wp_menu_tree( $items, $parent_id ) {
	$result = array();
	foreach ( $items as $item ) {
		if ( (int) $item->menu_item_parent !== $parent_id ) {
			continue;
		}

		if ( $item->type === 'post_type' && $item->object === 'page' ) {
			$type = 'page';
			$id   = (int) $item->object_id;
		} else {
			$type = 'custom';
			$id   = '';
		}

		$result[] = array(
			'type'     => $type,
			'id'       => $id,
			'label'    => $item->title,
			'url'      => $item->url,
			'target'   => $item->target,
			'children' => menux_build_wp_menu_tree( $items, (int) $item->ID ),
		);
	}
	return $result;
}
