<?
global $gdb;

ob_start();
  ?>
    <div class="menu_sortable">
      <ol class="sortable" id="sortable">
        <? if ( is_array( $this -> categories ) ): foreach ( $this -> categories as $category ):?>
          <li id="list_<?= $category['id'];?>" class="category_<?= $category['id'];?>" category="<?= $category['id'];?>">
            <div class="context_0 content content_menu">
              <span class="disclose"><span></span></span>
              <? if ( !$category['status'] ) echo '<i class="fa fa-ban fa-lg text-danger" title="Kategoria nieaktywna"></i>';?> 
              <b><?= $category['languages'][$this -> dlang]['title'];?></b>
              <div class="btn-group ml20 pull-right">
                <a href="/admin/shop_category/category_edit/id=<?= $category['id'];?>" title="Edytuj kategorię" class="btn btn-sm btn-system">
                  <i class="fa fa-file-text"></i> <span class="hidden-xs">Edytuj kategorię</span>
                </a>
                <a href="#" title="Usuń kategorię" class="btn btn-sm btn-danger category-delete" category-id="<?= $category['id'];?>">
                  <i class="fa fa-trash"></i> <span class="hidden-xs">Usuń kategorię</span>
                </a>
                <a href="/admin/shop_category/category_products/id=<?= $category['id'];?>" title="Lista produktów" class="btn btn-sm btn-info" category-id="<?= $category['id'];?>">
                  <i class="fa fa-bars"></i> <span class="hidden-xs">Lista produków</span>
                </a>
                <a href="/admin/shop_category/category_edit/pid=<?= $category['id'];?>" title="Dodaj podkategorię" class="btn btn-sm btn-success">
                  <i class="fa fa-plus-circle"></i> <span class="hidden-xs">Dodaj podkategorię</span>
                </a>
              </div>
            </div>
            <?= \Tpl::view( 'shop-category/subcategories-list', [
                    'categories' => \admin\factory\ShopCategory::subcategories( $category['id'] ),
                    'level' => $this -> level + 1,
                    'dlang' => $this -> dlang
                  ] );?>
          </li>
        <? endforeach; endif;?>
      </ol>
    </div>
  <?
$out = ob_get_clean();

$grid = new \gridEdit;
$grid -> id               = 'pages-list';
$grid -> gdb_opt          = $gdb;
$grid -> include_plugins  = true;
$grid -> title            = 'Lista kategorii';
$grid -> default_buttons  = false;
$grid -> buttons          = [
                              [ 
                                'label' => 'Dodaj kategorię', 
                                'url'   => '/admin/shop_category/category_edit/',
                                'icon'  => 'fa-plus-circle',
                                'class' => 'btn-success'
                              ]
                            ];
$grid -> external_code    = $out;

echo $grid -> draw();
?>
<script type="text/javascript" src="/libraries/jquery-nested-sortable/jquery.mjs.nestedSortable.js"></script>
<script type="text/javascript">
  
  $( document ).ready( function() 
  {
    $( 'body' ).on( 'click', '.category-delete', function()
    {
      var category_id = $( this ).attr( 'category-id' );
      
      $.prompt( "Na pewno chcesz usunąć wybraną kategorię?", 
      {
        title: "Potwierdź?",
        buttons: { "Tak": true, "Nie": false },
        submit: function( e, v, m, f ) 
        {
          if ( v === true )
            document.location.href = '/admin/shop_category/category_delete/id=' + category_id;
        }
      });
    });
    
    $( 'ol.sortable' ).nestedSortable(
    {
			forcePlaceholderSize: true,
			handle: 'div',
			helper:	'clone',
			items: 'li',
			opacity: .9,
			placeholder: 'placeholder',
			revert: 250,
			tabSize: 45,
			tolerance: 'pointer',
			toleranceElement: '> div',
			maxLevels: 4,
			isTree: true,
			expandOnHover: 700,
      protectRoot: false,
      stop: function() { 
        save_categories_order(); 
      }
		});

		$( '.disclose' ).on( 'click', function() 
    {
			$( this ).closest( 'li' ).toggleClass( 'sort-collapsed' ).toggleClass( 'sort-expanded' );
		});
            
    $( '.disclose' ).mousedown( function(e) 
    {
      if ( e.which === 1 ) 
      {
        var category_id = $( this ).parent( 'div' ).parent( 'li' ).attr( 'id' );

        $.ajax(
        {
          type: 'POST',
          cache: false,
          url: '/admin/ajax.php',
          data: {
            a: 'cookie_categories',
            category_id:  category_id
          }
        });
      }
    });
    
    <?php
      $array = unserialize( $_COOKIE[ 'cookie_categories' ] );
      if ( is_array( $array ) ): foreach ( $array as $key => $val ):
        if ( $val ):
          ?>$( '#<?= $key;?>' ).children( 'div' ).children( 'span.disclose' ).click();<?
        endif;
      endforeach; endif;
    ?>
  });
  
  function save_categories_order( ) 
  {
    categories = $( '#sortable' ).nestedSortable( 'toArray', { startDepthCount: 0 } );
    
    $.ajax(
    {
      type: 'POST',
      cache: false,
      url: '/admin/ajax.php',
      data: 
      {
        a: 'save_categories_order',
        categories: categories
      },
      beforeSend: function()
      {
        $.prompt( 'Trwa zapisywanie...', { title: 'Proszę czekać' } );
      },
      success: function( data ) 
      {        
        $( '.jqibox' ).remove();
        response = jQuery.parseJSON( data );

        if ( response.status === 'error' )
          create_error( response.msg );
      }
    });
  }
</script>