<?php
/*
=============================================================================
   
============================================================================*/ 

function ppt_orderby_system(){
     
    include (ppt_orderby_PATH . '/main-interface.php');      
           
    $options = ppt_order_settings();
    
    $capability = 'manage_options'; 
    
    //put a menu within all custom types if apply
    $post_types = get_post_types();
    foreach( $post_types as $post_type){               
                  
            if (count(get_object_taxonomies($post_type)) == 0){
                continue;                
            }

            $menu_title = apply_filters('atto/admin/menu_title', 'Taxonomy Order', $post_type);
            
            if ($post_type == 'post'){

                $hookID =   add_submenu_page('edit.php', $menu_title, $menu_title, $capability, 'ppt_orderby-'.$post_type, 'ppt_orderby_interface' );
            
            }elseif ($post_type == 'attachment'){
                
                $hookID =   add_submenu_page('upload.php', $menu_title, $menu_title, $capability, 'ppt_orderby-'.$post_type, 'ppt_orderby_interface' );
           
            }else{ 
                $hookID =   add_submenu_page('edit.php?post_type='.$post_type, $menu_title, $menu_title, $capability, 'ppt_orderby-'.$post_type, 'ppt_orderby_interface' );
            }
                
            add_action('admin_print_styles-' . $hookID , 'ppt_orderby_admin_styles');
            add_action('admin_print_scripts-' . $hookID , 'ppt_orderby_admin_scripts');
        }
}
/*
=============================================================================
   
============================================================================*/ 
function ppt_order_settings(){
                    
    $settings = get_option('tto_options'); 
                    
    $defaults   = array (
        'capability'                =>  'manage_options',
        'autosort'                  =>  '0',
        'adminsort'                 =>  '0'
    );
    $settings          = wp_parse_args( $settings, $defaults );
                    
    return $settings;   
                    
 }
/*
=============================================================================
   
============================================================================*/ 

function ppt_orderby_admin_scripts() {
            
    wp_enqueue_script('jquery');			
    wp_enqueue_script('jquery-ui-sortable'); 
    $myJsFile = ppt_orderby_URL . '/scripts.js';
    wp_register_script('orderby_scripts.js', $myJsFile);
    wp_enqueue_script( 'orderby_scripts.js');  


}
/*
=============================================================================
   
============================================================================*/ 

function ppt_orderby_admin_styles(){
    $myCssFile = ppt_orderby_URL . '/styles.css';
    wp_register_style('orderby_styles.css', $myCssFile);
    wp_enqueue_style( 'orderby_styles.css');
}

/*
=============================================================================
   
============================================================================*/ 

function ppt_orderby_activated($network_wide){

            global $wpdb;
                 
            ppt_check_table_column();
}
/*
=============================================================================
   
============================================================================*/ 

function ppt_check_table_column(){ 
    
    global $wpdb;
                    
        //check if the menu_order column exists;
        $query = "SHOW COLUMNS FROM $wpdb->terms LIKE 'term_order'";
        $result = $wpdb->query($query);
        
        if ($result == 0){
                $query = "ALTER TABLE $wpdb->terms ADD `term_order` INT( 4 ) NULL DEFAULT '0'";
                $result = $wpdb->query($query); 
        }
}
 /*
=============================================================================
   
============================================================================*/ 
  
add_filter('get_terms_orderby', 'ppt_get_terms_orderby', 10, 2);
function ppt_get_terms_orderby($orderby, $args)
{
 
    if (isset($args['orderby']) && $args['orderby'] == "term_order" && $orderby != "term_order"){
        return "t.term_order";
    } 
    
    return $orderby;
 }
        
/*
=============================================================================
   
============================================================================*/ 
 
add_filter('terms_clauses', 'ppt_to_terms_clauses', 99, 3);
function ppt_to_terms_clauses($clauses, $taxonomies, $args){


    $options = ppt_order_settings();    
 
    // SINGLE QUERY
    if(count($taxonomies) == 1){

        $taxonomy = $taxonomies[0];
        $order_type = (isset($options['taxonomy_settings'][$taxonomy]['order_type'])) ? $options['taxonomy_settings'][$taxonomy]['order_type'] : 'auto'; 
        
       if($order_type == "manual"){

            $clauses['orderby'] =   'ORDER BY t.term_order';

       }elseif($order_type == "auto"){ 

        if(isset($options['taxonomy_settings'][$taxonomy])){

            $order_by = (isset($options['taxonomy_settings'][$taxonomy]['auto']['order_by'])) ? $options['taxonomy_settings'][$taxonomy]['auto']['order_by'] : 'name'; 
            $order = (isset($options['taxonomy_settings'][$taxonomy]['auto']['order'])) ? $options['taxonomy_settings'][$taxonomy]['auto']['order'] : 'asc'; 
            
            if($order_by != "default"){ 
            
            $clauses['orderby'] =   'ORDER BY '.$order_by;
            $clauses['order']   =   $order;
            
            }
 
        }

       } 
        
    } 

     
    if (is_admin()){
             
        //return if use orderby columns
        if (isset($_GET['orderby']) && $_GET['orderby'] !=  'term_order'){
           return $clauses;
        }   
    
    }
 
         
     return $clauses;  

}
/*
=============================================================================
   
============================================================================*/ 

add_action( 'wp_ajax_update-taxonomy-order', 'ppt_orderby_SaveAjaxOrder' );
function ppt_orderby_SaveAjaxOrder()
        {
           
            global $wpdb;
            
            if  ( ! wp_verify_nonce( $_POST['nonce'], 'update-taxonomy-order' ) )
                die();
             
            $data               = stripslashes($_POST['order']);
            $unserialised_data  = json_decode($data, TRUE);
                    
            if (is_array($unserialised_data))
            foreach($unserialised_data as $key => $values ) 
                {
                    //$key_parent = str_replace("item_", "", $key);
                    $items = explode("&", $values);
                    unset($item);
                    foreach ($items as $item_key => $item_)
                        {
                            $items[$item_key] = trim(str_replace("item[]=", "",$item_));
                        }
                    
                    if (is_array($items) && count($items) > 0)
                        {
                            foreach( $items as $item_key => $term_id ) 
                                {
                                    $wpdb->update( $wpdb->terms, array('term_order' => ($item_key + 1)), array('term_id' => $term_id) );
                                }
                            clean_term_cache($items);
                        } 
                } 
             
            wp_cache_flush();
                
            die();

        }
    
 
 /*
=============================================================================
   
============================================================================*/ 
   
class PPT_Orderby_Walker extends Walker {
    
                var $db_fields = array ('parent' => 'parent', 'id' => 'term_id');
    
    
                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";
                    }
    
    
                function end_lvl(&$output, $depth = 0, $args = array()) 
                    {
                        extract($args, EXTR_SKIP);
                            
                        $indent = str_repeat("\t", $depth);
                        $output .= "$indent</ul>\n";
                    }
    
    
                function start_el(&$output, $term, $depth = 0, $args = array(), $current_object_id = 0) 
                    {
                        if ( $depth )
                            $indent = str_repeat("\t", $depth);
                        else
                            $indent = '';
    
                        //extract($args, EXTR_SKIP);
                        $post_type = isset($_GET['post_type']) ? $_GET['post_type'] : 'post'; 
                        $taxonomy = get_taxonomy($term->term_taxonomy_id);
                        $output .= $indent . '<li class="term_type_li" id="item_'.$term->term_id.'"><div class="item"><div class="options"><span class="option edit"><a href="'. admin_url( 'edit-tags.php') .'?action=edit&taxonomy='. $term->taxonomy .'&tag_ID='.$term->term_id.'&post_type='. $post_type .'">Edit</a></span></div><span>'.apply_filters( 'term_name', $term->name, $term->term_id ).' ('.$term->term_id.')</span></div>';
                    }
    
    
                function end_el(&$output, $post_type, $depth = 0, $args = array()) 
                    {
                        $output .= "</li>\n";
                    }
    
            }
 /*
=============================================================================
   
============================================================================*/ 
   
?>