<?php
$article = is_array($this->article ?? null) ? $this->article : [];
$articleId = (int)($article['id'] ?? 0);
$userId = (int)($this->user['id'] ?? 0);
$imagesCount = is_array($article['images'] ?? null) ? count($article['images']) : 0;
$filesCount = is_array($article['files'] ?? null) ? count($article['files']) : 0;

$imageMaxPx = 1920;
if (isset($this->settings['image_px']) && (int)$this->settings['image_px'] > 0) {
    $imageMaxPx = (int)$this->settings['image_px'];
} elseif (isset($GLOBALS['settings']['image_px']) && (int)$GLOBALS['settings']['image_px'] > 0) {
    $imageMaxPx = (int)$GLOBALS['settings']['image_px'];
}

$uploadToken = bin2hex(random_bytes(24));
if (!isset($_SESSION['upload_tokens']) || !is_array($_SESSION['upload_tokens'])) {
    $_SESSION['upload_tokens'] = [];
}
$_SESSION['upload_tokens'][$uploadToken] = [
    'user_id' => $userId,
    'expires' => time() + 60 * 20,
];

$cookiePages = [];
$cookieMenus = [];
if (!empty($_COOKIE['cookie_pages'])) {
    $decoded = @unserialize($_COOKIE['cookie_pages']);
    if (is_array($decoded)) {
        $cookiePages = $decoded;
    }
}
if (!empty($_COOKIE['cookie_menus'])) {
    $decoded = @unserialize($_COOKIE['cookie_menus']);
    if (is_array($decoded)) {
        $cookieMenus = $decoded;
    }
}
?>

<link type="text/css" rel="stylesheet" href="/libraries/plupload/jquery.plupload.queue/css/jquery.plupload.queue.css" />
<link type="text/css" rel="stylesheet" href="/libraries/grid/plugins/impromptu/jquery-impromptu.css" />

<script type="text/javascript" src="/libraries/grid/plugins/impromptu/jquery-impromptu.js"></script>
<script type="text/javascript" src="/libraries/jquery/sortable/sortable.js"></script>
<script type="text/javascript" src="/libraries/plupload/plupload.js"></script>
<script type="text/javascript" src="/libraries/plupload/plupload.flash.js"></script>
<script type="text/javascript" src="/libraries/plupload/plupload.html5.js"></script>
<script type="text/javascript" src="/libraries/plupload/plupload.html4.js"></script>
<script type="text/javascript" src="/libraries/plupload/jquery.plupload.queue/jquery.plupload.queue.js"></script>
<script type="text/javascript" src="/libraries/plupload/i18n/pl.js"></script>
<script type="text/javascript" src="/libraries/jquery-nested-sortable/jquery.mjs.nestedSortable.js"></script>
<script type="text/javascript" src="/libraries/jquery/lozad.js"></script>

<style type="text/css">
  #fg-article-edit .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;
    text-indent: 0;
    background-image: none !important;
  }

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

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

  #fg-article-edit .sortable li.sort-branch > div > .layout-tree-toggle {
    display: inline-flex;
    float: none;
    margin-right: 4px;
  }

  #fg-article-edit .menu_sortable .icheckbox_minimal-blue {
    margin-top: 0;
    margin-right: 5px;
  }

  #fg-article-edit .menu_sortable .g-checkbox {
    position: relative;
    overflow: hidden;
  }

  .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 images_count = <?= (int)$imagesCount ?>;
  var files_count = <?= (int)$filesCount ?>;
  var article_id = <?= (int)$articleId ?>;

  $(function() {
    function confirmDialog(message, onConfirm, okLabel) {
      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: okLabel || 'Usun',
              btnClass: 'btn-danger',
              action: function() {
                if (typeof onConfirm === 'function') {
                  onConfirm();
                }
              }
            }
          }
        });
        return;
      }

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

    function ensureGalleryOrderInput() {
      var $form = $('#fg-article-edit');
      if (!$form.length) {
        return null;
      }

      var $input = $form.find('input[name="gallery_order"]');
      if (!$input.length) {
        $input = $('<input>', {
          type: 'hidden',
          name: 'gallery_order',
          id: 'gallery_order'
        });
        $form.append($input);
      }

      return $input;
    }

    function ensureFilesOrderInput() {
      var $form = $('#fg-article-edit');
      if (!$form.length) {
        return null;
      }

      var $input = $form.find('input[name="files_order"]');
      if (!$input.length) {
        $input = $('<input>', {
          type: 'hidden',
          name: 'files_order',
          id: 'files_order'
        });
        $form.append($input);
      }

      return $input;
    }

    function buildGalleryOrder() {
      var order = [];
      $('#images-list li').each(function() {
        var imageId = $(this).find('a.article_image_delete').attr('image-id');
        if (imageId) {
          order.push(imageId);
        }
      });
      return order.join(';');
    }

    function refreshGalleryOrderInput() {
      var $input = ensureGalleryOrderInput();
      if ($input) {
        $input.val(buildGalleryOrder());
      }
    }

    function buildFilesOrder() {
      var order = [];
      $('#files-list li').each(function() {
        var fileId = $(this).find('.article_file_edit').attr('file_id');
        if (fileId) {
          order.push(fileId);
        }
      });
      return order.join(';');
    }

    function refreshFilesOrderInput() {
      var $input = ensureFilesOrderInput();
      if ($input) {
        $input.val(buildFilesOrder());
      }
    }

    ensureGalleryOrderInput();
    refreshGalleryOrderInput();
    ensureFilesOrderInput();
    refreshFilesOrderInput();

    var observer = lozad();
    observer.observe();

    var imageList = document.getElementById('images-list');
    if (imageList) {
      Sortable.create(imageList, {
        onEnd: function() {
          var order = '';
          $('#images-list li').each(function() {
            if (order !== '') {
              order += ';';
            }
            order += $(this).children('a').attr('image-id');
          });

          $.ajax({
            type: 'POST',
            cache: false,
            url: '/admin/articles/galleryOrderSave/',
            data: {
              article_id: article_id,
              order: order
            },
            beforeSend: function() {
              $('#overlay').show();
            },
            success: function(data) {
              $('#overlay').hide();
              var response = jQuery.parseJSON(data);
              if (response.status !== 'ok') {
                create_error(response.msg);
              }
            }
          });

          refreshGalleryOrderInput();
        }
      });
    }

    var filesList = document.getElementById('files-list');
    if (filesList) {
      Sortable.create(filesList, {
        onEnd: function() {
          var order = buildFilesOrder();

          $.ajax({
            type: 'POST',
            cache: false,
            url: '/admin/articles/filesOrderSave/',
            data: {
              article_id: article_id,
              order: order
            },
            beforeSend: function() {
              $('#overlay').show();
            },
            success: function(data) {
              $('#overlay').hide();
              var response = jQuery.parseJSON(data);
              if (response.status !== 'ok') {
                create_error(response.msg);
              }
            }
          });

          refreshFilesOrderInput();
        }
      });
    }

    $('#images-uploader').pluploadQueue({
      multipart_params: {
        upload_token: '<?= htmlspecialchars($uploadToken, ENT_QUOTES, 'UTF-8') ?>',
        article_id: article_id
      },
      runtimes: 'html5,flash,html4',
      init: {
        Refresh: function() {
          $('.plupload_buttons').css('display', 'inline');
          $('.plupload_upload_status').css('display', 'inline');
          $('.plupload_start').addClass('plupload_disabled');
          $('.plupload_start').removeClass('plupload_disabled');
        },
        UploadComplete: function() {
          $('.plupload_buttons').css('display', 'inline');
          $('.plupload_upload_status').css('display', 'inline');
          $('.plupload_start').addClass('plupload_disabled');
          $('.plupload_start').removeClass('plupload_disabled');
        },
        FileUploaded: function(up, file, response) {
          var data = jQuery.parseJSON(response.response);

          $('#images-list').append(
            '<li id="image-' + data.image_id + '">' +
              '<img class="article-image lozad" data-src="/libraries/thumb.php?img=' + data.data_link + '&w=300&h=300">' +
              '<a href="#" class="input-group-addon btn btn-danger article_image_delete" image-id="' + data.image_id + '">' +
                '<i class="fa fa-trash"></i>' +
              '</a>' +
              '<input type="text" class="form-control image-alt" value="" image-id="' + data.image_id + '" placeholder="atrybut alt...">' +
            '</li>'
          );
          images_count++;
          observer.observe();
          refreshGalleryOrderInput();

          $('html, body').animate({
            scrollTop: $('#images-uploader').offset().top
          }, 1);
        }
      },
      url: '/libraries/plupload/upload-articles-images.php',
      chunk_size: '1mb',
      max_file_size: '20mb',
      unique_names: false,
      resize: {
        width: <?= (int)$imageMaxPx ?>,
        height: <?= (int)$imageMaxPx ?>,
        quality: 95
      },
      filters: [
        { title: 'Obrazki', extensions: 'jpg,gif,png,bmp,jpeg' }
      ],
      flash_swf_url: '/../libraries/plupload/plupload.flash.swf'
    });

    $('#files-uploader').pluploadQueue({
      multipart_params: {
        upload_token: '<?= htmlspecialchars($uploadToken, ENT_QUOTES, 'UTF-8') ?>'
      },
      runtimes: 'html5,flash,html4',
      init: {
        Refresh: function() {
          $('.plupload_buttons').css('display', 'inline');
          $('.plupload_upload_status').css('display', 'inline');
          $('.plupload_start').addClass('plupload_disabled');
          $('.plupload_start').removeClass('plupload_disabled');
        },
        FileUploaded: function(up, file, response) {
          var data = jQuery.parseJSON(response.response);
          $('#files-list').append(
            '<li id="file-' + data.file_id + '">' +
              '<div class="input-group">' +
                '<input type="text" class="form-control article_file_edit" file_id="' + data.file_id + '" value="' + data.file_name + '" />' +
                '<a href="#" class="input-group-addon btn btn-info article_file_delete" file_id="' + data.file_id + '">' +
                  '<i class="fa fa-trash"></i>' +
                '</a>' +
              '</div>' +
            '</li>'
          );
          files_count++;
          refreshFilesOrderInput();
        }
      },
      url: '/libraries/plupload/upload-articles-files.php',
      chunk_size: '1mb',
      max_file_size: '50mb',
      unique_names: false,
      filters: [
        { title: 'Wszystkie pliki', extensions: '*' }
      ],
      flash_swf_url: '/../libraries/plupload/plupload.flash.swf'
    });

    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();
        }
      });
    }

    if ($.fn && typeof $.fn.iCheck === 'function') {
      $('#fg-article-edit .menu_sortable .g-checkbox').iCheck({
        checkboxClass: 'icheckbox_minimal-blue',
        radioClass: 'iradio_minimal-blue'
      });
    }

    $('ol.sortable').nestedSortable({
      forcePlaceholderSize: true,
      handle: 'div',
      cancel: 'input,textarea,button,select,option,.icheckbox_minimal-blue,.iradio_minimal-blue,ins.iCheck-helper',
      helper: 'clone',
      items: 'li',
      opacity: .6,
      placeholder: 'placeholder',
      revert: 250,
      tabSize: 25,
      tolerance: 'pointer',
      toleranceElement: '> div',
      maxLevels: 3,
      isTree: true,
      expandOnHover: 700,
      isAllowed: function() {
        return false;
      }
    });

    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();
    });

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

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

    <?php foreach ($cookiePages as $key => $val): ?>
      <?php if ($val): ?>$('.list_<?= (int)$key ?>').children('div').children('.disclose').click();<?php endif; ?>
    <?php endforeach; ?>
    <?php foreach ($cookieMenus as $key => $val): ?>
      <?php if ($val): ?>$('.menu_<?= (int)$key ?>').children('div').children('.disclose').click();<?php endif; ?>
    <?php endforeach; ?>

    $('body').on('change', '.image-alt', function() {
      var image_alt = $(this).val();
      var image_id = $(this).attr('image-id');

      $.ajax({
        type: 'POST',
        cache: false,
        url: '/admin/articles/imageAltChange/',
        data: {
          image_id: image_id,
          image_alt: image_alt
        },
        beforeSend: function() {
          $('#overlay').show();
        },
        success: function(data) {
          $('#overlay').hide();
          var response = jQuery.parseJSON(data);
          if (response.status !== 'ok') {
            create_error(response.msg);
          }
        }
      });
    });

    $('body').on('change', '.article_file_edit', function() {
      var file_name = $(this).val();
      var file_id = $(this).attr('file_id');

      $.ajax({
        type: 'POST',
        cache: false,
        url: '/admin/articles/fileNameChange/',
        data: {
          file_id: file_id,
          file_name: file_name
        },
        beforeSend: function() {
          $('#overlay').show();
        },
        success: function(data) {
          $('#overlay').hide();
          var response = jQuery.parseJSON(data);
          if (response.status !== 'ok') {
            create_error(response.msg);
          }
        }
      });
    });

    $('body').on('click', '.article_file_delete', function() {
      $(this).blur();
      var file_id = $(this).attr('file_id');

      confirmDialog('Na pewno chcesz usunac wybrany plik?', function() {
        $.ajax({
          type: 'POST',
          cache: false,
          url: '/admin/articles/fileDelete/',
          data: {
            file_id: file_id
          },
          beforeSend: function() {
            $('#file-' + file_id).children('input').addClass('disabled');
            $('#file-' + file_id).children('a').addClass('disabled');
          },
          success: function(data) {
            var response = jQuery.parseJSON(data);
            if (response.status === 'ok') {
              $('#file-' + file_id).remove();
              refreshFilesOrderInput();
            } else {
              create_error(response.msg);
            }
          }
        });
      }, 'Usun');
      return false;
    });

    $('body').on('click', '.article_image_delete', function() {
      $(this).blur();
      var image_id = $(this).attr('image-id');

      confirmDialog('Na pewno chcesz usunac wybrane zdjecie?', function() {
        $.ajax({
          type: 'POST',
          cache: false,
          url: '/admin/articles/imageDelete/',
          data: {
            image_id: image_id
          },
          beforeSend: function() {
            $('#overlay').show();
          },
          success: function(data) {
            $('#overlay').hide();
            var response = jQuery.parseJSON(data);
            if (response.status === 'ok') {
              $('#image-' + image_id).remove();
              refreshGalleryOrderInput();
            } else {
              create_error(response.msg);
            }
          }
        });
      }, 'Usun');
      return false;
    });

    $('body').on('click', '#g-edit-save, #g-edit-save-close', function() {
      refreshGalleryOrderInput();
      refreshFilesOrderInput();
    });
  });

  function generate_seo_links(lang, title, article_id) {
    if (title === '') {
      return false;
    }

    $.ajax({
      type: 'POST',
      cache: false,
      url: '/admin/pages/generateSeoLink/',
      data: {
        title: title,
        article_id: article_id
      },
      beforeSend: function() {
        $('#seo_link_' + lang).parents('.g-form-data').find('input, a').each(function() {
          $(this).prop('disabled', true).addClass('disabled');
        });
      },
      success: function(data) {
        $('#seo_link_' + lang).parents('.g-form-data').find('input, a').each(function() {
          $(this).prop('disabled', false).removeClass('disabled');
        });

        var response = jQuery.parseJSON(data);
        if (response.status === 'ok') {
          $('#seo_link_' + lang).val(response.seo_link);
        } else {
          create_error(response.msg);
        }
      }
    });
  }
</script>

