<?php

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

    function ppt_orderby_interface()
        {
            global $wpdb, $wp_locale, $CORE, $CORE_ADMIN;
            
            $options = ppt_order_settings();
              
            $taxonomy = isset($_GET['taxonomy']) ? sanitize_key($_GET['taxonomy']) : '';
            $post_type = isset($_GET['post_type']) ? sanitize_key($_GET['post_type']) : '';
            
            if(empty($post_type))
                {
                    $screen = get_current_screen();
                    
                    if(isset($screen->post_type)    && !empty($screen->post_type))
                        $post_type  =   $screen->post_type;
                        else
                        {
                            switch($screen->parent_file)
                                {
                                    case "upload.php" :
                                                                $post_type  =   'attachment';
                                                                break;
                                                        
                                    case "shopp-products"   :
                                                                $post_type  =   'shopp_product';
                                                                break;
                                                
                                    default:
                                                                $post_type  =   'post';   
                                }
                        }       
                }
                    
            $post_type_taxonomies = get_object_taxonomies($post_type);
        
            //use the first taxonomy if emtpy taxonomy
            if ($taxonomy == '' || !taxonomy_exists($taxonomy)){
                    reset($post_type_taxonomies);   
                    $taxonomy = current($post_type_taxonomies);
            }
                                
            $post_type_data = get_post_type_object($post_type);
            
            if (!taxonomy_exists($taxonomy)) {   $taxonomy = ''; }
            

            //// GET ORDER AND SET AUTO AS DEFAULT
            $order_type = (isset($options['taxonomy_settings'][$taxonomy]['order_type'])) ? $options['taxonomy_settings'][$taxonomy]['order_type'] : 'auto'; 
             
            $taxonomy_info = get_taxonomy($taxonomy); 
            
            // SWITCH ORDER TYPE
            if (isset($_GET['switch_order_type']))
            {
                    $order_type =   $_GET['switch_order_type'];
                              
                    //save the new order
                    $options['taxonomy_settings'][$taxonomy]['order_type'] = $order_type;
                    update_option('tto_options', $options); 
                    
                    echo '<div class="message updated fade"><p>'. __('Order type for','premiumpress') . ' ' .$taxonomy_info->label.' '. __('Switched to', 'premiumpress'). ' ' . ucfirst($order_type)  .'</p></div>';  
            }
                        
            //check for order type update
            if (isset($_POST['order_type'])){

                    $new_order_type = $_POST['order_type'];
                    if ($new_order_type != 'auto' && $new_order_type != 'manual')
                        $new_order_type = '';
                        
                    if ($new_order_type != '')
                        {
                            
                            echo '<div class="message updated fade"><p>'. __('Order updated','premiumpress') .'</p></div>';
                            $order_type = $new_order_type;
                            
                            //save the new order
                            $options['taxonomy_settings'][$taxonomy]['order_type'] = $order_type;

                            //update the orde_by
                            if (isset($_POST['auto_order_by']))
                                {
                                    $new_order_by = $_POST['auto_order_by'];
                                    if ($new_order_by != '')
                                        $options['taxonomy_settings'][$taxonomy]['auto']['order_by'] = $new_order_by;
                                } 
                            
                            //update the orde_by
                            if (isset($_POST['auto_order']))
                                {
                                    $new_order = $_POST['auto_order'];
                                    if ($new_order_by != '')
                                        $options['taxonomy_settings'][$taxonomy]['auto']['order'] = $new_order;
                                }    
                                
                            update_option('tto_options', $options);                        
                        }
                }
            
            if(isset($taxonomy_info->hierarchical) && $taxonomy_info->hierarchical === TRUE)    
                $is_hierarchical = TRUE;
                else
                $is_hierarchical = FALSE;

            
            $current_section_parent_file    =   '';
     
            switch($post_type)
                {
                    case "post" :
                                    $current_section_parent_file    =    "edit.php";
                                    break;
                    case "attachment" :
                                    $current_section_parent_file    =   "upload.php";
                                    break;
                }
    
?>    
<div id="atto" class="wrap">
   <div id="ajax-response"></div>

   <div class="clear"></div>
 
 
   <form action="<?php  echo $current_section_parent_file ?>" method="get" id="to_form">
      <input type="hidden" name="page" value="ppt_orderby-<?php echo $post_type ?>" />
      <input type="hidden" name="taxonomy" value="" id="chageTaxValue" />
      <?php
         if (!in_array($post_type, array('post', 'attachment')))
            echo '<input type="hidden" name="post_type" value="'. $post_type .'" />';
         
         
                                
         if (count($post_type_taxonomies) > -1) {
         
         global $CORE_ADMIN;
         echo $CORE_ADMIN->HEAD();
                ?>
   </form>
   <div class="main-body-column ">
      <div class="tab-content ppt-wrap">
         <h1>Taxonomy Order</h1>
         <div class="padding">
            <p><strong>Select Taxonomy</strong></p>
            <nav class="nav nav-inline postbox" style="margin-top: 20px; padding: 20px;">
               <?php
                  $alternate = FALSE;
                  foreach ($post_type_taxonomies as $key => $post_type_taxonomy) {
                      
                                                              $taxonomy_info = get_taxonomy($post_type_taxonomy);
                  
                                                              $alternate = $alternate === TRUE ? FALSE :TRUE;
                                                              
                                                              
                                                              $args = array(
                                                                              'hide_empty'    =>  0
                                                                              );
                                                              $taxonomy_terms = get_terms($post_type_taxonomy, $args);
                                                                               
                                                              ?>
               <a class="nav-link" href="javascript:void(0);" onclick="updatetax('<?php echo $post_type_taxonomy ?>')" style="text-decoration: none; color:black;">
                  <b> <?php if ($post_type_taxonomy == $taxonomy) {  ?><u> <?php } ?> <?php echo $CORE->GEO("translation_tax_key", $post_type_taxonomy);  ?></b> <?php if ($post_type_taxonomy == $taxonomy) {  ?></u> <?php } ?>  <!--(<?php echo  $taxonomy_info->labels->singular_name; ?>) -->
                  (<?php echo count($taxonomy_terms) ?>)
               </a>
               <span style="margin:0px 10px;"> &#8226; </span> 
               <?php
                  }
                  
                  ?>
            </nav>
            <?php
               }
                   ?>
            </form>
            <script >    
               var taxonomy    = '<?php echo $taxonomy ?>';
               function updatetax(element) {
                
               	jQuery('#chageTaxValue').val(element);
                   jQuery('#to_form').submit();
               }
               
                
            </script>
            <?php
               $url_query_vars =   array(
                                           "page"          =>  "ppt_orderby-" .   $post_type,
                                           "taxonomy"      =>  $taxonomy 
                                           );
               
               if (!in_array($post_type, array('post', 'attachment')))   
                   $url_query_vars['post_type']    =   $post_type;
               
               ?>
            <form action="<?php  echo $current_section_parent_file ?>?<?php echo http_build_query($url_query_vars) ?>" method="post" id="to_form">
               <input type="hidden" name="order_type" value="<?php echo $order_type ?>" />
               <?php
                  if (!in_array($post_type, array('post', 'attachment')))
                      echo '<input type="hidden" name="post_type" value="'. $post_type .'" />';
                  
                  $url_query_vars =   array(
                                              "page"          =>  "ppt_orderby-" .   $post_type,
                                              "taxonomy"      =>  $taxonomy 
                                              );
                  
                  if (!in_array($post_type, array('post', 'attachment')))   
                      $url_query_vars['post_type']    =   $post_type;
                   
                  ?>


               <h2 class="nav-tab-wrapper" id="apto-nav-tab-wrapper">
                  <a href="<?php  echo $current_section_parent_file ?>?<?php echo http_build_query(array_merge($url_query_vars, array("switch_order_type" => "auto"))) ?>" class="nav-tab<?php if ($order_type == 'auto') {echo ' nav-tab-active';} ?>"><?php _e('Automatic Order', 'premiumpress') ?></a>
                  <a href="<?php  echo $current_section_parent_file ?>?<?php echo http_build_query(array_merge($url_query_vars, array("switch_order_type" => "manual"))) ?>" class="nav-tab<?php if ($order_type == 'manual') {echo ' nav-tab-active';} ?>"><?php _e('Manual Order', 'premiumpress') ?></a>
               </h2>



<?php if ($order_type == 'auto')  {  ?>


               <div class="atto_metabox">
                  <h4 class="ntitle"><?php _e('Order By', 'premiumpress') ?></h4>
                  <?php
                     $auto_order_by = isset($options['taxonomy_settings'][$taxonomy]['auto']['order_by']) ? $options['taxonomy_settings'][$taxonomy]['auto']['order_by'] : 'name';
                     
                     ?>
                  <div class="row">
                      
                     <label class="control-label ">   

                        <input type="radio" <?php if ($auto_order_by == 'default') {echo 'checked="checked"'; } ?> value="default" id="order_by_default" name="auto_order_by" />
                      <?php _e('Default', 'premiumpress') ?>
                    
                    </label>                                                
                  </div>
                  <div class="clearfix"></div>
                  <div class="row">
                    
                     <label class="control-label">
                        
                     <input type="radio" <?php if ($auto_order_by == 'id') {echo 'checked="checked"'; } ?> value="id" id="order_by_id" name="auto_order_by" />
                     
                     <?php _e('Creation Time / ID', 'premiumpress') ?></label> 
                  </div>
                  <div class="clearfix"></div>
                  <div class="row">
                    
                     <label class="control-label">
                        
                     <input type="radio" <?php if ($auto_order_by == 'name') {echo 'checked="checked"'; } ?> value="name" id="order_by_name" name="auto_order_by" />
                     
                     <?php _e('Name', 'premiumpress') ?></label>
                  </div>
                  <div class="clearfix"></div>
                                                            
         <div class="row">                                               
          
         <label class="control-label">
            
         <input type="radio" <?php if ($auto_order_by == 'slug') {echo 'checked="checked"'; } ?> value="slug" id="order_by_slug" name="auto_order_by" />
        
         
         <?php _e('Slug', 'premiumpress') ?></label>
         </div>
         <div class="clearfix"></div>                                                
   
   <h4 class="ntitle"><?php _e('Order', 'premiumpress') ?></h4>
   <?php
      $auto_order = isset($options['taxonomy_settings'][$taxonomy]['auto']['order']) ? $options['taxonomy_settings'][$taxonomy]['auto']['order'] : 'desc';
      
      ?>


   <div class="row">                                               
   
   <label for="order_desc">
   <input type="radio" <?php if ($auto_order == 'desc') {echo 'checked="checked"'; } ?> value="desc" id="order_desc" name="auto_order" />
   
   
   <?php _e('Descending', 'premiumpress') ?></label>
   </div>

   <div class="row"> 
   <label for="order_asc">
   <input type="radio" <?php if ($auto_order == 'asc') {echo 'checked="checked"'; } ?> value="asc" id="order_asc" name="auto_order" />
   
   <?php _e('Ascending', 'premiumpress') ?></label><br>
   </div>

   <input type="submit" value="<?php _e('Update', 'premiumpress') ?>" class="button-primary" name="update" style="margin-top:20px;">
</div>


<?php } ?>

<?php if ($order_type == 'manual')  {  ?>

<div id="order-terms">
<div id="nav-menu-header">
<div class="major-publishing-actions">
<div class="alignright actions">
<p class="actions">
 
<a href="javascript:;" class="save-order button-primary"><?php _e('Update', 'premiumpress') ?></a>
</p>
</div>
<div class="clear"></div>
</div> 
</div> 
<div id="post-body">                    
<ul id="sortable" class="sortable">
<?php 
   WLTlistTerms($taxonomy); 
   ?>
</ul>
<div class="clear"></div>
</div>
<div id="nav-menu-footer">
<div class="major-publishing-actions">
<div class="alignright actions"> 
<a href="javascript:;" class="save-order button-primary"><?php _e('Update', 'premiumpress') ?></a>
</div>
<div class="clear"></div>
</div> 
</div> 
</div>
<?php
   }
   ?> 
</form>
<script>
   jQuery(document).ready(function() {   
   
       jQuery("ul.sortable").sortable({
                       'tolerance':'intersect',
                       'cursor':'pointer',
                       'items':'> li',
                       'axi': 'y',
                       'placeholder':'placeholder',
                       'nested': 'ul'
                   }); 
   
         
                   jQuery(".save-order").bind( "click", function() {
                       var mySortable = new Array();
                      
                       jQuery(".sortable").each(  function(){
                           
                           var serialized = jQuery(this).sortable("serialize");
                           
                           var parent_tag = jQuery(this).parent().get(0).tagName;
                           parent_tag = parent_tag.toLowerCase()
                           if (parent_tag == 'li')
                               {
                                   // 
                                   var tag_id = jQuery(this).parent().attr('id');
                                   mySortable[tag_id] = serialized;
                               }
                               else
                               {
                                   //
                                   mySortable[0] = serialized;
                               }
                       });
                       
                       //serialize the array
                       var serialize_data = JSON.stringify( convArrToObj(mySortable));
                                                                                   
                       jQuery.post( ajaxurl, { action:'update-taxonomy-order', order: serialize_data, nonce : '<?php echo wp_create_nonce( 'update-taxonomy-order' ); ?>' }, function() {
                           jQuery("#ajax-response").html('<div class="message updated fade"><p><?php esc_html_e ( "Items Order Updated", 'taxonomy-terms-order' ) ?></p></div>');
                           jQuery("#ajax-response div").delay(3000).hide("slow");
                       });
                   });
   });
</script>
</div> </div></div>

<?php 
             echo $CORE_ADMIN->FOOTER();
            
        }
/*
=============================================================================
   
============================================================================*/ 
    function WLTlistTerms($taxonomy) 
            {

                // Query pages.
                $args = array(
                            'orderby'       =>  'term_order',
                            'depth'         =>  0,
                            'child_of'      => 0,
                            'hide_empty'    =>  0
                );
                $taxonomy_terms = get_terms($taxonomy, $args);

                $output = '';
                if (count($taxonomy_terms) > 0)
                    {
                        $output = WLTTOwalkTree($taxonomy_terms, $args['depth'], $args);    
                    }

                echo $output; 
                
            }
/*
=============================================================================
   
============================================================================*/ 
        function WLTTOwalkTree($taxonomy_terms, $depth, $r) 
            {
                $walker = new PPT_Orderby_Walker; 
                $args = array($taxonomy_terms, $depth, $r);
                return call_user_func_array(array(&$walker, 'walk'), $args);
            }

?>