<?php
namespace BricksUltimate;

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

/**
 * Walker for Category
 * Adding the Back button and managing the classes
 */
class BuSlidingMenuCategoryWalker extends \Walker_Category {

	public function start_lvl( &$output, $depth = 0, $args = array() ) {
        if ( 'list' !== $args['style'] ) {
            return;
        }
        
        $output .= "<ul class='sub-menu bu-slide-menu-sub-menu'>\n";
		$output .= '<li class="menu-item bu-slide-menu-item bu-slide-menu-back" aria-expanded="false" aria-pressed="false" aria-hidden="true">' . 
					$args['back_arrow_icon'] . '<span class="bu-menu-sub-item-back" role="button" aria-label="hidden">Back</span></li>' . "\n";
    }

	public function start_el( &$output, $category, $depth = 0, $args = array(), $id = 0 ) {
		$cat_name = apply_filters(
			'list_cats',
			esc_attr( $category->name ),
			$category
		);

		// Don't generate an element if the category name is empty.
		if ( ! $cat_name ) {
			return;
		}

		if ( 'list' == $args['style'] ) {
			$link = '<a href="' . esc_url( get_term_link( $category ) ) . '" class="bu-slide-menu-item-link" itemprop="url" data-title="' . esc_attr( $cat_name ) . '">';
			$link .= '<span itemprop="name">' . $cat_name . '</span></a>';

			$output .= "\t<li";
			$css_classes = array(
				'menu-item',
				'cat-item',
				'cat-item-' . $category->term_id,
				'bu-slide-menu-item'
			);

			$termchildren = get_term_children( $category->term_id, $category->taxonomy );

			if( count($termchildren) > 0 ) {
				$css_classes[] =  'menu-item-has-children';
				$css_classes[] =  'bu-slide-menu-item-has-children';
			}

			if ( ! empty( $args['current_category'] ) ) {
				$_current_category = get_term( $args['current_category'], $category->taxonomy );
				if ( $category->term_id == $args['current_category'] ) {
					$css_classes[] = 'current-menu-item bu-slide-menu-item-current';
				} elseif ( $category->term_id == $_current_category->parent ) {
					$css_classes[] = 'current-menu-ancestor';
				}
			}

			$css_classes = implode( ' ', apply_filters( 'sliding_category_css_class', $css_classes, $category, $depth, $args ) );

			$output .=  ' class="' . $css_classes . '"';
			$output .= ">" . $args['arrow_icon'] . "\n$link\n";
		} else {
            $output .= "\t$link<br />\n";
        }
	}
}