<?php
class NavWalker extends Walker_Nav_Menu {
	private $collapsible = false;
	private $submenu_stack = []; // نمرر id للـ sub-menu بين start_el و start_lvl

	public function __construct($collapsible = false){
		$this->collapsible = (bool) $collapsible;
	}

	private function attrs($arr){
		$out='';
		foreach($arr as $k=>$v){ if($v!=='') $out.=" $k=\"".esc_attr($v)."\""; }
		return $out;
	}

	public function start_lvl( &$output, $depth = 0, $args = [] ) {
		$depth = (int)$depth;
		$submenu_id = end($this->submenu_stack); // آخر id تم دفعه
		$id_attr    = $submenu_id ? ' id="'.esc_attr($submenu_id).'"' : '';
		$hidden     = $this->collapsible ? ' hidden' : ''; // موبايل فقط
		$output    .= '<ul'.$id_attr.' class="sub-menu list-unstyled depth-'.$depth.'"'.$hidden.'>'."\n";
	}

	public function end_lvl( &$output, $depth = 0, $args = [] ) {
		array_pop($this->submenu_stack);
		$output .= "</ul>\n";
	}

	public function start_el( &$output, $item, $depth = 0, $args = [], $id = 0 ) {
		$classes = empty($item->classes) ? [] : (array)$item->classes;
		$classes[] = 'menu-item-'.$item->ID;

		if (in_array('current-menu-item', $classes)) {
			$classes[] = 'active';
		}

		$has_children = in_array('menu-item-has-children', $classes);
		if ($has_children) {
			$classes[] = 'has-dropdown';
		}

		$link_id    = 'menu-link-'.$item->ID;
		$submenu_id = $has_children ? 'submenu-'.$item->ID : '';

		// خزن الـ submenu id عشان start_lvl يحطه
		if ($has_children) {
			$this->submenu_stack[] = $submenu_id;
		}

		$atts = [
			'id'    => $link_id,
			'title' => $item->attr_title ?: '',
			'target'=> $item->target ?: '',
			'rel'   => $item->xfn ?: '',
			'href'  => $item->url ?: '#',
		];

		// ARIA وزر التبديل للموبايل/السايدبار فقط
		if ($this->collapsible && $has_children) {
			$atts['aria-haspopup'] = 'true';
			$atts['aria-controls'] = $submenu_id;
			$atts['aria-expanded'] = 'false';
		}

		$output .= "\n<li class=\"menu-item ".esc_attr(implode(' ', array_filter($classes)))."\">";
		$output .= '<a'.$this->attrs($atts).'><span class="menu-text">'.esc_html($item->title).'</span>';

		if ($this->collapsible && $has_children) {
			$output .= '<button type="button" class="dd-trigger" aria-label="toggle submenu" aria-controls="'.esc_attr($submenu_id).'" aria-expanded="false"></button>';
		}

		$output .= '</a>';
	}

	public function end_el( &$output, $item, $depth = 0, $args = [] ) {
		$output .= "</li>\n";
	}
}
