<?php
/**
 * Nav menu helper: resolve and manage PufferGo's own menus.
 *
 * PufferGo owns two menu locations:
 *   - puffergo_primary  → Header navigation
 *   - puffergo_footer   → Footer sections
 *
 * No fallback to theme locations or FSE wp_navigation.
 *
 * @package PufferGo
 */

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

// ─── 共享：菜单 ID 解析（位置 → 按名 fallback → 自修复）─────────

/**
 * Resolve menu ID for a location: check nav_menu_locations first,
 * fallback to finding the menu by name, and auto-repair the binding.
 *
 * @param string $location  Nav menu location slug (e.g. 'puffergo_primary').
 * @param string $menu_name Menu name for fallback lookup (e.g. 'PufferGo Header').
 * @return int Menu term ID, or 0 if not found.
 */
function puffergo_resolve_menu_id( $location, $menu_name ) {
	$locations = get_nav_menu_locations();
	if ( ! is_array( $locations ) ) {
		$locations = array();
	}
	if ( ! empty( $locations[ $location ] ) ) {
		return (int) $locations[ $location ];
	}

	// Fallback: 按菜单名查找（主题自定义器保存时可能覆盖 nav_menu_locations）
	$menu_obj = wp_get_nav_menu_object( $menu_name );
	if ( $menu_obj && isset( $menu_obj->term_id ) ) {
		$menu_id = (int) $menu_obj->term_id;
		// 自修复：重新绑定位置
		$locations[ $location ] = $menu_id;
		set_theme_mod( 'nav_menu_locations', $locations );
		return $menu_id;
	}

	return 0;
}

// ─── 菜单读取 ──────────────────────────────────────────────

/**
 * Get menu items for the header (with sub-menus).
 * Cached per request.
 *
 * @return array Tree of objects with url, title, object_id, object, children.
 */
function puffergo_get_header_menu_items() {
	static $cached = null;
	if ( null !== $cached ) {
		return $cached;
	}
	$cached = puffergo_get_menu_tree( 'puffergo_primary', 'PufferGo Header' );
	return $cached;
}

/**
 * Get a menu as a tree (with ->children).
 *
 * @param string $location  Nav menu location slug.
 * @param string $menu_name Menu name for fallback lookup.
 * @return array Tree of stdClass with url, title, object_id, object, children.
 */
function puffergo_get_menu_tree( $location, $menu_name ) {
	$menu_id = puffergo_resolve_menu_id( $location, $menu_name );
	if ( $menu_id <= 0 ) {
		return array();
	}

	$menu_items = wp_get_nav_menu_items( $menu_id );
	if ( ! is_array( $menu_items ) || empty( $menu_items ) ) {
		return array();
	}

	$by_parent = array();
	foreach ( $menu_items as $item ) {
		$pid = (int) $item->menu_item_parent;
		if ( ! isset( $by_parent[ $pid ] ) ) {
			$by_parent[ $pid ] = array();
		}
		$by_parent[ $pid ][] = $item;
	}

	return puffergo_build_menu_tree( $by_parent, 0 );
}

/**
 * Build menu tree from items grouped by parent.
 *
 * @param array $by_parent Map of parent_id => array of menu item objects.
 * @param int   $parent_id Parent ID (0 for top-level).
 * @return array Items with ->children.
 */
function puffergo_build_menu_tree( array $by_parent, $parent_id ) {
	$items = isset( $by_parent[ $parent_id ] ) ? $by_parent[ $parent_id ] : array();
	if ( empty( $items ) ) {
		return array();
	}
	usort( $items, function ( $a, $b ) {
		return ( (int) $a->menu_order ) - ( (int) $b->menu_order );
	} );
	$out = array();
	foreach ( $items as $item ) {
		$obj             = new stdClass();
		$obj->url        = $item->url;
		$obj->title      = $item->title;
		$obj->object_id  = isset( $item->object_id ) ? (int) $item->object_id : 0;
		$obj->object     = isset( $item->object ) ? $item->object : '';
		$obj->children   = puffergo_build_menu_tree( $by_parent, (int) $item->ID );
		$out[]           = $obj;
	}
	return $out;
}

// ─── 菜单管理（写入端，供 Step5 和钩子使用）────────────────────

/**
 * Ensure the PufferGo Header menu exists and is bound to puffergo_primary location.
 * Creates the menu if it doesn't exist. Returns the menu term ID.
 *
 * @return int Menu ID, or 0 on failure.
 */
function puffergo_ensure_primary_menu() {
	$menu_id = puffergo_resolve_menu_id( 'puffergo_primary', 'PufferGo Header' );
	if ( $menu_id > 0 ) {
		return $menu_id;
	}

	// Menu doesn't exist yet — create it
	$created = wp_create_nav_menu( 'PufferGo Header' );
	if ( is_wp_error( $created ) ) {
		return 0;
	}
	$menu_id = (int) $created;

	$locations = get_nav_menu_locations();
	if ( ! is_array( $locations ) ) {
		$locations = array();
	}
	$locations['puffergo_primary'] = $menu_id;
	set_theme_mod( 'nav_menu_locations', $locations );

	return $menu_id;
}

/**
 * Ensure the PufferGo Footer menu exists and is bound to puffergo_footer location.
 * Creates the menu if it doesn't exist. Returns the menu term ID.
 *
 * @return int Menu ID, or 0 on failure.
 */
function puffergo_ensure_footer_menu() {
	$menu_id = puffergo_resolve_menu_id( 'puffergo_footer', 'PufferGo Footer' );
	if ( $menu_id > 0 ) {
		return $menu_id;
	}

	$created = wp_create_nav_menu( 'PufferGo Footer' );
	if ( is_wp_error( $created ) ) {
		return 0;
	}
	$menu_id = (int) $created;

	$locations = get_nav_menu_locations();
	if ( ! is_array( $locations ) ) {
		$locations = array();
	}
	$locations['puffergo_footer'] = $menu_id;
	set_theme_mod( 'nav_menu_locations', $locations );

	return $menu_id;
}

/**
 * Add a custom-link menu item (if not already present).
 *
 * @param int    $menu_id Menu term ID.
 * @param string $title   Display label.
 * @param string $url     Full URL.
 * @return bool True if added or already present.
 */
function puffergo_add_custom_link_to_menu( $menu_id, $title, $url ) {
	$items = wp_get_nav_menu_items( $menu_id );
	if ( is_array( $items ) ) {
		foreach ( $items as $item ) {
			if ( $item->type === 'custom' && $item->url === $url ) {
				return true;
			}
		}
	}

	$result = wp_update_nav_menu_item( $menu_id, 0, array(
		'menu-item-title'  => $title,
		'menu-item-url'    => $url,
		'menu-item-type'   => 'custom',
		'menu-item-status' => 'publish',
	) );

	return ! is_wp_error( $result );
}

/**
 * Add a post_type menu item (if not already present).
 *
 * @param int    $menu_id   Menu term ID.
 * @param int    $object_id Post/Page ID.
 * @param string $title     Display label (optional, defaults to post title).
 * @return bool True if added or already present.
 */
function puffergo_add_page_to_menu( $menu_id, $object_id, $title = '' ) {
	$items = wp_get_nav_menu_items( $menu_id );
	if ( is_array( $items ) ) {
		foreach ( $items as $item ) {
			if ( (int) $item->object_id === (int) $object_id ) {
				return true;
			}
		}
	}

	if ( '' === $title ) {
		$title = get_the_title( $object_id );
	}

	$result = wp_update_nav_menu_item( $menu_id, 0, array(
		'menu-item-title'     => $title,
		'menu-item-object'    => 'page',
		'menu-item-object-id' => $object_id,
		'menu-item-type'      => 'post_type',
		'menu-item-status'    => 'publish',
	) );

	return ! is_wp_error( $result );
}
