<?php
global $gdb;

$menus = is_array($this->menus ?? null) ? $this->menus : [];
$cookiePages = is_array($this->cookie_pages ?? null) ? $this->cookie_pages : [];
$cookieMenus = is_array($this->cookie_menus ?? null) ? $this->cookie_menus : [];

ob_start();
foreach ($menus as $menu):
    $menuId = (int)($menu['id'] ?? 0);
    $menuName = (string)($menu['name'] ?? '');
    $menuStatus = (int)($menu['status'] ?? 0);
?>
  <div class="menu_sortable">
    <ol class="sortable" id="sortable_<?= $menuId; ?>" menu-id="<?= $menuId; ?>">
      <li id="list_<?= $menuId; ?>" class="menu_<?= $menuId; ?>" menu="<?= $menuId; ?>">
        <div class="context_0 content content_menu">
          <button type="button" class="disclose layout-tree-toggle" aria-expanded="false" title="Rozwin / zwin">
            <i class="fa fa-caret-right"></i>
          </button>
          <?php if ($menuStatus !== 1): ?><i class="fa fa-ban fa-lg text-danger" title="Menu nieaktywne"></i><?php endif; ?>
          <b>Menu: <?= htmlspecialchars($menuName, ENT_QUOTES, 'UTF-8'); ?></b>
          <div class="btn-group ml20 pull-right">
            <a href="/admin/pages/menuEdit/id=<?= $menuId; ?>" 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&#324; menu" class="btn btn-sm btn-danger menu-delete" menu-id="<?= $menuId; ?>">
              <i class="fa fa-trash"></i> <span class="hidden-xs">Usu&#324; menu</span>
            </a>
            <a href="/admin/pages/edit/pid=0&menu_id=<?= $menuId; ?>" title="Dodaj stron&#281;" class="btn btn-sm btn-success">
              <i class="fa fa-plus-circle"></i> <span class="hidden-xs">Dodaj stron&#281;</span>
            </a>
          </div>
        </div>
        <?= \Shared\Tpl\Tpl::view('pages/subpages-list', [
          'pages' => $menu['pages'] ?? [],
          'step' => 1,
        ]); ?>
      </li>
    </ol>
  </div>
<?php
endforeach;
$out = ob_get_clean();

$gridId = 'pages-list';
$gridTitle = 'Lista stron';
$gridSaveUrl = '';
$gridBackUrl = '';
$gridHidden = [];
$gridContent = $out;
$gridPersist = false;
include __DIR__ . '/../components/grid-edit-replacement.php';
?>
<script type="text/javascript" src="/libraries/jquery-nested-sortable/jquery.mjs.nestedSortable.js"></script>
<style type="text/css">
  .layout-tree-toggle {
    width: 18px;
    height: 18px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    border: 0;
    background: transparent;
    padding: 0;
    margin-right: 4px;
    color: #666;
    cursor: pointer;
  }

  .layout-tree-toggle:focus,
  .layout-tree-toggle:active,
  .layout-tree-toggle:focus-visible {
    outline: none;
    box-shadow: none;
  }

  li.sort-expanded > div .layout-tree-toggle i {
    transform: rotate(90deg);
  }

  .jconfirm.table-list-confirm-dialog .jconfirm-row {
    min-height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .jconfirm.table-list-confirm-dialog .jconfirm-box-container {
    width: 100%;
    max-width: 560px;
    padding-left: 12px;
    padding-right: 12px;
    margin: 0 auto;
  }

  .jconfirm.table-list-confirm-dialog .jconfirm-box {
    width: 100% !important;
  }
</style>
<script type="text/javascript">
  var menu_id = 0;
  var cookiePages = <?= json_encode($cookiePages, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>;
  var cookieMenus = <?= json_encode($cookieMenus, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>;

  $(document).ready(function() {
    function refreshTreeDisclosureState() {
      $('ol.sortable li').each(function() {
        var $li = $(this);
        var hasChildren = $li.children('ol').children('li').length > 0;
        var $disclose = $li.children('div').children('.disclose');

        if (hasChildren) {
          $li.removeClass('sort-leaf');
          if (!$li.hasClass('sort-collapsed') && !$li.hasClass('sort-expanded')) {
            $li.addClass('sort-collapsed');
          }
          $li.addClass('sort-branch');
          $disclose.attr('aria-expanded', $li.hasClass('sort-expanded') ? 'true' : 'false');
          $disclose.show();
        } else {
          $li.removeClass('sort-branch sort-collapsed sort-expanded').addClass('sort-leaf');
          $disclose.attr('aria-expanded', 'false');
          $disclose.hide();
        }
      });
    }

    function confirmDialog(message, onConfirm) {
      if (typeof $.confirm === 'function') {
        $.confirm({
          title: 'Potwierdzenie',
          content: String(message),
          type: 'red',
          boxWidth: '560px',
          useBootstrap: false,
          animation: 'scale',
          closeAnimation: 'scale',
          backgroundDismissAnimation: 'shake',
          container: 'body',
          theme: 'modern',
          columnClass: '',
          typeAnimated: true,
          lazyOpen: false,
          draggable: false,
          closeIcon: true,
          containerFluid: true,
          escapeKey: true,
          backgroundDismiss: true,
          animationBounce: 1.1,
          watchInterval: 100,
          offsetTop: 0,
          offsetBottom: 0,
          customClass: 'table-list-confirm-dialog',
          buttons: {
            cancel: {
              text: 'Anuluj',
              btnClass: 'btn-default'
            },
            confirm: {
              text: 'Usuń',
              btnClass: 'btn-danger',
              action: function() {
                if (typeof onConfirm === 'function') {
                  onConfirm();
                }
              }
            }
          }
        });
        return;
      }

      if (window.confirm(message) && typeof onConfirm === 'function') {
        onConfirm();
      }
    }

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

      confirmDialog('Na pewno chcesz usunąć wybrane menu?', function() {
        document.location.href = '/admin/pages/menuDelete/id=' + selectedMenuId;
      });
    });

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

      confirmDialog('Na pewno chcesz usunąć wybraną stronę?', function() {
        document.location.href = '/admin/pages/delete/id=' + pageId;
      });
    });

    $('ol.sortable').nestedSortable({
      forcePlaceholderSize: true,
      handle: 'div',
      helper: 'clone',
      items: 'li',
      opacity: 0.9,
      placeholder: 'placeholder',
      revert: 250,
      tabSize: 45,
      tolerance: 'pointer',
      toleranceElement: '> div',
      maxLevels: 4,
      isTree: true,
      expandOnHover: 700,
      stop: function() {
        refreshTreeDisclosureState();
        save_pages_order();
      }
    });

    refreshTreeDisclosureState();

    $('.disclose').on('click', function() {
      var $li = $(this).closest('li');
      if (!$li.hasClass('sort-branch')) {
        return;
      }

      $li.toggleClass('sort-collapsed').toggleClass('sort-expanded');
      $(this).attr('aria-expanded', $li.hasClass('sort-expanded') ? 'true' : 'false');
      this.blur();
    });

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

    $('.disclose').mousedown(function(e) {
      if (e.which !== 1) {
        return;
      }

      if ($(this).parent('div').hasClass('content_menu')) {
        var selectedMenuId = $(this).parent('div').parent('li').attr('menu');
        $.ajax({
          type: 'POST',
          cache: false,
          url: '/admin/pages/cookieMenus/',
          data: { menu_id: selectedMenuId }
        });
      } else {
        var pageId = $(this).parent('div').parent('li').attr('id').replace('list_', '');
        $.ajax({
          type: 'POST',
          cache: false,
          url: '/admin/pages/cookiePages/',
          data: { page_id: pageId }
        });
      }
    });

    Object.keys(cookiePages || {}).forEach(function(key) {
      if (String(cookiePages[key]) === '1') {
        $('.list_' + key).children('div').children('.disclose').click();
      }
    });

    Object.keys(cookieMenus || {}).forEach(function(key) {
      if (String(cookieMenus[key]) === '1') {
        $('.menu_' + key).children('div').children('.disclose').click();
      }
    });
  });

  function save_pages_order() {
    if (!menu_id) {
      return;
    }

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

    $.ajax({
      type: 'POST',
      cache: false,
      url: '/admin/pages/savePagesOrder/',
      data: {
        menu_id: menu_id,
        pages: pages
      },
      beforeSend: function() {
        $.prompt('Trwa zapisywanie...', { title: 'Prosz\\u0119 czeka\\u0107' });
      },
      success: function(data) {
        $('.jqibox').remove();

        var response = jQuery.parseJSON(data);
        if (response.status === 'error') {
          create_error(response.msg);
        }
      }
    });
  }
</script>


