<?php

declare(strict_types=1);

namespace AC\Helper;

use WP_Term;

class Menu extends Creatable
{
    public function get_label(int $menu_item_id): string
    {
        global $wpdb;

        return (string)$wpdb->get_var(
            $wpdb->prepare(
                "
			SELECT t.name
				FROM $wpdb->terms AS t
				INNER JOIN $wpdb->term_taxonomy AS tt ON tt.term_id = t.term_id
				INNER JOIN $wpdb->term_relationships AS tr ON tr.term_taxonomy_id = tt.term_taxonomy_id
				INNER JOIN $wpdb->posts AS menu ON menu.ID = tr.object_id
				    AND menu.post_type = 'nav_menu_item'
    			WHERE menu.ID = %d
			",
                $menu_item_id
            )
        );
    }

    /**
     * The `nav_menu_item` post IDs that reference the given object.
     *
     * @return int[]
     */
    public function get_item_ids(int $object_id, string $object_type): array
    {
        return get_posts([
            'post_type'      => 'nav_menu_item',
            'posts_per_page' => -1,
            'post_status'    => 'publish',
            'fields'         => 'ids',
            'meta_query'     => [
                [
                    'key'   => '_menu_item_object_id',
                    'value' => $object_id,
                ],
                [
                    'key'   => '_menu_item_object',
                    'value' => $object_type,
                ],
            ],
        ]);
    }

    /**
     * The `nav_menu` terms the given object is assigned to.
     *
     * @return array<int|string|WP_Term> Terms, term IDs when `$args['fields']` is `ids`, or term names/slugs for other `fields` values.
     * @see WP_Term_Query::__construct() for supported arguments.
     *
     */
    public function get_terms(int $object_id, string $object_type, array $args = []): array
    {
        $object_ids = $this->get_item_ids($object_id, $object_type);

        if (! $object_ids) {
            return [];
        }

        $terms = wp_get_object_terms($object_ids, 'nav_menu', $args);

        if (! $terms || is_string($terms) || is_wp_error($terms)) {
            return [];
        }

        return $terms;
    }

}
