<?php

class Tax_Terms_Order_Walker extends Walker {

    var $db_fields = array (
        'parent'    => 'parent', 
        'id'        => 'term_id',
    );

    public function start_lvl( &$output, $depth = 0, $args = array() ) {
        extract( $args, EXTR_SKIP ); 
        $indent = str_repeat( "\t", $depth );
        $output .= "\n$indent<ul class='children sortable'>\n";
    }

    public function end_lvl( &$output, $depth = 0, $args = array() ) {
        extract( $args, EXTR_SKIP );     
        $indent = str_repeat( "\t", $depth );
        $output .= "$indent</ul>\n";
    }

    public function start_el( &$output, $term, $depth = 0, $args = array(), $current_object_id = 0 ) {
        $page = isset( $_GET['page'] ) ? $_GET['page'] : '';
        $page = explode( '-', $page );
        $post_type = $page[0];

        $term_edit_link = add_query_arg( array(
            'post_type' => $post_type,
            'taxonomy'  => $term->taxonomy,
            'tag_ID'    => $term->term_id,
        ), admin_url( 'term.php' ) );
        
        if ( $depth ) {
            $indent = str_repeat( "\t", $depth );
        } else{
            $indent = '';
		}
        
        $output .= $indent . '<li class="term_type_li" id="item_'.$term->term_id.'"><div class="item"><span class="dashicons dashicons-menu"></span><a href="' . $term_edit_link . '" class="item-term">' . $term->name . '</a></div>';
    }

    /**
     * Output the closing </li> for a term, and add an empty drop zone ul for
     * leaf terms so that any other term can be dragged into them as a child.
     *
     * @param string $output   Walker output string, passed by reference.
     * @param object $object   Current term object.
     * @param int    $depth    Depth of the term in the tree.
     * @param array  $args     Walker arguments, including 'term_ids_with_children'.
     */
    public function end_el( &$output, $object, $depth = 0, $args = array() ) {
        // Add an empty sortable ul so cross-level drops can target leaf terms.
        $term_ids_with_children = isset( $args['term_ids_with_children'] ) ? $args['term_ids_with_children'] : array();

        if ( ! in_array( $object->term_id, $term_ids_with_children ) ) {
            $indent = str_repeat( "\t", $depth + 1 );
            $output .= "$indent<ul class='children sortable empty-placeholder'></ul>\n";
        }

        $output .= "</li>\n";
    }

}