<script type="text/javascript" src="/libraries/framework/vendor/plugins/ckeditor/ckeditor.js"></script>
<script type="text/javascript" src="/libraries/framework/vendor/plugins/ckeditor/adapters/jquery.js"></script>
<script type="text/javascript" src="/libraries/jquery/sortable/sortable.js"></script>
<?
global $db;

$upload_token = bin2hex( random_bytes(24) );
$_SESSION['upload_tokens'][$upload_token] = [
  'user_id' => $this -> user['id'],
  'expires' => time() + 60*20
];

$_SESSION['rfm_akey'] = bin2hex(random_bytes(16));
$_SESSION['rfm_akey_expires'] = time() + 20*60;
$_SESSION['can_use_rfm'] = true;
$rfmAkeyJS = $_SESSION['rfm_akey'];

ob_start();
?>

<div id="settings-tabs">
  <ul class="resp-tabs-list settings-tabs">
    <li><i class="fa fa-file"></i>Opis</li>
    <li><i class="fa fa-file"></i>Zakładki</li>
    <li><i class="fa fa-dollar"></i>Cena</li>
    <li><i class="fa fa-home"></i>Magazyn</li>
    <li><i class="fa fa-wrench"></i>Ustawienia</li>
    <li><i class="fa fa-globe"></i>SEO</li>
    <li><i class="fa fa-share-alt"></i>Wyświetlanie</li>
    <li><i class="fa fa-file-image-o"></i>Galeria</li>
    <li><i class="fa fa-file-archive-o"></i>Załączniki</li>
    <li><i class="fa fa-exchange"></i>Produkty powiązane</li>
    <li><i class="fa fa-file-excel-o"></i>XML</li>
    <li><i class="fa fa-file-o"></i>Dodatkowe pola</li>
    <li><i class="fa fa-file-o"></i>GPSR</li>
  </ul>
  <div class="resp-tabs-container settings-tabs">
    <div>
      <div id="languages-main">
        <ul class="resp-tabs-list languages-main htabs">
          <? if (is_array($this->languages)) : foreach ($this->languages as $lg) : ?>
              <? if ($lg['status']) : ?>
                <li><? if ($lg['id'] == \front\factory\Languages::default_language()) echo '<i class="fa fa-star fa-lg text-system" title="Język domyślny"></i> '; ?><?= $lg['name']; ?></a></li>
              <? endif; ?>
          <?
            endforeach;
          endif;
          ?>
        </ul>
        <div class="resp-tabs-container languages-main">
          <? if (is_array($this->languages)) : foreach ($this->languages as $lg) : ?>
              <?
              $languages = array();

              $languages[''] = '---- wersja językowa ----';
              if (is_array($this->languages))
                foreach ($this->languages as $lg_tmp)
                {
                  if ($lg_tmp['id'] != $lg['id'])
                    $languages[$lg_tmp['id']] = $lg_tmp['name'];
                }
              ?>
              <? if ($lg['status']) : ?>
                <div>
                  <?=
                  \Html::select(
                    array(
                      'label'  => 'Wyświetlaj treść z wersji',
                      'name'   => 'copy_from[' . $lg['id'] . ']',
                      'values' => $languages,
                      'value'  => $this->product['languages'][$lg['id']]['copy_from'],
                    )
                  );
                  ?>
                  <?=
                  \Html::input(
                    array(
                      'label'  => 'Nazwa',
                      'name'   => 'name[' . $lg['id'] . ']',
                      'id'     => 'name_' . $lg['id'],
                      'value'  => $this->product['languages'][$lg['id']]['name'],
                      'inline' => true
                    )
                  );
                  ?>
                  <?=
                  \Html::input(
                    array(
                      'label'  => 'Komunikat gdy stan magazynowy równy 0',
                      'name'   => 'warehouse_message_zero[' . $lg['id'] . ']',
                      'id'     => 'warehouse_message_zero_' . $lg['id'],
                      'value'  => $this->product['languages'][$lg['id']]['warehouse_message_zero'],
                      'inline' => true
                    )
                  );
                  ?>
                  <?=
                  \Html::input(
                    array(
                      'label'  => 'Komunikat gdy stan magazynowy większy niż 0',
                      'name'   => 'warehouse_message_nonzero[' . $lg['id'] . ']',
                      'id'     => 'warehouse_message_nonzero_' . $lg['id'],
                      'value'  => $this->product['languages'][$lg['id']]['warehouse_message_nonzero'],
                      'inline' => true
                    )
                  );
                  ?>
                  <?=
                  \Html::textarea(
                    array(
                      'label'  => 'Krótki opis',
                      'name'   => 'short_description[' . $lg['id'] . ']',
                      'id'     => 'short_description_' . $lg['id'],
                      'value'  => $this->product['languages'][$lg['id']]['short_description'],
                      'inline' => true
                    )
                  );
                  ?>
                  <?=
                  \Html::textarea(
                    array(
                      'label'  => 'Opis',
                      'name'   => 'description[' . $lg['id'] . ']',
                      'id'     => 'description_' . $lg['id'],
                      'value'  => $this->product['languages'][$lg['id']]['description'],
                      'inline' => true
                    )
                  );
                  ?>
                  <script type="text/javascript">
                    $(function() {
                      $('#short_description_<?= $lg['id']; ?>, #description_<?= $lg['id']; ?>').ckeditor({
                        toolbar: 'MyToolbar',
                        height: '250',
                        filebrowserBrowseUrl: '/libraries/filemanager-9.14.2/dialog.php?type=2&editor=ckeditor&akey=<?= $rfmAkeyJS;?>',
                        filebrowserImageBrowseUrl: '/libraries/filemanager-9.14.2/dialog.php?type=1&editor=ckeditor&akey=<?= $rfmAkeyJS;?>',
                        filebrowserUploadUrl: '/libraries/filemanager-9.14.2/dialog.php?type=2&editor=ckeditor&upload=1&akey=<?= $rfmAkeyJS;?>',
                        filebrowserImageUploadUrl: '/libraries/filemanager-9.14.2/dialog.php?type=1&editor=ckeditor&upload=1&akey=<?= $rfmAkeyJS;?>'
                      });
                    });
                  </script>
                </div>
              <? endif; ?>
          <?
            endforeach;
          endif;
          ?>
        </div>
        <div class="clear"></div>
      </div>
    </div>
    <div>
      <div id="languages-tabs">
        <ul class="resp-tabs-list languages-tabs htabs">
          <? if (is_array($this->languages)) : foreach ($this->languages as $lg) : ?>
              <? if ($lg['status']) : ?>
                <li><? if ($lg['id'] == \front\factory\Languages::default_language()) echo '<i class="fa fa-star fa-lg text-system" title="Język domyślny"></i> '; ?><?= $lg['name']; ?></a></li>
              <? endif; ?>
          <?
            endforeach;
          endif;
          ?>
        </ul>
        <div class="resp-tabs-container languages-tabs">
          <? if (is_array($this->languages)) : foreach ($this->languages as $lg) : ?>
              <?
              $languages = array();

              $languages[''] = '---- wersja językowa ----';
              if (is_array($this->languages))
                foreach ($this->languages as $lg_tmp)
                {
                  if ($lg_tmp['id'] != $lg['id'])
                    $languages[$lg_tmp['id']] = $lg_tmp['name'];
                }
              ?>
              <? if ($lg['status']) : ?>
                <div>
                  <?=
                  \Html::input(
                    array(
                      'label'  => 'Nazwa zakładki (1)',
                      'name'   => 'tab_name_1[' . $lg['id'] . ']',
                      'id'     => 'tab_name_1_' . $lg['id'],
                      'value'  => $this->product['languages'][$lg['id']]['tab_name_1'],
                      'inline' => true
                    )
                  );
                  ?>
                  <?=
                  \Html::textarea(
                    array(
                      'label'  => 'Zawartość zakładki (1)',
                      'name'   => 'tab_description_1[' . $lg['id'] . ']',
                      'id'     => 'tab_description_1_' . $lg['id'],
                      'value'  => $this->product['languages'][$lg['id']]['tab_description_1'],
                      'inline' => true
                    )
                  );
                  ?>
                  <?=
                  \Html::input(
                    array(
                      'label'  => 'Nazwa zakładki (2)',
                      'name'   => 'tab_name_2[' . $lg['id'] . ']',
                      'id'     => 'tab_name_2_' . $lg['id'],
                      'value'  => $this->product['languages'][$lg['id']]['tab_name_2'],
                      'inline' => true
                    )
                  );
                  ?>
                  <?=
                  \Html::textarea(
                    array(
                      'label'  => 'Zawartość zakładki (2)',
                      'name'   => 'tab_description_2[' . $lg['id'] . ']',
                      'id'     => 'tab_description_2_' . $lg['id'],
                      'value'  => $this->product['languages'][$lg['id']]['tab_description_2'],
                      'inline' => true
                    )
                  );
                  ?>
                  <script type="text/javascript">
                    $(function() {
                      $('#tab_description_1_<?= $lg['id']; ?>, #tab_description_2_<?= $lg['id']; ?>').ckeditor({
                        toolbar: 'MyToolbar',
                        height: '250',
                        filebrowserBrowseUrl: '/libraries/filemanager-9.14.2/dialog.php?type=2&editor=ckeditor&akey=<?= $rfmAkeyJS;?>',
                        filebrowserImageBrowseUrl: '/libraries/filemanager-9.14.2/dialog.php?type=1&editor=ckeditor&akey=<?= $rfmAkeyJS;?>',
                        filebrowserUploadUrl: '/libraries/filemanager-9.14.2/dialog.php?type=2&editor=ckeditor&upload=1&akey=<?= $rfmAkeyJS;?>',
                        filebrowserImageUploadUrl: '/libraries/filemanager-9.14.2/dialog.php?type=1&editor=ckeditor&upload=1&akey=<?= $rfmAkeyJS;?>'
                      });
                    });
                  </script>
                </div>
              <? endif; ?>
          <?
            endforeach;
          endif;
          ?>
        </div>
        <div class="clear"></div>
      </div>
    </div>
    <div>
      <?=
      \Html::input(
        array(
          'label'    => 'VAT (%)',
          'name'     => 'vat',
          'id'       => 'vat',
          'class'    => 'int-format',
          'value'    => $this->product['id'] ? $this->product['vat'] : 23,
          'onchange' => 'calculate_price_brutto(); return false;'
        )
      );
      ?>
      <?=
      \Html::input(
        array(
          'label'    => 'Cena netto (PLN)',
          'name'     => 'price_netto',
          'id'       => 'price_netto',
          'class'    => 'number-format',
          'value'    => $this->product['price_netto'],
          'onchange' => 'calculate_price_brutto(); return false;'
        )
      );
      ?>
      <?=
      \Html::input(
        array(
          'label'    => 'Cena brutto (PLN)',
          'name'     => 'price_brutto',
          'id'       => 'price_brutto',
          'class'    => 'number-format',
          'value'    => $this->product['price_brutto'],
          'onchange' => 'calculate_price_netto(); return false;'
        )
      );
      ?>
      <?=
      \Html::input(
        array(
          'label'    => 'Promocyjna cena netto (PLN)',
          'name'     => 'price_netto_promo',
          'id'       => 'price_netto_promo',
          'class'    => 'number-format',
          'value'    => $this->product['price_netto_promo'],
          'onchange' => 'calculate_price_brutto_promo(); return false;'
        )
      );
      ?>
      <?=
      \Html::input(
        array(
          'label'    => 'Promocyjna cena brutto (PLN)',
          'name'     => 'price_brutto_promo',
          'id'       => 'price_brutto_promo',
          'class'    => 'number-format',
          'value'    => $this->product['price_brutto_promo'],
          'onchange' => 'calculate_price_netto_promo(); return false;'
        )
      );
      ?>

      <?
      $units[] = '--- wybierze jednostkę miary ---';
      foreach ($this->units as $unit)
        $units[$unit['id']] = $unit['text'];
      ?>
      <?= \Html::select([
        'label' => 'Jednostka miary',
        'name' => 'product_unit',
        'id' => 'product_unit',
        'values' => $units,
        'value' => $this->product['product_unit_id']
      ]); ?>
      <?= \Html::input([
        'label' => 'Waga/pojemność',
        'name' => 'weight',
        'id' => 'weight',
        'class' => 'number-format',
        'value' => $this->product['weight']
      ]); ?>
    </div>
    <div>
      <?=
      \Html::input([
        'label' => 'Stan magazynowy',
        'name'  => 'quantity',
        'id'    => 'quantity',
        'class' => 'int-format',
        'value' => $this->product['quantity']
      ]);
      ?>
      <?=
      \Html::input_switch([
        'label'   => 'Pozwól zamawiać gdy stan 0',
        'name'    => 'stock_0_buy',
        'checked' => $this->product['stock_0_buy'] == 1 ? true : false
      ]);
      ?>
      <?=
      \Html::input([
        'label' => 'Współczynnik WP',
        'name'  => 'wp',
        'id'    => 'wp',
        'class' => 'number-format',
        'value' => $this->product['wp']
      ]);
      ?>
      <?= \Html::input_icon([
        'label' => 'Kod SKU',
        'name' => 'sku',
        'id' => 'sku',
        'value' => $this->product['sku'],
        'icon_content' => 'generuj',
        'icon_js' => 'generate_sku_code( ' . (int)$this->product['id'] . ' );'
      ]); ?>
      <?= \Html::input([
        'label' => 'EAN',
        'name' => 'ean',
        'id' => 'ean',
        'value' => $this->product['ean']
      ]); ?>
    </div>
    <div>
      <?=
      \Html::input_switch([
        'label'   => 'Widoczny',
        'name'    => 'status',
        'checked' => $this->product['status'] == 1 or !$this->product['id'] ? true : false
      ]);
      ?>
      <?=
      \Html::input_switch([
        'label'   => 'Promowany',
        'name'    => 'promoted',
        'checked' => $this->product['promoted'] == 1 ? true : false
      ]);
      ?>
      <?=
      \Html::input([
        'label' => 'Nowość do dnia',
        'name'  => 'new_to_date',
        'id'    => 'new_to_date',
        'class' => 'date',
        'value' => $this->product['new_to_date']
      ]);
      ?>
      <?= \Html::input_switch([
        'label' => 'Wyświetlaj pole na dodatkową wiadomość',
        'name' => 'additional_message',
        'checked' => $this->product['additional_message'] == 1 ? true : false
      ]);
      ?>
      <?= \Html::input_switch([
        'label' => 'Dodatkowa wiadomość jest wymagana',
        'name' => 'additional_message_required',
        'checked' => $this->product['additional_message_required'] == 1 ? true : false
      ]);
      ?>
      <?= \Html::input([
        'label' => 'Dodatkowa wiadomość (treść komunikatu)',
        'name' => 'additional_message_text',
        'id' => 'additional_message_text',
        'value' => $this->product['additional_message_text']
      ]);
      ?>
    </div>
    <div>
      <div id="languages-seo">
        <ul class="resp-tabs-list languages-seo htabs">
          <? if (is_array($this->languages)) : foreach ($this->languages as $lg) : ?>
              <? if ($lg['status']) : ?>
                <li><? if ($lg['id'] == \front\factory\Languages::default_language()) echo '<i class="fa fa-star fa-lg text-system" title="Język domyślny"></i> '; ?><?= $lg['name']; ?></li>
              <? endif; ?>
          <?
            endforeach;
          endif;
          ?>
        </ul>
        <div class="resp-tabs-container languages-seo">
          <? if (is_array($this->languages)) : foreach ($this->languages as $lg) : ?>
              <? if ($lg['status']) : ?>
                <div>
                  <?=
                  \Html::input_icon(
                    array(
                      'label'        => 'Link SEO',
                      'name'         => 'seo_link[' . $lg['id'] . ']',
                      'id'           => 'seo_link_' . $lg['id'],
                      'value'        => $this->product['languages'][$lg['id']]['seo_link'],
                      'icon_content' => 'generuj',
                      'icon_js'      => 'generate_seo_links( "' . $lg['id'] . '", $( "#name_' . $lg['id'] . '" ).val(), ' . (int)$this->product['id'] . ' );'
                    )
                  );
                  ?>
                  <?= \Html::input([
                    'label' => 'Meta title',
                    'name' => 'meta_title[' . $lg['id'] . ']',
                    'id' => 'meta_title_' . $lg['id'],
                    'value' => $this->product['languages'][$lg['id']]['meta_title']
                  ]); ?>
                  <?=
                  \Html::textarea(
                    array(
                      'label' => 'Meta description',
                      'name'  => 'meta_description[' . $lg['id'] . ']',
                      'id'    => 'meta_description_' . $lg['id'],
                      'value' => $this->product['languages'][$lg['id']]['meta_description']
                    )
                  );
                  ?>
                  <?=
                  \Html::textarea(
                    array(
                      'label' => 'Meta keywords',
                      'name'  => 'meta_keywords[' . $lg['id'] . ']',
                      'id'    => 'meta_keywords_' . $lg['id'],
                      'value' => $this->product['languages'][$lg['id']]['meta_keywords']
                    )
                  );
                  ?>
                  <?= \Html::input([
                    'label' => 'Canonical',
                    'name' => 'canonical[' . $lg['id'] . ']',
                    'id' => 'canonical_' . $lg['id'],
                    'value' => $this->product['languages'][$lg['id']]['canonical']
                  ]); ?>
                </div>
              <? endif; ?>
          <?
            endforeach;
          endif;
          ?>
        </div>
        <div class="clear"></div>
      </div>
    </div>
    <div>
      <?
      $layouts[''] = '---- szablon domyślny ----';
      if (is_array($this->layouts)) : foreach ($this->layouts as $layout) :
          $layouts[$layout['id']] = $layout['name'];
        endforeach;
      endif;
      ?>
      <?=
      \Html::select([
        'label'  => 'Szablon',
        'name'   => 'layout_id',
        'id'     => 'layout_id',
        'values' => $layouts,
        'value'  => $this->product['layout_id']
      ]);
      ?>
      <div class="form-group row">
        <label class="col-md-4 control-label">Wyświetlaj w:</label>
        <div class="col-md-8">
          <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>'; ?>
                      <input type="checkbox" class="g-checkbox" name="categories[]" value="<?= $category['id']; ?>" <? if (is_array($this->product['categories']) and in_array($category['id'], $this->product['categories'])) : ?>checked="checked" <? endif; ?> />
                      <b><?= $category['languages'][$this->dlang]['title']; ?></b>
                    </div>
                    <?=
                    \Tpl::view('shop-product/subcategories-list', [
                      'categories' => \admin\factory\ShopCategory::subcategories($category['id']),
                      'product_categories' => $this->product['categories'],
                      'dlang' => $this->dlang
                    ]);
                    ?>
                  </li>
              <?
                endforeach;
              endif;
              ?>
            </ol>
          </div>
        </div>
        <div class="clear"></div>
      </div>
    </div>
    <div>
      <ul id="images-list">
        <?
        $images_count = 0;
        if (is_array($this->product['images'])) : foreach ($this->product['images'] as $img) :
        ?>
            <li id="image-<?= $img['id']; ?>">
              <img class="article-image lozad" data-src="/libraries/thumb.php?img=<?= $img['src']; ?>&w=300&h=300">
              <a href="#" class="input-group-addon btn btn-danger article_image_delete" image-id="<?= $img['id']; ?>">
                <i class="fa fa-trash"></i>
              </a>
              <input type="text" class="form-control image-alt" value="<?= $img['alt']; ?>" image-id="<?= $img['id']; ?>" placeholder="atrybut alt...">
            </li>
        <?
            $images_count++;
          endforeach;
        endif;
        ?>
      </ul>
      <div id="images-uploader">You browser doesn't have Flash installed.</div>
    </div>
    <div>
      <ul id="files-list">
        <?
        $files_count = 0;
        if (is_array($this->product['files'])) : foreach ($this->product['files'] as $file) :

            if ($file['name'])
              $name = $file['name'];
            else
            {
              $name = explode('/', $file['src']);
              $name = $name[count($name) - 1];
            }
        ?>
            <li id="file-<?= $file['id']; ?>">
              <div class="input-group">
                <input type="text" class="product_file_edit form-control" file_id="<?= $file['id']; ?>" value="<?= $name; ?>" />
                <a href="#" class="input-group-addon btn btn-info product_file_delete" file_id="<?= $file['id']; ?>">
                  <i class="fa fa-trash"></i>
                </a>
              </div>
            </li>
        <?
            $files_count++;
          endforeach;
        endif;
        ?>
      </ul>
      <div id="files-uploader">You browser doesn't have Flash installed.</div>
    </div>
    <div>
      <div class="form-group row">
        <label class="col-lg-4 control-label">Wybierz zdefiniowany komplet produktów:</label>
        <div class="col-lg-8">
          <select id="set" class="form-control" name="set">
            <option value="">wybierz komplet...</option>
            <? foreach ($this->sets as $set) : ?>
              <option value="<?= $set['id']; ?>" <? if ($this->product['set_id'] == $set['id']) : ?> selected="selected" <? endif; ?>><?= $set['name']; ?></option>
            <? endforeach; ?>
          </select>
        </div>
      </div>
      <div class="form-group row">
        <label class="col-lg-4 control-label">Produkty powiązane:</label>
        <div class="col-lg-8">
          <select id="products_related" multiple name="products_related[]" placeholder="produkty powiązane">
            <option value="">wybierz produkt...</option>
            <? foreach ($this->products as $key => $val) : ?>
              <? if ($key != $this->product['id']) : ?>
                <option value="<?= $key; ?>" <? if ( is_array( $this -> product['products_related'] ) and in_array($key, $this->product['products_related'])) : ?>selected<? endif; ?>><?= $val; ?></option>
              <? endif; ?>
            <? endforeach; ?>
          </select>
        </div>
      </div>
    </div>
    <div>
      <div class="tab-block mb25">
        <ul class="nav nav-tabs nav-tabs-right tabs-border">
          <? $z = 0; ?>
          <? if (is_array($this->languages)) : foreach ($this->languages as $lg) : ?>
              <? if ($lg['status']) : ?>
                <li class="<? if (!$z++) : ?>active<? endif; ?>">
                  <a href="#xml_name_<?= $this->i; ?>_<?= $lg['id']; ?>" data-toggle="tab" aria-expanded="true"><?= $lg['name']; ?></a>
                </li>
              <? endif; ?>
          <? endforeach;
          endif; ?>
        </ul>
        <div class="tab-content">
          <? $z = 0; ?>
          <? if (is_array($this->languages)) : foreach ($this->languages as $lg) : ?>
              <? if ($lg['status']) : ?>
                <div id="xml_name_<?= $this->i; ?>_<?= $lg['id']; ?>" class="tab-pane <? if (!$z++) : ?>active<? endif; ?>">
                  <label class="col-lg-4 control-label">Nazwa produktu XML (150 znaków):</label>
                  <div class="col-lg-8">
                    <input type="text" class="form-control" name="xml_name[<?= $lg['id']; ?>]" value="<?= $this->product['languages'][$lg['id']]['xml_name']; ?>">
                  </div>
                </div>
              <? endif; ?>
          <? endforeach;
          endif; ?>
        </div>
      </div>
      <?= \Html::input([
        'label' => 'Custom label 0',
        'name' => 'custom_label_0',
        'id' => 'custom_label_0',
        'value' => $this->product['custom_label_0']
      ]);
      ?>
      <?= \Html::input([
        'label' => 'Custom label 1',
        'name' => 'custom_label_1',
        'id' => 'custom_label_1',
        'value' => $this->product['custom_label_1']
      ]);
      ?>
      <?= \Html::input([
        'label' => 'Custom label 2',
        'name' => 'custom_label_2',
        'id' => 'custom_label_2',
        'value' => $this->product['custom_label_2']
      ]);
      ?>
      <?= \Html::input([
        'label' => 'Custom label 3',
        'name' => 'custom_label_3',
        'id' => 'custom_label_3',
        'value' => $this->product['custom_label_3']
      ]);
      ?>
      <?= \Html::input([
        'label' => 'Custom label 4',
        'name' => 'custom_label_4',
        'id' => 'custom_label_4',
        'value' => $this->product['custom_label_4']
      ]);
      ?>
    </div>
    <div>
      <a href="#" class="btn btn-success" id="add_custom_field"><i class="fa fa-plus"></i> dodaj niestandardowe pole</a>
      <div class="additional_fields">
        <? if ( is_array( $this->product['custom_fields'] ) ) : foreach ( $this->product['custom_fields'] as $field ):?>
          <? $isRequired = !empty($field['is_required']); ?>
          <div class="form-group row custom-field-row">
            <label class="col-lg-4 control-label">Nazwa pola:</label>
            <div class="col-lg-8">
              <div class="input-group">
                <input type="text" class="form-control" name="custom_field_name[]" value="<?= htmlspecialchars($field['name']); ?>">
                <span class="input-group-addon">
                  <label style="margin:0; font-weight:normal;">
                    <input type="checkbox" class="custom-field-required" <?= $isRequired ? 'checked' : '' ?> name="custom_field_required[]" />
                    wymagane
                  </label>
                </span>
                <span class="input-group-addon btn btn-info" onclick="remove_custom_filed( $( this ) );">usuń</span>
              </div>
            </div>
          </div>
        <? endforeach; endif;?>
      </div>
    </div>
    <div>
      <?
      $producers[''] = '--- wybierz producenta ---';
      foreach ($this->producers as $producer)
        $producers[$producer['id']] = $producer['name'];
      ?>
      <?= \Html::select([
        'label' => 'Producent',
        'name' => 'producer_id',
        'id' => 'producer_id',
        'values' => $producers,
        'value' => $this->product['producer_id']
      ]); ?>
      <div id="gpsr-seo">
        <ul class="resp-tabs-list gpsr-seo htabs">
          <? if ( is_array( $this -> languages ) ): foreach ( $this -> languages as $lg ):?>
              <? if ($lg['status']) : ?>
                <li><? if ($lg['id'] == \front\factory\Languages::default_language()) echo '<i class="fa fa-star fa-lg text-system" title="Język domyślny"></i> '; ?><?= $lg['name']; ?></li>
              <? endif; ?>
          <? endforeach; endif; ?>
        </ul>
        <div class="resp-tabs-container gpsr-seo">
          <? if ( is_array ($this -> languages ) ): foreach ( $this -> languages as $lg ):?>
              <? if ( $lg['status'] ):?>
                <div>
                  <?= \Html::textarea( [
                      'label' => 'Informacje o bezpieczeństwie ('.$lg['name'].')',
                      'name' => 'security_information[' . $lg['id'] . ']',
                      'id' => 'security_information_' . $lg['id'],
                      'value' => $this->product['languages'][$lg['id']]['security_information']
                    ] );?>
                </div>
                <script type="text/javascript">
                  $(function () {
                    $( '#security_information_<?= $lg[ 'id' ];?>').ckeditor({
                      toolbar: 'MyToolbar',
                      height: '250'
                    });
                  });
                </script>
              <? endif; ?>
          <? endforeach; endif;?>
        </div>
        <div class="clear"></div>
      </div>
    </div>
  </div>
</div>
<?
$out = ob_get_clean();

$grid = new \gridEdit;
$grid->id = 'product-edit';
$grid->gdb_opt = $gdb;
$grid->include_plugins = true;
$grid->title = $this->product['id'] ? 'Edycja produktu: <u>' . $this->product['languages'][\front\factory\Languages::default_language()]['name'] . '</u>' : 'Edycja produktu';
$grid->fields = [
  [
    'db'    => 'id',
    'type'  => 'hidden',
    'value' => $this->product['id']
  ]
];
$grid->actions = [
  'save'   => ['url' => '/admin/shop_product/save/', 'back_url' => '/admin/shop_product/view_list/'],
  'cancel' => ['url' => '/admin/shop_product/view_list/']
];
$grid->buttons = [
  [
    'label' => 'Podgląd',
    'id'    => 'product-preview',
    'url'   => '#',
    'icon'  => 'fa-search',
    'class' => 'btn-primary'
  ]
];
$grid->external_code = $out;
$grid->persist_edit = true;
$grid->id_param = 'id';

echo $grid->draw();
?>

<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/selectize/css/selectize.css">
<link type="text/css" rel="stylesheet" href="/libraries/selectize/css/selectize.default.css">

<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>
<script type="text/javascript" src="/libraries/selectize/js/standalone/selectize.js"></script>

<script type="text/javascript">
  var images_count = <?= $images_count; ?>;
  var files_count = <?= $files_count; ?>;

  function remove_custom_filed( el )
  {
    confirm_delete_element(function() {
      el.parent().parent().parent().remove();
    });
  };

  $(function() {

    $('body').on('click', '#add_custom_field', function() {
      var html = '';
      html += '<div class="form-group row custom-field-row">';
        html += '<label class="col-lg-4 control-label">Nazwa pola:</label>';
        html += '<div class="col-lg-8">';
          html += '<div class="input-group">';
            html += '<input type="text" class="form-control" name="custom_field_name[]" value="">';
            html += '<span class="input-group-addon">';
              html += '<label style="margin:0; font-weight:normal;">';
                html += '<input type="checkbox" class="custom-field-required" name="custom_field_required[]"> wymagane';
              html += '</label>';
            html += '</span>';
            html += '<span class="input-group-addon btn btn-info" onclick="remove_custom_filed( $( this ) );">usuń</span>';
          html += '</div>';
        html += '</div>';
      html += '</div>';
      $('.additional_fields').append(html);
    });

    $('body').on('click', '#product-preview', function() {
      $.ajax({
        type: 'POST',
        cache: false,
        url: '/admin/shop_product/ajax_product_url/',
        data: {
          product_id: $('#id').val()
        },
        success: function(response) {
          data = jQuery.parseJSON(response);
          var win = window.open(data.url, '_blank');
          win.focus();
        }
      });
    });

    $('#products_related').selectize({
      maxItems: 999,
      plugins: ['remove_button']
    });

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

    disable_menu();

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

        $.ajax({
          type: 'POST',
          cache: false,
          url: '/admin/shop_product/images_order_save/',
          data: {
            product_id: '<?= $this->product['id']; ?>',
            order: order
          },
          beforeSend: function() {
            $('#overlay').show();
          },
          success: function(data) {
            $('#overlay').hide();

            response = jQuery.parseJSON(data);

            if (response.status !== 'ok')
              create_error(response.msg);
          }
        });
      }
    });

    $("#images-uploader").pluploadQueue({
      multipart_params: {
        upload_token: '<?= $upload_token ?>',
      },
      runtimes: 'html5,flash,html4',
      init: {
        Refresh: function(up) {
          $(".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) {
          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();
          $('html, body').animate({
            scrollTop: $("#images-uploader").offset().top
          }, 1);
        }
      },
      url: '/libraries/plupload/upload-product-images.php',
      chunk_size: '1mb',
      unique_names: false,
      resize: {
        width: <?= $this->settings['image_px'] ? $this->settings['image_px'] : '1920'; ?>,
        height: <?= $this->settings['image_px'] ? $this->settings['image_px'] : '1920'; ?>,
        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: '<?= $upload_token ?>',
      },
      runtimes: 'html5,flash,html4',
      init: {
        Refresh: function(up) {
          $(".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) {
          data = jQuery.parseJSON(response.response);
          $('#files-list').append(
            '<li id="file-' + data.file_id + '">' +
            '<div class="input-group">' +
            '<input type="text" class="form-control product_file_edit" file_id="' + data.file_id + '" value="' + data.file_name + '" />' +
            '<a href="#" class="input-group-addon btn btn-info product_file_delete" file_id="' + data.file_id + '">' +
            '<i class="fa fa-trash"></i>' +
            '</a>' +
            '</div>' +
            '</li>'
          );
          files_count++;
        }
      },
      url: '/libraries/plupload/upload-product-files.php',
      chunk_size: '1mb',
      unique_names: false,
      filters: [{
        title: "Wszystkie pliki",
        extensions: "*"
      }],
      flash_swf_url: '/../libraries/plupload/plupload.flash.swf'
    });

    $('#settings-tabs').easyResponsiveTabs({
      width: 'auto',
      fit: true,
      tabidentify: 'settings-tabs',
      type: 'vertical'
    });

    $('#languages-main').easyResponsiveTabs({
      width: 'auto',
      fit: true,
      tabidentify: 'languages-main'
    });

    $('#languages-seo').easyResponsiveTabs({
      width: 'auto',
      fit: true,
      tabidentify: 'languages-seo'
    });

    $('#gpsr-seo').easyResponsiveTabs({
      width: 'auto',
      fit: true,
      tabidentify: 'gpsr-seo'
    });

    $('#languages-tabs').easyResponsiveTabs({
      width: 'auto',
      fit: true,
      tabidentify: 'languages-tabs'
    });

    $('ol.sortable').nestedSortable({
      forcePlaceholderSize: true,
      handle: 'div',
      helper: 'clone',
      items: 'li',
      opacity: .9,
      placeholder: 'placeholder',
      revert: 250,
      tabSize: 45,
      tolerance: 'pointer',
      toleranceElement: '> div',
      maxLevels: 2,
      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;
  ?>

  $('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/shop_product/image_alt_change/',
      data: {
        image_id: image_id,
        image_alt: image_alt
      },
      beforeSend: function() {
        $('#overlay').show();
      },
      success: function(data) {
        $('#overlay').hide();

        response = jQuery.parseJSON(data);

        if (response.status !== 'ok')
          create_error(response.msg);
      }
    });
  });

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

    $.ajax({
      type: 'POST',
      cache: false,
      url: '/admin/ajax.php',
      data: {
        a: 'product_file_name_change',
        file_id: file_id,
        file_name: file_name
      },
      beforeSend: function() {
        $('#overlay').show();
      },
      success: function(data) {
        $('#overlay').hide();

        response = jQuery.parseJSON(data);

        if (response.status !== 'ok')
          create_error(response.msg);
      }
    });

  });

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

    $.prompt('Na pewno chcesz usunąć wybrany plik?', {
      title: 'Potwierdź?',
      submit: function(e, v, m, f) {
        if (v === true) {
          $.ajax({
            type: 'POST',
            cache: false,
            url: '/admin/ajax.php',
            data: {
              a: 'product_file_delete',
              file_id: file_id
            },
            beforeSend: function() {
              $('#file-' + file_id).children('input').addClass('disabled');
              $('#file-' + file_id).children('a').addClass('disabled');
            },
            success: function(data) {
              response = jQuery.parseJSON(data);

              if (response.status === 'ok')
                $('#file-' + file_id).remove();
              else
                create_error(msg);
            }
          });
        }
      },
      buttons: {
        'tak': true,
        'nie': false
      },
      focus: 0
    });

  });

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

    $.prompt('Na pewno chcesz usunąć wybrane zdjęcie?', {
      title: 'Potwierdź?',
      submit: function(e, v, m, f) {
        if (v === true) {
          $.ajax({
            type: 'POST',
            cache: false,
            url: '/admin/shop_product/image_delete/',
            data: {
              image_id: image_id
            },
            beforeSend: function() {
              $('#overlay').show();
            },
            success: function(data) {
              $('#overlay').hide();
              response = jQuery.parseJSON(data);

              if (response.status === 'ok')
                $('#image-' + image_id).remove();
              else
                create_error(msg);
            }
          });
        }
      },
      buttons: {
        'tak': true,
        'nie': false
      },
      focus: 0
    });
    return false;
  });

  $('body').on('keyup', '#price_netto', function() {
    calculate_price_brutto();
  });

  $('body').on('keyup', '#price_brutto', function() {
    calculate_price_netto();
  });

  $('body').on('keyup', '#price_netto_promo', function() {
    calculate_price_brutto_promo();
  });

  $('body').on('keyup', '#price_brutto_promo', function() {
    calculate_price_netto_promo();
  });
  });

  function calculate_price_brutto_promo() {
    var price_netto = $('#price_netto_promo').val().replace(',', '.');
    var vat = $('#vat').val().replace(',', '.');

    var price_brutto = price_netto * 1 + price_netto * vat / 100;
    price_brutto = Math.floor(price_brutto * 100) / 100;
    price_brutto = number_format(price_brutto, 2, '.', '');

    if (Math.floor(price_netto) <= 0) {
      $('#price_netto_promo').val('');
      $('#price_brutto_promo').val('');
      return true;
    }

    return $('#price_brutto_promo').val(price_brutto);
  }

  function calculate_price_netto_promo() {
    var price_brutto = $('#price_brutto_promo').val().replace(',', '.');
    var vat = $('#vat').val().replace(',', '.');

    var price_netto = price_brutto / (vat / 100 + 1);
    price_netto = number_format(price_netto, 2, '.', '');

    if (Math.floor(price_brutto) <= 0) {
      $('#price_netto_promo').val('');
      $('#price_brutto_promo').val('');
      return true;
    }

    return $('#price_netto_promo').val(price_netto);
  }

  function calculate_price_brutto() {
    var price_netto = $('#price_netto').val().replace(',', '.');
    if (!price_netto)
      return false;
    var vat = $('#vat').val().replace(',', '.');

    var price_brutto = price_netto * 1 + price_netto * vat / 100;
    price_brutto = Math.floor(price_brutto * 100) / 100;
    price_brutto = number_format(price_brutto, 2, '.', '');

    return $('#price_brutto').val(price_brutto);
  }

  function calculate_price_netto() {
    var price_brutto = $('#price_brutto').val().replace(',', '.');
    var vat = $('#vat').val().replace(',', '.');

    var price_netto = price_brutto / (vat / 100 + 1);
    price_netto = number_format(price_netto, 2, '.', '');

    return $('#price_netto').val(price_netto);
  }

  function generate_sku_code(product_id) {
    $.ajax({
      type: 'POST',
      cache: false,
      url: '/admin/shop_product/generate_sku_code/',
      data: {
        product_id: product_id
      },
      beforeSend: function() {
        $('#sku').addClass('disabled');
      },
      success: function(data) {
        $('#sku').removeClass('disabled');
        response = jQuery.parseJSON(data);

        if (response.status === 'ok')
          $('#sku').val(response.sku);
        else
          create_error(response.msg);
      }
    });
  }

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

    $.ajax({
      type: 'POST',
      cache: false,
      url: '/admin/ajax.php',
      data: {
        a: 'generate_seo_link',
        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');
        });

        response = jQuery.parseJSON(data);

        if (response.status === 'ok')
          $('#seo_link_' + lang).val(response.seo_link);
        else
          create_error(response.msg);
      }
    });
  }
</script>
<script>
  CKEDITOR.dtd.$removeEmpty['span'] = false;
</script>