<div class="admin-form theme-primary">
  <div class="panel heading-border panel-primary">
    <div class="panel-body">
      <div class="row">
        <div class="col-md-6">
          <label class="field select">
            <select id="client_id" name="client_id">
              <option value="">--- wybierz klienta ---</option>
              <? foreach ( $this -> clients as $client ):?>
                <option value="<?= $client['id'];?>"><?= $client['name'];?></option>
              <? endforeach;?>
            </select>
            <i class="arrow double"></i>
          </label>
        </div>
        <div class="col-md-1 text-right">
          <label>Bestseller min ROAS</label>
        </div>
        <div class="col-md-3">
          <input type="text" id="bestseller_min_roas" name="bestseller_min_roas" class="form-control" placeholder="Minimalny ROAS bestsellerów" value="" />
        </div>
      </div>
    </div>
  </div>
</div>

<div class="admin-form theme-primary">
  <div class="panel heading-border panel-primary">
    <div class="panel-body">
      <table class="table table-sm table-hover" id="products">
        <thead>
          <tr>
            <th scope="col">Id</th>
            <th scope="col">Id oferty</th>
            <th scope="col">Nazwa produktu</th>
            <th scope="col">Wyśw.</th>
            <th scope="col">Wyśw. (30 dni)</th>
            <th scope="col">Klik.</th>
            <th scope="col">Klik. (30 dni)</th>
            <th scope="col">CTR</th>
            <th scope="col">Koszt</th>
            <th scope="col">CPC</th>
            <th scope="col">Konw.</th>
            <th scope="col">Wartość konw.</th>
            <th scope="col">ROAS</th>
            <th scope="col">Min. ROAS</th>
            <th scope="col">CL3</th>
            <th scope="col">CL4</th>
          </tr>
        </thead>
        <tbody>

        </tbody>
      </table>
    </div>
  </div>
</div>
<script type="text/javascript">
  $( function()
  {
    $( 'body' ).on( 'change', '#client_id', function()
    {
      var client_id = $( this ).val();

      table = $( '#products' ).DataTable();
      table.destroy();

      // get min client roas
      $.ajax({
        url: '/products/get_client_bestseller_min_roas/',
        type: 'POST',
        data: {
          client_id: client_id
        },
        success: function( response ) {
          data = JSON.parse(response);
          if  ( data.status == 'ok' )
          {
            $( '#bestseller_min_roas' ).val( data.min_roas );
          }
          else
          {
            $( '#bestseller_min_roas' ).val( '' );
          }
        },
        error: function() {

        }
      });

      new DataTable( '#products', {
        ajax: {
          type: 'POST',
          url: '/products/get_products/client_id=' + client_id,
        },
        processing: true,
        serverSide: true,
        columns: [
          { width: '100px', orderable: false },
          { width: '100px', name: 'offer_id' },
          { width: 'auto', name: 'name' },
          { width: 'auto', name: 'impressions' },
          { width: 'auto', name: 'impressions_30' },
          { width: 'auto', name: 'clicks' },
          { width: 'auto', name: 'clicks_30' },
          { width: 'auto', name: 'ctr' },
          { width: 'auto', name: 'cost', className: "dt-type-numeric" },
          { width: 'auto', name: 'cpc', className: "dt-type-numeric" },
          { width: 'auto', name: 'conversions' },
          { width: 'auto', name: 'conversions_value', className: "dt-type-numeric" },
          { width: 'auto', name: 'roas' },
          { width: '100px', name: 'min_roas' },
          { width: 'auto', name: 'cl3', orderable: false },
          { width: '200px', orderable: false }],
        order: [ [ 5, 'desc' ] ]
      });
    });

    $( 'body' ).on( 'change', '.min_roas', function()
    {
      var input = $( this );
      var product_id = $( this ).attr( 'product_id' );
      var min_roas = $( this ).val();

      input.addClass('saving');
      $.ajax({
        url: '/products/save_min_roas/',
        type: 'POST',
        data: {
          product_id: product_id,
          min_roas: min_roas
        },
        success: function( response ) {
        },
        complete: function() {
        }
      });
    })

    $( 'body' ).on( 'change', '.custom_label_4', function()
    {
      var input = $( this );
      var product_id = $( this ).attr( 'product_id' );
      var custom_label_4 = $( this ).val();

      input.addClass('saving');
      $.ajax({
        url: '/products/save_custom_label_4/',
        type: 'POST',
        data: {
          product_id: product_id,
          custom_label_4: custom_label_4
        },
        success: function( response ) {
        },
        complete: function() {
        }
      });
    });

    $( 'body' ).on( 'click', '.edit-product-title', function(e)
    {
      $.confirm({
        title: 'Edytuj tytuł',
        content: '' +
        '<form action="" class="formName">' +
          '<div class="form-group">' +
            '<input type="text" value="' + escapeHtml( $( this ).siblings( 'a' ).text().trim() ) + '" product_id="' + $( this ).attr( 'product_id' ) + '" class="name form-control" required />' +
            '<small>0/150 znaków</small>' +
          '</div>' +
        '</form>',
        columnClass: 'col-md-8 col-md-offset-2 col-12',
        theme: 'modern',
        draggable: true,
        buttons: {
          formSubmit: {
            text: 'Zapisz',
            btnClass: 'btn-blue',
            action: function () {
              var jc = this;
              var product_id = this.$content.find( '.name' ).attr( 'product_id' );
              var customTitle = this.$content.find('.name').val();

              if ( !customTitle )
              {
                $.alert('Pole tytuł nie może być puste!');
                return false;
              }
              else if (customTitle.length > 150)
              {
                $.alert('Pole tytuł nie może przekraczać 150 znaków!');
                this.$content.find('.name').addClass('is-invalid');
                return false;
              }

              jc.showLoading(true);

              $.ajax({
                url: '/products/save_custom_title/',
                type: 'POST',
                data: {
                  product_id: product_id,
                  custom_title: customTitle
                },
                success: function(response) {
                  data = JSON.parse(response);
                  jc.hideLoading();

                  if  ( data.status == 'ok' )
                  {
                    $.alert( 'Tytuł został pomyślnie zapisany' );
                    jc.close();
                  }
                  else
                  {
                    $.alert('Błąd: ' + response);
                  }
                },
                error: function() {
                  jc.hideLoading();
                  $.alert('Wystąpił błąd podczas zapisywania tytułu. Spróbuj ponownie.');
                }
              });
            }
          },
          cancel: {
            text: 'Anuluj',
            btnClass: 'btn-red',
            action: function () {
            }
          },
        },
        onContentReady: function () {
          var jc = this;

          var inputField = this.$content.find('.name');
          var charCount = this.$content.find('small');

          inputField.on('input', function() {
              var currentLength = $(this).val().length;
              charCount.text(currentLength + '/150 znaków');

              if (currentLength > 150) {
                  $(this).addClass('is-invalid');
              } else {
                  $(this).removeClass('is-invalid');
              }
          });

          this.$content.find('form').on('submit', function (e) {
            e.preventDefault();
            jc.$$formSubmit.trigger('click');
          });
        }
      });
    });

    $( 'body' ).on( 'blur', '#bestseller_min_roas', function(){
      var min_roas = $( this ).val();
      var client_id = $( '#client_id' ).val();

      $.ajax({
        url: '/products/save_client_bestseller_min_roas/',
        type: 'POST',
        data: {
          client_id: client_id,
          min_roas: min_roas
        },
        success: function( response ) {
          data = JSON.parse(response);
          if  ( data.status == 'ok' )
          {
            $.alert( 'Minimalny ROAS bestsellerów został pomyślnie zapisany' );
          }
          else
          {
            $.alert('Błąd: ' + response);
          }
        },
        error: function() {
          $.alert('Wystąpił błąd podczas zapisywania minimalnego ROAS. Spróbuj ponownie.');
        }
      });
    });
  });
</script>