<?php
global $gdb;

$pageId = (int)($this->page_id ?? 0);
$articles = is_array($this->articles ?? null) ? $this->articles : [];

ob_start();
?>
<ol class="sortable" id="article-list">
  <?php foreach ($articles as $article): ?>
    <?php
      $articleId = (int)($article['article_id'] ?? 0);
      $title = (string)($article['title'] ?? '');
      $status = (int)($article['status'] ?? 0);
    ?>
    <li id="list_<?= $articleId; ?>">
      <div class="content <?= $status === 1 ? '' : 'text-danger'; ?>"><span class="disclose"><span></span></span> <?= htmlspecialchars($title, ENT_QUOTES, 'UTF-8'); ?></div>
    </li>
  <?php endforeach; ?>
</ol>
<?php
$out = ob_get_clean();

$gridId = 'page-articles';
$gridTitle = 'Lista artyku&#322;&#243;w';
$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>
<script type="text/javascript">
  $(document).ready(function() {
    $('ol.sortable').nestedSortable({
      forcePlaceholderSize: true,
      handle: 'div',
      helper: 'clone',
      items: 'li',
      opacity: 0.6,
      placeholder: 'placeholder',
      revert: 250,
      tabSize: 25,
      tolerance: 'pointer',
      toleranceElement: '> div',
      maxLevels: 1,
      isTree: true,
      expandOnHover: 700,
      save_articles_order: true
    });
  });

  function save_articles_order() {
    var articles = $('ol.sortable').nestedSortable('toArray', { startDepthCount: 0 });

    $.ajax({
      type: 'POST',
      cache: false,
      url: '/admin/pages/saveArticlesOrder/',
      data: {
        page_id: <?= $pageId; ?>,
        articles: articles
      },
      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>


