<?php
namespace Prodigy\Includes\Content;

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

use Prodigy\Includes\Prodigy;

/**
 * Set user content class
 *
 * @version    3.0.8
 * @package    Prodigy
 * @subpackage Prodigy/includes
 */
class Prodigy_User_Content {
	public function __construct() {
		add_filter( 'wp_nav_menu_objects', array( $this, 'pg_nav_menu_items' ) );
	}


	/**
	 * @param array $menu_items
	 *
	 * @return array
	 */
	public function pg_nav_menu_items( array $menu_items ): array {
		$categories = $this->get_user_categories();

		return $this->set_user_categories_list( $menu_items, $categories['data'] ?? array() );
	}

	/**
	 * @param array $menu_items
	 * @param array $categories
	 *
	 * @return array
	 */
	private function set_user_categories_list( array $menu_items, array $categories ): array {
		foreach ( $menu_items as $key => $item ) {
			$found = false;
			foreach ( $categories as $category ) {
				if ( $item->object === Prodigy::get_prodigy_category_type() ) {
					$term = get_term_by( 'id', $item->object_id, Prodigy::get_prodigy_category_type() );
					if ( $term && isset( $category['attributes']['slug'], $term->slug ) && $category['attributes']['slug'] === $term->slug ) {
						$found = true;
						break;
					}
				}
			}
			if ( ! $found && $item->object === Prodigy::get_prodigy_category_type() ) {
				unset( $menu_items[ $key ] );
			}
		}

		return $menu_items;
	}

	/**
	 * @return array
	 */
	private function get_user_categories(): array {
		return Prodigy_Request_Maker::get_instance()->do_categories_request();
	}
}
