<?php

namespace Greyd\Navigation;

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

class Offcanvas_Menu_Walker extends \Walker_Nav_Menu {

	protected $submenu_id = '';

	/**
	 * Display an element
	 */
	function display_element( $element, &$children_elements, $max_depth, $depth, $args, &$output ) {
		if ( ! $element ) {
			return;
		}

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

		// display this element
		if ( is_array( $args[0] ) ) {
			$args[0]['has_children'] = ! empty( $children_elements[ $element->$id_field ] );
		}
		elseif ( is_object( $args[0] ) ) {
			$args[0]->has_children = ! empty( $children_elements[ $element->$id_field ] );
		}

		$cb_args = array_merge( array( &$output, $element, $depth ), $args );
		call_user_func_array( array( &$this, 'start_el' ), $cb_args );

		$id = $element->$id_field;

		// descend only when the depth is right and there are childrens for this element
		if ( ( $max_depth == 0 || $max_depth > $depth + 1 ) && isset( $children_elements[ $id ] ) ) {

			foreach ( $children_elements[ $id ] as $child ) {

				if ( ! isset( $newlevel ) ) {
					$this->submenu_id = "off-submenu-{$element->ID}";

					$newlevel = true;

					// start the child delimiter
					$cb_args = array_merge( array( &$output, $depth ), $args );
					call_user_func_array( array( &$this, 'start_lvl' ), $cb_args );
				}
				$this->display_element( $child, $children_elements, $max_depth, $depth + 1, $args, $output );
			}
			unset( $children_elements[ $id ] );
		}

		if ( isset( $newlevel ) && $newlevel ) {
			// end the child delimiter
			$cb_args = array_merge( array( &$output, $depth ), $args );
			call_user_func_array( array( &$this, 'end_lvl' ), $cb_args );
		
			$this->submenu_id = "";
		}

		// end this element
		$cb_args = array_merge( array( &$output, $element, $depth ), $args );
		call_user_func_array( array( &$this, 'end_el' ), $cb_args );
	}

	/**
	 * Start new sublevel.
	 */
	public function start_lvl( &$output, $depth = 0, $args = null ) {

		// make link a toggle button
		$output = preg_replace_callback(
			'/(<a.+?"\s?>)(.+?)<\/a>$/',
			function( $matches ) {
				return sprintf(
					'<a tabindex="0" role="button" aria-expanded="false" aria-controls="%s" aria-label="%s">%s</a>',
					esc_attr( $this->submenu_id ),
					sprintf( __( "Zeige Menü-Unterpunkte von '%s'", "core" ), strip_tags( $matches[2] ) ),
					$matches[2]
				);
			},
			$output
		);
		// debug( esc_attr( $new_output ) );
		// echo '<hr>';

		$output .= sprintf(
			'<ul class="sub-menu" id="%s">',
			esc_attr( $this->submenu_id )
		);
	}

	/**
	 * End sublevel.
	 */
	function end_lvl( &$output, $depth = 0, $args = null ) {
		$output .= '</ul>';
	}
}
