<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.content',
      cancel: 'input,textarea,button,select,option,.icheckbox_minimal-blue,.iradio_minimal-blue,ins.iCheck-helper',
      helper: 'original',
      items: 'li',
      opacity: .6,
      placeholder: 'placeholder',
      revert: 250,
      tabSize: 25,
      tolerance: 'pointer',
      toleranceElement: '> div.content',
      maxLevels: 4,
      isTree: true,
      expandOnHover: 700,
      isAllowed: function() { return false; }
    });

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

    refreshTreeDisclosureState();

    // Inicjalizacja iCheck — osobno dla produktów i kategorii
    if ($.fn && typeof $.fn.iCheck === 'function') {
      $('.product-item .g-checkbox').iCheck({
        checkboxClass: 'icheckbox_minimal-blue',
        radioClass: 'iradio_minimal-blue'
      });
      $('#sortable input.g-checkbox').iCheck({
        checkboxClass: 'icheckbox_minimal-blue',
        radioClass: 'iradio_minimal-blue'
      });
    }

    $('body').on('click', '.disclose', 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) {
        var category_id = $(this).parent('div').parent('li').attr('id');
        $.ajax({
          type: 'POST',
          cache: false,
          url: '/admin/shop_category/cookie_categories/',
          data: { category_id: category_id }
        });
      }
    });

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

    $('.select-all').click(function() {
      $('.product-item .g-checkbox').iCheck('check');
    });

    $('.deselect-all').click(function() {
      $('.product-item .g-checkbox').iCheck('uncheck');
    });

    $('body').on('click', 'span[field-id="discount_percent"]', function() {
      $('.ajax-msg').remove();
      var discount_percent = $('#discount_percent').val();
      var products = [];
      $('input[name="products[]"]:checked').each(function() {
        products.push($(this).val());
      });

      function saveProduct(index) {
        if (index < products.length) {
          $.ajax({
            url: '/admin/shop_product/mass_edit_save/',
            type: 'post',
            data: { discount_percent: discount_percent, products: [products[index]] },
            success: function(data) {
              data = JSON.parse(data);
              if (data.status == 'ok') {
                if (data.price_brutto_promo)
                  $('label[for="product' + products[index] + '"]').append(' <span class="ajax-msg text-success">cena promocyjna: ' + data.price_brutto_promo + ' zł, cena zwykła: ' + data.price_brutto + '</span>');
                else
                  $('label[for="product' + products[index] + '"]').append(' <span class="ajax-msg text-success">cena zwykła: ' + data.price_brutto + '</span>');
              } else {
                alert('Błąd przy zapisie produktu: ' + products[index]);
              }
              saveProduct(index + 1);
            },
            error: function() {
              alert('Błąd przy zapisie produktu: ' + products[index]);
            }
          });
        } else {
          $.alert({
            title: 'Informacja',
            content: 'Zakończono zapisywanie produktów',
            type: 'orange',
            closeIcon: true,
            closeIconClass: 'fa fa-close',
            typeAnimated: true,
            animation: 'opacity',
            useBootstrap: false,
            theme: 'modern',
            autoClose: 'cancel|10000',
            icon: 'fa fa-exclamation',
            buttons: {
              confirm: {
                text: 'Zamknij',
                btnClass: 'btn-blue',
                keys: ['enter'],
                action: function() {}
              }
            }
          });
        }
      }

      if (products.length > 0) {
        saveProduct(0);
      }
    });
  });
</script>
