<?php

// Get menu object by location
if ( ! function_exists( 'wpj_get_menu_by_location' ) ) {
	function wpj_get_menu_by_location( $location ) {
		$ret_menu = [];

		$locations = get_nav_menu_locations(); // get all locations

		if ( isset( $locations[$location] ) ) {
			$object    = wp_get_nav_menu_object( $locations[$location] ); // get object id by location
			$main_menu = isset( $object->name ) ? wp_get_nav_menu_items( $object->name ) : ''; // get menu items by menu name

			if ( $main_menu ) {
				if ( ! function_exists( 'wpj_build_menu_structure_from_wp_menu' ) ) {
					function wpj_build_menu_structure_from_wp_menu( $menu_items, $parent_id = 0 ) {
						$menu_structure = [];

						foreach ( $menu_items as $menu_item ) {
							if ( $menu_item->menu_item_parent == $parent_id ) {
								$item = [
									'id'      => $menu_item->ID,
									'label'   => $menu_item->title,
									'url'     => $menu_item->url,
									'childs'  => wpj_build_menu_structure_from_wp_menu( $menu_items, $menu_item->ID ),
									'classes' => implode( ' ', $menu_item->classes ),
									'order'   => $menu_item->menu_order
								];

								$menu_structure[] = $item;
							}
						}

						return $menu_structure;
					}
				}

				$ret_menu = wpj_build_menu_structure_from_wp_menu( $main_menu );
			}
		}

		$ret_menu = apply_filters( 'wp_nav_menu_args', $ret_menu );
		$ret_menu = apply_filters( 'wpj_' . $location . '_filter', $ret_menu );

		return $ret_menu;
	}
}

// Get menu id by slug
if ( ! function_exists( 'wpj_get_menu_id_by_slug' ) ) {
	function wpj_get_menu_id_by_slug( $menu ) {
		$menu_object = wp_get_nav_menu_object( $menu );

		return isset( $menu_object->term_id ) ? $menu_object->term_id : false;
	}
}

// Get menu id by location
if ( ! function_exists( 'wpj_get_menu_id_by_location' ) ) {
	function wpj_get_menu_id_by_location( $location ) {
		$locations = get_nav_menu_locations();

		if ( in_array( $location, $locations ) ) {
			return $locations[ $location ];

		} else {
			return false;

		}
	}
}

// Sort menu
if ( ! function_exists( 'wpj_sort_menu' ) ) {
	function wpj_sort_menu( $array, $order ) {
		if ( strtolower( $order ) == strtolower( 'asc' ) ) {
			usort( $array, function ( $item1, $item2 ) {
				return $item1['order'] < $item2['order'] ? 1 : -1;
			});

		} else {
			usort( $array, function ( $item1, $item2 ) {
				return $item1['order'] > $item2['order'] ? 1 : -1;
			});

		}

		return $array;
	}
}

/* WP */
if ( ! function_exists( 'wpj_add_custom_class_to_nav_menu' ) ) {
	function wpj_add_custom_class_to_nav_menu( $classes, $item ) {
		$classes[] = "custom-class-" . $item->menu_order;

		return $classes;
	}
}

if ( ! function_exists( 'wpj_add_custom_class_to_last_item_nav_menu' ) ) {
    function wpj_add_custom_class_to_last_item_nav_menu( $str_HTML ) {
        $intPos = strripos( $str_HTML, 'menu-item' );

        // Check if 'menu-item' is found in the string
        if ( false !== $intPos ) {
            $modified_HTML = sprintf(
                "%s last_item %s",
                substr( $str_HTML, 0, $intPos ),
                substr( $str_HTML, $intPos )
            );

            return $modified_HTML;
        }

        // Return unmodified HTML if 'menu-item' is not found
        return $str_HTML;
    }
}

if ( ! function_exists( 'wpj_add_custom_class_to_first_last_item_nav_menu' ) ) {
    function wpj_add_custom_class_to_first_last_item_nav_menu( $output ) {
        if ( $output ) {
            // Add 'first-menu-item' to the first occurrence of 'class="menu-item"'
            $output = preg_replace( '/class="([^"]*)menu-item/', 'class="first-menu-item $1menu-item', $output, 1 );

            // Add 'last-menu-item' to the last occurrence of 'class="menu-item"'
            $lastPos = strripos( $output, 'class="menu-item' );
            if ( false !== $lastPos ) {
                $output = substr_replace( $output, ' last-menu-item', $lastPos + strlen( 'class="menu-item' ), 0 );
            }
        }

        return $output;
    }
}

if ( ! function_exists( 'wpj_add_class_to_parent_nav_menu' ) ) {
	function wpj_add_class_to_parent_nav_menu( $classes, $item ) {
		global $dd_depth, $dd_children;

		$classes[] = 'depth' . $dd_depth;

		if ( $dd_children ) {
			$classes[] = 'parent';
		}

		return $classes;
	}
}

if ( ! function_exists( 'wpj_add_active_class_to_nav_menu' ) ) {
	function wpj_add_active_class_to_nav_menu( $nav_menu, $args ) {
		if ( in_array( $args->theme_location, [
			'wpjobster_responsive_left_menu',
			'wpjobster_responsive_left_loggedin_menu',
			'wpjobster_responsive_right_menu',
			'wpjobster_responsive_right_loggedin_menu',
		] ) ) {
			return preg_replace( '/<a /', '<a class="item" ', $nav_menu );

		} else {
			return $nav_menu;

		}
	}
}

class WalkerMainNavMenu extends Walker_Nav_Menu {
	private $total_parents;
	private $total_children;
	private $current_element_position;

	function start_lvl( &$output, $depth = 0, $args = [] ) {
		$jobster_design = wpj_get_design_option();

		$menu_open_postition = $this->current_element_position <= ceil( $this->total_parents / 2 ) ? ' left0' : ' right0';

		$split_class = '';

		if ( $args->theme_location == 'wpjobster_header_secondary_menu' || $args->theme_location == 'wpjobster_header_secondary_loggedin_menu' ) {
			if ( isset( $jobster_design['secondarymenu_style'] ) ) {
				$split_class = $this->total_children >= 6 ? ' ul-multiple-columns' : ' ul-single-column';

				if ( $this->total_children >= 6 ) {
					$split_class .= ' ul-multiple-columns--' . $jobster_design['secondarymenu_style'];
				}
			}

		} else {
			if ( isset( $jobster_design['menu_style'] ) ) {
				$split_class = $this->total_children >= 6 ? ' ul-multiple-columns' : ' ul-single-column';

				if ( $this->total_children >= 6 ) {
					$split_class .= ' ul-multiple-columns--' . $jobster_design['menu_style'];
				}
			}

			if ( isset( $jobster_design['main_menu_submenu_items_alignment'] ) ) {
				if ( $jobster_design['main_menu_submenu_items_alignment'] == 'left' )
					$split_class .= ' text-left';

				if ( $jobster_design['main_menu_submenu_items_alignment'] == 'right' )
					$split_class .= ' text-right';
			}
		}

		$indent = str_repeat( "\t", $depth );
		$output .= "\n" . $indent . '<ul class="sub-menu' . $split_class . ' ' . $menu_open_postition . '">' . "\n";
	}

	public function display_element( $element, &$children_elements, $max_depth, $depth, $args, &$output ) {
		if ( ! $element ) return;

		if ( $element->menu_item_parent === '0' ) $this->current_element_position++;

		$id_field = $this->db_fields['id'];
		$id       = $element->$id_field;

		$this->total_children = 0;

		if ( ! empty( $children_elements[$id] ) )
			$this->total_children = count( $children_elements[$id] );

		parent::display_element( $element, $children_elements, $max_depth, $depth, $args, $output );
	}

	public function walk( $elements, $max_depth, ...$args ) {
		$parent_field = $this->db_fields['parent'];

		$this->total_parents = 0;

		foreach ( $elements as $e ) {
			if ( empty( $e->$parent_field ) )
				$this->total_parents++;
		}

		return parent::walk( $elements, $max_depth, ...$args );
	}
}