<div class="panel mb50 panel-primary">
  <div class="panel-heading">
    <span class="panel-title">Masowa edycja produktów</span>
  </div>
  <div class="panel-body">
    <button class="btn btn-dark select-all">Zaznacz wszystkie</button>
    <button class="btn btn-default btn-outline-dark deselect-all">Odznacz wszystkie</button>
  </div>
  <div class="panel-body">
    <div class="form-group mb10">
      <label class="col-lg-3 control-label" for="inputDefault">Ustaw cenę promocyjną (minus X procent)</label>
      <div class="col-lg-9">
        <div class="bs-component">
          <div class="input-group">
            <input class="form-control" type="text" id="discount_percent" name="discount_percent">
            <span class="input-group-addon cursor" field-id="discount_percent">
              <i class="fa fa-save"></i>
            </span>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="panel-body">
    <div class="row">
      <div class="col-lg-6">
        <? foreach ( $this -> products as $key => $product ):?>
          <div class="checkbox-custom fill mb5">
            <input type="checkbox" name="products[]" id="product<?= $key;?>" value="<?= $key;?>">
            <label for="product<?= $key;?>"><?= $product;?></label>
          </div>
        <? endforeach;?>
      </div>
      <div class="col-lg-6">
        <div class="menu_sortable">
          <ol class="sortable" id="sortable">
            <? if ( is_array( $this -> categories ) ): foreach ( $this -> categories as $category ):?>
              <li id="list_<?= $category['id'];?>" class="category_<?= $category['id'];?>" category="<?= $category['id'];?>">
                <div class="context_0 content content_menu">
                  <span class="disclose"><span></span></span>
                  <? if ( !$category['status'] ) echo '<i class="fa fa-ban fa-lg text-danger" title="Kategoria nieaktywna"></i>';?>
                  <b><?= $category['languages'][$this -> dlang]['title'];?></b>
                </div>
                <?= \Tpl::view( 'shop-product/subcategories-list', [
                        'categories' => \admin\factory\ShopCategory::subcategories( $category['id'] ),
                        'level' => $this -> level + 1,
                        'dlang' => $this -> dlang
                      ] );?>
              </li>
            <? endforeach; endif;?>
          </ol>
        </div>
      </div>
    </div>
  </div>
</div>
<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: .9,
			placeholder: 'placeholder',
			revert: 250,
			tabSize: 45,
			tolerance: 'pointer',
			toleranceElement: '> div',
			maxLevels: 4,
			isTree: true,
			expandOnHover: 700,
      protectRoot: false
		});

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

    $( '.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/ajax.php',
          data: {
            a: 'cookie_categories',
            category_id:  category_id
          }
        });
      }
    });

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

    $( '.select-all' ).click( function()
    {
      $( '.checkbox-custom input' ).prop( 'checked', true );
    });

    $( '.deselect-all' ).click( function()
    {
      $( '.checkbox-custom input' ).prop( 'checked', false );
    });

    $( 'body' ).on( 'click', '#sortable input[type="checkbox"]', function(){
      if ( $( this ).is( ':checked' ) ) {
        $.ajax({
          url: '/admin/shop_product/get_products_by_category/',
          type: 'post',
          data: {
            category_id: $( this ).val()
          },
          success: function(data) {
            data = JSON.parse(data);
            if ( data.status == 'ok' ) {
              $.each( data.products, function( key, value ) {
                $( '#product' + value ).prop( 'checked', true );
              });
            }
          }
        })
      } else {
        $.ajax({
          url: '/admin/shop_product/get_products_by_category/',
          type: 'post',
          data: {
            category_id: $( this ).val()
          },
          success: function(data) {
            data = JSON.parse(data);
            if ( data.status == 'ok' ) {
              $.each( data.products, function( key, value ) {
                $( '#product' + value ).prop( 'checked', false );
              });
            }
          }
        })
      }
    });

    $( '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]);
              }
              // Wywołanie dla następnego produktu
              saveProduct(index + 1);
            },
            error: function(err) {
              alert('Błąd przy zapisie produktu: ', err);
              // Można dodać obsługę błędu lub przerwać proces
            }
          });
        } else {
          $.alert({
            title: 'Informacja',
            content: 'Zakończono zapisywanie produktów',
            type: 'orange',
            closeIcon: true,
            closeIconClass: 'fa fa-close',
            typeAnimated: true,
            animation: 'opacity',
            autoClose: 'confirm|10000',
            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); // Rozpoczęcie od pierwszego produktu
      }
    });
  });
</script>