<?php

namespace yndenz\Modules\Navigation;

use stdClass;
use WP_Post;

class NavBootstrap extends NavNonClickables {

    /**
     * Add dropdown attributes to the menu.
     *
     * @see Walker::start_lvl()
     * @since 3.0.0
     *
     * @param string $output Passed by reference. Used to append additional content.
     * @param int $depth Depth of page. Used for padding.
     * @param array $args
     */
    public function start_lvl(&$output, $depth = 0, $args = array()) {
        $indent = str_repeat("\t", $depth);

        $id = '';
        if (isset($args->dropdown_id) && $args->dropdown_id) {
            $id = ' id="' . $args->dropdown_id . '"';
        }

        $output .= "\n" . $indent . '<ul role="menu" class="dropdown-menu"' . $id . ">\n";
    }

    /**
     * Add dropdown classes to the item.
     *
     * @param WP_Post $item
     * @param stdClass $args
     *
     * @return array
     */
    protected function item_get_classes($item, $args) {
        if (empty($item->classes)) {
            $item->classes = array();
        }

        if (!is_array($item->classes)) {
            $item->classes = (array)$item->classes;
        }

        if ($args->has_children) {
            array_push($item->classes, 'dropdown');
        }
        if (in_array('current-menu-item', $item->classes)) {
            array_push($item->classes, 'active');
        }

        return parent::item_get_classes($item, $args);
    }

    /**
     * Add dropdown caret to the anchor.
     *
     * @param WP_Post $item Menu item data object.
     * @param int $depth Depth of menu item. Used for padding.
     * @param stdClass $args An object of wp_nav_menu() arguments.
     *
     * @return string
     */
    protected function build_anchor($item, $depth, $args) {
        if ($args->has_children) {
            if ($depth > 0) {
                $dropdown_toggle_atts = ' class="submenu-toggle"';
            } else {
                $dropdown_toggle_atts = ' data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" class="dropdown-toggle"';
                if (isset($args->dropdown_id) && $args->dropdown_id) {
                    $dropdown_toggle_atts .= ' data-target="' . $args->dropdown_id . '"';
                }
            }

            if (!property_exists($item, 'link_extra_after')) {
                $item->link_extra_after = '';
            }

            $item->link_extra_after .= '</a> <a title="' . $item->attr_title . '" href="#"' . $dropdown_toggle_atts . '><span class="caret"></span>';
        }

        return parent::build_anchor($item, $depth, $args);
    }

}