<?
global $gdb;

ob_start();
  if ( is_array( $this -> menus ) ) foreach ( $this -> menus as $menu )
  {
    ?>
      <div class="menu_sortable">
        <ol class="sortable" id="sortable_<?= $menu['id'];?>" menu-id="<?= $menu['id'];?>">
          <li id="list_<?= $menu['id'];?>" class="menu_<?= $menu['id'];?>" menu="<?= $menu['id'];?>">
            <div class="context_0 content content_menu">
              <span class="disclose"><span></span></span>
              <? if ( !$menu['status'] ) echo '<i class="fa fa-ban fa-lg text-danger" title="Menu nieaktywne"></i>';?>
               <b>Menu: <?= $menu['name'];?></b>
              <div class="btn-group ml20 pull-right">
                <a href="/admin/pages/menu_edit/id=<?= $menu['id'];?>" title="Edytuj menu" class="btn btn-sm btn-system">
                  <i class="fa fa-file-text"></i> <span class="hidden-xs">Edytuj menu</span>
                </a>
                <a href="#" title="Usuń menu" class="btn btn-sm btn-danger menu-delete" menu-id="<?= $menu['id'];?>">
                  <i class="fa fa-trash"></i> <span class="hidden-xs">Usuń menu</span>
                </a>
                <a href="/admin/pages/page_edit/pid=0&menu_id=<?= $menu['id'];?>" title="Dodaj stronę" class="btn btn-sm btn-success">
                  <i class="fa fa-plus-circle"></i> <span class="hidden-xs">Dodaj stronę</span>
                </a>
              </div>
            </div>
            <?= \Tpl::view( 'pages/subpages-list', [
                'pages' => \admin\factory\Pages::menu_pages( $menu['id'] ),
                'menu_id' => $menu['id']
              ] );
            ?>
          </li>
        </ol>
      </div>
    <?
  }

$out = ob_get_clean();

$grid = new \gridEdit;
$grid -> id               = 'pages-list';
$grid -> gdb_opt          = $gdb;
$grid -> include_plugins  = true;
$grid -> title            = 'Lista stron';
$grid -> default_buttons  = false;
$grid -> buttons          = [
                              [
                                'label' => 'Dodaj menu',
                                'url'   => '/admin/pages/menu_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">
  var menu_id   = 0;

  $( document ).ready( function()
  {
    $( 'body' ).on( 'click', '.menu-delete', function()
    {
      var menu_id = $( this ).attr( 'menu-id' );

      $.prompt( "Na pewno chcesz usunąć wybrane menu?",
      {
        title: "Potwierdź?",
        buttons: { "Tak": true, "Nie": false },
        submit: function( e, v, m, f )
        {
          if ( v === true )
            document.location.href = '/admin/pages/menu_delete/id=' + menu_id;
        }
      });
    });

    $( 'body' ).on( 'click', '.page-delete', function()
    {
      var page_id = $( this ).attr( 'page-id' );

      $.prompt( "Na pewno chcesz usunąć wybraną stronę?",
      {
        title: "Potwierdź?",
        buttons: { "Tak": true, "Nie": false },
        submit: function( e, v, m, f )
        {
          if ( v === true )
            document.location.href = '/admin/pages/page_delete/id=' + page_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,
      stop: function() {
        save_pages_order();
      }
		});

		$( '.disclose' ).on( 'click', function()
    {
			$( this ).closest( 'li' ).toggleClass( 'sort-collapsed' ).toggleClass( 'sort-expanded' );
		});

    $( ".sortable *" ).mousedown( function(e)
    {
      menu_id = $( this ).parents( 'ol.sortable' ).attr( 'menu-id' );
    });

    $( '.disclose' ).mousedown( function(e)
    {
      if ( e.which === 1 ) {
        if ( $( this ).parent( 'div' ).hasClass( 'content_menu' ) )
        {
          var menu_id = $( this ).parent( 'div' ).parent( 'li' ).attr( 'menu' );

          $.ajax(
          {
            type: 'POST',
            cache: false,
            url: '/admin/ajax.php',
            data: {
              a: 'cookie_menus',
              menu_id:  menu_id
            }
          });
        }
        else
        {
          var page_id = $( this ).parent( 'div' ).parent( 'li' ).attr( 'id' );

          $.ajax(
          {
            type: 'POST',
            cache: false,
            url: '/admin/ajax.php',
            data: {
              a: 'cookie_pages',
              page_id:  page_id
            }
          });
        }
      }
    });

    <?php
      $array = unserialize( $_COOKIE[ 'cookie_pages' ] );
      if ( is_array( $array ) ): foreach ( $array as $key => $val ):
        if ( $val ):
          ?>$( '.<?= $key;?>' ).children( 'div' ).children( 'span.disclose' ).click();<?
        endif;
      endforeach; endif;

      $array = unserialize( $_COOKIE[ 'cookie_menus' ] );
      if ( is_array( $array ) ): foreach ( $array as $key => $val ):
        if ( $val ):
          ?>$( '.menu_<?= $key;?>' ).children( 'div' ).children( 'span.disclose' ).click();<?
        endif;
      endforeach; endif;
    ?>
  });

  function save_pages_order( )
  {
    pages = $( '#sortable_' + menu_id ).nestedSortable( 'toArray', { startDepthCount: 0 } );

    $.ajax(
    {
      type: 'POST',
      cache: false,
      url: '/admin/ajax.php',
      data:
      {
        a: 'save_pages_order',
        menu_id: menu_id,
        pages: pages
      },
      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>