<?php
/**
 * File: modules/menu-structure-check.php
 */

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

// If your utilities aren't already loaded globally, uncomment this:
// require_once plugin_dir_path(__FILE__) . '../includes/sac-utils.php';

add_action('rest_api_init', function () {
    register_rest_route('myaio/v1', '/menu-structure-check', [
        'methods'             => WP_REST_Server::READABLE,
        'callback'            => 'myaio_sac_menu_structure_check',

        // ✅ Key validation (x-api-key / ?key= / ?api_key=)
        'permission_callback' => 'myaio_sac_rest_permission_check',

        'args' => [
            // Optional: include menu items or not (for lightweight calls)
            'include_items' => [
                'type'              => 'boolean',
                'default'           => true,
                'sanitize_callback' => 'rest_sanitize_boolean',
            ],
        ],
    ]);
});

/**
 * Convert flat menu items array into a tree.
 */
function myaio_sac_build_menu_tree($items) {
    $menu_tree   = [];
    $items_by_id = [];

    foreach ($items as $it) {
        $items_by_id[$it->ID] = [
            'ID'               => (int) $it->ID,
            'title'            => (string) $it->title,
            'url'              => (string) $it->url,
            'type'             => (string) $it->type,
            'object'           => (string) $it->object,
            'object_id'        => (int) $it->object_id,
            'menu_item_parent' => (int) $it->menu_item_parent,
            'sub_menus'        => [],
        ];
    }

    $has_submenu = false;

    foreach ($items_by_id as $id => &$node) {
        $parent_id = (int) $node['menu_item_parent'];

        if ($parent_id > 0 && isset($items_by_id[$parent_id])) {
            $items_by_id[$parent_id]['sub_menus'][] = &$node;
            $has_submenu = true;
        } else {
            $menu_tree[] = &$node;
        }
    }
    unset($node);

    return [$menu_tree, $has_submenu];
}

function myaio_sac_menu_structure_check(WP_REST_Request $request) {

    $include_items = (bool) $request->get_param('include_items');

    // Menus assigned to theme locations: [location_key => menu_term_id]
    $assigned = get_nav_menu_locations();

    // All registered theme locations: [location_key => label]
    $registered = function_exists('get_registered_nav_menus') ? get_registered_nav_menus() : [];

    $results = [];

    // If theme didn't register locations (rare), fallback to listing all menus
    if (empty($registered)) {
        $menus = wp_get_nav_menus();

        foreach ($menus as $menu_obj) {
            $items = wp_get_nav_menu_items($menu_obj->term_id, ['update_post_term_cache' => false]) ?: [];
            [$tree, $has_submenu] = myaio_sac_build_menu_tree($items);

            $results[] = [
                'location_key'       => null,
                'location_label'     => null,
                'is_assigned'        => true,
                'menu_name'          => $menu_obj->name,
                'menu_id'            => (int) $menu_obj->term_id,
                'has_submenu'        => $has_submenu,
                'menu_items'         => $include_items ? $tree : [],
                'seo_recommendation' => $has_submenu
                    ? '✅ Good menu hierarchy for SEO (submenu detected)'
                    : '⚠️ No submenu structure — consider improving hierarchy for better SEO',
            ];
        }

        return rest_ensure_response([
            'summary' => [
                'total_locations_registered' => 0,
                'total_locations_assigned'   => count($assigned),
                'total_results'              => count($results),
                'results_with_submenus'      => count(array_filter($results, fn($r) => !empty($r['has_submenu']))),
                'results_without_submenus'   => count(array_filter($results, fn($r) => empty($r['has_submenu']))),
            ],
            'results' => $results,
        ]);
    }

    // Normal case: iterate every registered location
    foreach ($registered as $location_key => $location_label) {

        $menu_id = isset($assigned[$location_key]) ? (int) $assigned[$location_key] : 0;

        $menu_obj = $menu_id ? wp_get_nav_menu_object($menu_id) : null;
        $items    = $menu_id ? (wp_get_nav_menu_items($menu_id, ['update_post_term_cache' => false]) ?: []) : [];

        [$tree, $has_submenu] = myaio_sac_build_menu_tree($items);

        $results[] = [
            'location_key'       => (string) $location_key,
            'location_label'     => (string) $location_label,
            'is_assigned'        => (bool) $menu_id,
            'menu_name'          => $menu_obj ? $menu_obj->name : '(Not assigned)',
            'menu_id'            => $menu_id ?: null,
            'has_submenu'        => $has_submenu,
            'menu_items'         => $include_items ? $tree : [],
            'seo_recommendation' => !$menu_id
                ? '⚠️ Location exists but no menu assigned (Appearance → Menus → Manage Locations)'
                : ($has_submenu
                    ? '✅ Good menu hierarchy for SEO (submenu detected)'
                    : '⚠️ No submenu structure — consider improving hierarchy for better SEO'),
        ];
    }

    return rest_ensure_response([
        'summary' => [
            'total_locations_registered' => count($registered),
            'total_locations_assigned'   => count($assigned),
            'total_results'              => count($results),
            'results_with_submenus'      => count(array_filter($results, fn($r) => !empty($r['has_submenu']))),
            'results_without_submenus'   => count(array_filter($results, fn($r) => empty($r['has_submenu']))),
        ],
        'results' => $results,
    ]);
}
