<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-6">
          <label class="field select">
            <select id="campaign_id" name="campaign_id">
              <option value="">--- wybierz kampanię ---</option>
            </select>
            <i class="arrow double"></i>
          </label>
        </div>
      </div>
    </div>
  </div>
</div>

<div class="admin-form theme-primary">
  <div class="panel heading-border panel-primary">
    <div class="panel-body">
      <figure class="highcharts-figure">
        <div id="container"></div>
      </figure>
    </div>
  </div>
</div>

<div class="admin-form theme-primary">
  <div class="panel heading-border panel-primary">
    <div class="panel-body">
      <table class="table" id="products">
        <thead>
          <tr>
          <th scope="col">Data</th>
            <th scope="col">ROAS (30 dni)</th>
            <th scope="col">ROAS (all time)</th>
            <th scope="col">Wartość konwersji (30 dni)</th>
            <th scope="col">Wydatki (30 dni)</th>
            <th scope="col">Komentarz</th>
            <th scope="col">Strategia ustalania stawek</th>
            <th scope="col">Budżet</th>
          </tr>
        </thead>
        <tbody>

        </tbody>
      </table>
    </div>
  </div>
</div>
<script type="text/javascript">
  var client_id = '';
  $( function()
  {
    // load campaigns from server when client is selected
    $( 'body' ).on( 'change', '#client_id', function()
    {
      client_id = $( this ).val();
      var campaigns_select = $( '#campaign_id' );

      $.ajax(
      {
        url: '/campaigns/get_campaigns_list/client_id=' + client_id,
        type: 'GET',
        success: function( response )
        {
          var data = JSON.parse(response);

          campaigns_select.empty();
          campaigns_select.append('<option value="">- wybierz kampanię -</option>');

          var campaigns = Object.entries(data.campaigns);

          // Sortowanie kampanii: "--- konto ---" zawsze na początku, reszta alfabetycznie
          campaigns.sort(function(a, b) {
              if (a[1] === "--- konto ---") {
                  return -1; // "a" idzie na początek
              } else if (b[1] === "--- konto ---") {
                  return 1; // "b" idzie na początek
              } else {
                  // Porównanie ciągów znaków bez użycia localeCompare
                  return a[1] > b[1] ? 1 : (a[1] < b[1] ? -1 : 0);
              }
          });

          // Dodawanie opcji do selecta
          campaigns.forEach(function([key, value]) {
              campaigns_select.append('<option value="' + value.id + '">' + value.campaign_name + '</option>');
          });

          <? if ( $campaign_id ): ?>
            campaigns_select.val('<?= $campaign_id; ?>').trigger('change');
          <? endif; ?>
        }
      });
    });

    $( 'body' ).on( 'change', '#campaign_id', function()
    {
      var campaign_id = $( this ).val();

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

      new DataTable( '#products', {
        ajax: {
          type: 'POST',
          url: '/campaigns/get_campaign_history_data_table/campaign_id=' + campaign_id,
        },
        processing: true,
        serverSide: true,
        columns: [
          { width: '100px', name: 'date', orderable: false },
          { width: '200px', name: 'roas30', orderable: false, className: "dt-type-numeric" },
          { width: '200px', name: 'roas_all_time', orderable: false, className: "dt-type-numeric" },
          { width: '250px', name: 'conversion_value', orderable: false, className: "dt-type-numeric" },
          { width: '200px', name: 'spend30', orderable: false, className: "dt-type-numeric" },
          { width: 'auto', name: 'bidding_strategy', orderable: false },
          { width: 'auto', name: 'comment', orderable: false },
          { width: '150px', name: 'budget', orderable: false, className: "dt-type-numeric" }
        ],
      });

      $.ajax({
        url: '/campaigns/get_campaign_history_data_table_chart/',
        method: 'POST',
        data: {
          campaign_id: campaign_id
        },
        success: function(response) {
          const parsedData = JSON.parse(response);

          let plotLines = [];

          parsedData.comments.forEach(function(comment) {
            plotLines.push({
              color: '#333333',
              width: 1,
              value:  parsedData.dates.indexOf(comment.date_add.split(' ')[0]),
              dashStyle: 'Solid',
              label: {
                text: comment.comment,
                align: 'left',
                style: {
                  color: '#333333',
                  fontSize: '14px'
                }
              },
              zIndex: 5
            });
          });

          Highcharts.chart('container', {
              title: {
                text: ``,
              },
              subtitle: {
                text: ``,
              },
              yAxis: {
                title: {
                  text: ''
                },
              },
              xAxis: {
                categories: parsedData.dates,
                labels: {
                  style: {
                    fontSize: '14px'
                  },
                  formatter: function() {
                    var date = new Date(Date.parse(this.value));
                    var day = date.getDate();
                    var month = date.getMonth() + 1;
                    var year = date.getFullYear();

                    if (day === 1 || this.isLast) {
                      return `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`;
                    } else {
                        return null;
                    }
                  }
                },
                plotLines: plotLines
              },
              legend: {
                layout: 'vertical',
                align: 'right',
                verticalAlign: 'middle',
                itemStyle: {
                  fontSize: '14px'
                }
              },
              plotOptions: {
                series: {
                  label: {
                    connectorAllowed: false
                  },
                  pointStart: 0,
                },
              },
              series: parsedData.chart_data,
              tooltip: {
                style: {
                  fontSize: '14px'
                }
              }
          });
        },
        error: function (jqXHR, textStatus, errorThrown) {
          console.error('Error AJAX:', textStatus, errorThrown);
        }
      })
    })
  });
</script>