<?php namespace Fusio\Multilingual\Walkers;

class AdminMultilingualMenuWalker extends \Walker_Nav_Menu {
    public $menuSlugForViewsDirectory;

    function __construct() {
        parent::__construct();
        $this -> menuSlugForViewsDirectory = "admin-ml-walker";
        $this -> registerViewDirectory();
    }

    function start_el(&$output, $item, $depth = 0, $args = array(), $id = 0) {
        global $_wp_nav_menu_max_depth;
        // If for some mad reason we need to override the max depth constant we could change the default
        // value above
        $_wp_nav_menu_max_depth = $depth > $_wp_nav_menu_max_depth ? $depth : $_wp_nav_menu_max_depth;

        $indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';

        ob_start();
        $item_id = esc_attr($item -> ID);
        $removed_args = ["action", "customlink-tab", "edit-menu-item", "meny-item", "page-tab", "_wpnonce"];
        $remove_args = [];

        $original_title = "";

        if("taxonomy" == $item -> type) {
            $original_title = get_term_field("name", $item -> object_id, $item -> object, "raw");
            if (is_wp_error($original_title)) { // For whatever reason (like it was deleted) the system couldn't find a term
                $original_title = false;
            }
        }

        if("post_type" == $item -> type) {
            $original_object = get_post($item -> object_id);
            $original_title = $original_title -> post_title;
        }

        $classes = [
            "menu-item menu-item-depth-$depth",
            "menu-item-" . esc_attr($item -> object),
            //menu-item-edit opens the item so it can be changed
            "menu-item-edit" . ((isset($_GET["edit-menu-item"]) && $item_id == $_GET["edit-menu-item"]) ? "active" : "inactive"),
        ];

        $title = $item -> title;

        if(!empty($item->_invalid)) {
            $classes[] = "menu-item-invalid";
            $title = sprintf( __( '%s (Invalid)' ), $item->title );
        }

        if ( isset( $item->post_status ) && 'draft' == $item->post_status ) {
            $classes[] = 'pending';
            $title = sprintf( __('%s (Pending)'), $item->title );
        }

        $title = empty($item -> label) ? $title: $item -> label;
        $irish = get_post_meta($item -> ID, "_menu_item_irish", true);
        $accesskey = get_post_meta($item -> ID, "_menu_item_accesskey", true);

        $data = compact('indent', 'removed_args', 'remove_args', 'original_object', 'original_title', 'title', 'irish', 'accesskey');
        Waiter::plates()->serve("$this->slug::menu-form", $data);
    }

    private function registerViewDirectory() {
        $viewPath = dirname(__DIR__) . "fusio-multilingual/views";
        Waiter::plates()->registerViewsFromFolder($this->menuSlugForViewsDirectory, $viewPath);
    }
}