<script src="<?= base_url();?>/assets/plugins/chart-js/Chart.min.js"></script>
<script src="<?= base_url();?>/assets/plugins/chart-js/chartjs-plugin-datalabels.min.js"></script>
<script src="<?= base_url();?>/assets/plugins/gritter/js/jquery.gritter.js"></script>
<script src="<?= base_url();?>/assets/js/page-index-v3.demo.min.js"></script>

<style type="text/css">
  .table > thead > tr > th {
     vertical-align: middle;
     text-align: center;
  }
  .table > tbody > tr > td {
     vertical-align: middle;
     text-align: center;
  }
</style>

<h4>Nomor Batch: <?= $nomor_batch; ?></h4>
<div class="row">
    <!-- begin col-8 -->
    <div class="col-sm-12">
        <!-- begin panel -->
        <div class="panel panel-grey">
            <div class="panel-heading">
        		   <div class="panel-heading-btn">
                  <a href="javascript:;" class="btn btn-xs btn-icon btn-circle btn-grey" data-click="panel-expand"><i class="fa fa-expand"></i></a>
                  <a href="javascript:;" class="btn btn-xs btn-icon btn-circle btn-grey" data-click="panel-remove"><i class="fa fa-times"></i></a>
              </div>
              <?php if(empty($is_grafik)) : ?>
                  <button type="button" class="btn btn-primary" onclick="add_deret()">Add Data</button>
                  <input id="t_deret" type="number">
              <?php endif; ?>

              <?php if(!empty($is_grafik)) : ?>
                <div class="btn-group">
                      <a href="<?= site_url('batch_list/'.$jenis_uji); ?>" class="btn btn-primary btn-md">Kembali</a>
                      <a href="<?= site_url('kontrol_sampel_list/'.$jenis_uji.'/'.$nomor_batch); ?>" class="btn btn-warning btn-md">Kontrol Sampel</a>
                      <a href="<?= site_url('deret_uji_grafik/'.$jenis_uji.'/'.$nomor_batch.'/1'); ?>" class="btn btn-warning btn-md active">Deret Standar <?= ucwords($jenis_uji); ?></a>
                  </div>
              <?php endif; ?>
              <hr>
            </div>

            <form class="form-horizontal" id="form1" method="post" action="<?= site_url('save_deret_uji/'.$jenis_uji.'/'.$nomor_batch); ?>">
            <div class="panel-body table-responsive">
              <table class="table table-bordered table-striped">
                <thead class="bg-inverse text-center">
                  <tr class="inverse">
                    <th rowspan="2">No</th>
                    <th rowspan="2">Level Standar (ppb)</th>
                    <th colspan="4">Hasil Pembacaan Deret Standar Aflatoksin</th>
                  </tr>
                  <tr class="inverse">
                    <th>Abs<br>(Y)</th>
                    <th>Intercept<br>(a)</th>
                    <th>Slope<br>(b)</th>
                    <th>Total Aflatoksin (ppb) terbaca</th>
                  </tr>
                </thead>
                <tbody id="t_body">
                  <tr id="tb_deret"></tr>
                  <?php if(!empty($is_grafik)) : ?>
                    <?php $i=1; foreach($data as $r) : ?>
                      <tr>
                        <td><?= $this->uri->segment(5) + $i++; ?></td>
                        <td><?= round($r['level_standart'], 0) ?></td>
                        <td><?= $r['abs'] ?></td>
                        <td><?= $r['intercept']; ?></td>
                        <td><?= $r['slope']; ?></td>
                        <td><?= $r['total_af']; ?></td>
                      </tr>
                    <?php endforeach; ?>
                  <?php endif; ?>
                </tbody>
              </table>

            </div>
            <div class="panel-footer">
              <input type="hidden" name="nomor_batch[]" value="<?= $nomor_batch; ?>">
              <?php if(empty($is_grafik)) : ?>
                <button type="button" class="btn btn-primary" onclick="$('#form1').submit();">Lanjut ke Uji Aflatoksin Total</button>
              <?php endif; ?>
            </div>
            </form>
        </div>
    </div>
</div>

<?php if(!empty($is_grafik)) : ?>
<div class="panel panel-lime">
<div class="panel no-rounded-corner bg-default text-white wrapper m-b-0">
<div class="chartjs-size-monitor" style="position: absolute; left: 0px; top: 0px; right: 0px; bottom: 0px; overflow: hidden; pointer-events: none; visibility: hidden; z-index: -1;">
<div class="chartjs-size-monitor-expand" style="position:absolute;left:0;top:0;right:0;bottom:0;overflow:hidden;pointer-events:none;visibility:hidden;z-index:-1;">
<div style="position:absolute;width:1000000px;height:1000000px;left:0;top:0">
</div></div><div class="chartjs-size-monitor-shrink" style="position:absolute;left:0;top:0;right:0;bottom:0;overflow:hidden;pointer-events:none;visibility:hidden;z-index:-1;"><div style="position:absolute;width:200%;height:200%;left:0; top:0"></div></div></div>
                            <!-- end btn-group -->
                            <!-- begin title -->
                            <h4 class=" m-t-0 m-b-10">
                                <i class="fa fa-snowflake-o text-success-light"></i> Persamaan Kurva Kalibrasi/Standar
                                <small class="text-muted m-l-5"><?= date('Y'); ?></small>
                            </h4>
                            <!-- end title -->
                            <!-- begin chart -->
                        <canvas id="line-chart" style="display: block; width: 500px; height: 166px;" height="166" width="500"></canvas>
                        </div>
                        <div class="col-sm-12" style="margin-left: 40px;">
                          <h4>Rumus Persamaan</h4>
                          <label> y = <?= $grafik[0]['slope'].'x '.(strpos('|'.$grafik[0]['intercept'], '-')  == false ? '+' : '').$grafik[0]['intercept']; ?></label>
                          <br>
                          <label> r = <?= number_format(round($grafik[0]['d_range'], 4), 4);?></label>
                        </div>
</div>
<?php endif; ?>
<?php if(!empty($is_grafik)): ?>
<?php $a=array(); foreach($grafik as $r) {$a[] = (round($r['k_c'], 1)).'d';}?>
<?php $b=array(); foreach($grafik as $r) {$b[] = round($r['k_d'], 1);}?>
<?php 
  $n = '';
  $d = array();
  for($i=0;$i< 30 ;$i++){
    $v = $i*0.1-1.2;
    $v = (strlen($v)>10?'0':$v).'d';
    $d[] = $v;

    if(in_array($v, $a)) {
      for($c=0;$c<count($a);$c++) {
        if($v == $a[$c]) {
          if($b[$c] == 0){
            $n .= 'null,';
          }else{
            $n .= $b[$c].',';  
          }  
        }
      }
    } else {
      $n .= 'null,';
    }
  }

?>

<script>
new Chart(document.getElementById("line-chart"), {
  type: 'line',
  data: {
    labels: [<?php for ($i = 0; $i < 30 ; $i++) {
    $v = $i*0.1-1.2;
    echo (strlen($v)>10?'0':$v).',';
}?>],
    datasets: [{
        data: [<?= $n; ?>],
        label: '',//"Data Uji Sampel",
        borderColor: "#00e6e6",
        backgroundColor: "rgba(0, 0, 0, 0)",
        fill: true
      }
    ]
  },
  options: {
    spanGaps: true,
    elements: {
      line: {
          tension: 0
      }
    },
    legend: { display: false },
    title: {
      display: false,
    //   text: 'World population per region (in millions)'
    },
    plugins: {
      datalabels: {
          anchor :'end',
          align :'top',
      }
    },
    scales: {
        xAxes: [{
            ticks: {
                min: 0.00,
                max: 2.000,

                // forces step size to be 5 units
                stepSize: 0.200
            },
          display: true,
          scaleLabel: {
              display: true,
              labelString: ''//'Bulan'
          }
                }],
            yAxes: [{
            display: true,
            scaleLabel: {
              display: true,
              labelString: ''//'Jumlah Sampel'
            },
            ticks: {
              min: -2.000,
              max: 2.000,

              // forces step size to be 5 units
              stepSize: 0.200
            }
          }],
      }
  }
});
</script>
<?php endif; ?>

<script type="text/javascript">
  //---------------------------
  var x = [];
  var y = [];
  var xy = [];
  var x2 = [];

  var xxax = [];
  var yyay = [];

  var k_s = [];
  var abs = [];

  var kb = [];
  var kd = [];
  var kc = [];
  var cd = [];

  function cek_rumus(z){
    var tx = 0;
    var ty = 0;
    var txy = 0;
    var tx2 = 0;
    var cxx2 = 0;
    var cyy2 = 0;
    var cxxayy = 0;

    k_s[z] = parseFloat($('#deret_std_urea'+z).val());
    abs[z] = parseFloat($('#abs'+z).val());


    for(var i = 0; i < k_s.length; i++) {

      cd[i] = k_b = abs[i]/abs[0];

      var c_d = k_b/(1-k_b);
      k_c = Math.log10(k_s[i]);
      k_d = Math.log10(c_d);

      x[i] = k_c;
      y[i] = k_d;
      xy[i] = k_c*k_d;

      kb[i] = abs[i]/abs[0];
      kc[i] = Math.log10(x[i]);
      kd[i] = Math.log10((kb[i]/(1-kb[i])));
    }

    console.log('k_b:'+kb);
    console.log('k_c:'+kc);
    console.log('k_d:'+kd);

    for (var i = 1; i < x.length; i++) {
        x2[i] = Math.pow(x[i], 2);
        ty += y[i];
        tx += x[i];
        txy += xy[i];
        tx2 += x2[i];
    }

    var xlength = x.length-1;
    var ylength = y.length-1;

    var rx = tx / xlength;
    var ry = ty / ylength;

    var ntxy = xlength * txy;
    var txty = (tx * ty);
    var ntx2 = xlength * tx2;
    var ttx2 = Math.pow(tx, 2);

    var ttx22 = Math.pow(tx, 2);
    var txtxy = tx * txy;
    //txtxy = txtxy.toFixed(4);

    var slope = ((ntxy-txty)/(ntx2-ttx2));
    var intercept = (((ty*tx2)-txtxy)/(ntx2-ttx2));

    intercept = intercept.toFixed(4);
    slope = slope.toFixed(4);

    for(i=1;i<x.length;i++){
      var h1 = (x[i]-rx);
      var h2 = (y[i]-ry);
      var xx2 = Math.pow(h1, 2);
      var yy2 = Math.pow(h2, 2);
      cxx2 += xx2;
      cyy2 += yy2;
    }

    var ax = Math.sqrt((1/(xlength-1))*(cxx2));
    var ay = Math.sqrt((1/(ylength-1))*(cyy2));

    for(i=1;i<x.length;i++){
      var p1 = ((x[i]-rx)/ax);
      xxax[i] = p1;
      var p2 = ((y[i]-ry)/ay);
      yyay[i] = p2;
      var xxayy = (p1*p2);
      cxxayy += xxayy;


      var kg =abs[i]/abs[0];
      var kh2 = (kg/(1-kg));

      var kh = Math.log10(kh2);
      var ki = Math.pow(10,((kh-intercept)/slope));

      var dilution = 1;

      var c_std = ki*dilution;
      $('#c_std'+i).val(c_std.toFixed(2));
      $('#k_b'+i).val(kb[i]); 
      $('#k_c'+i).val(kc[i]); 
      $('#k_d'+i).val(kd[i]); 
    }

    var range = ((1/((xlength)-1))*cxxayy);

    console.log(range);

    $('.intercept').val(intercept);
    $('.slope').val(slope); 
    $('.d_range').val(range.toFixed(4));
    $('.abs0').val(abs[0]);  

  }

  function add_deret(){
    var d = parseInt($('#t_deret').val());

    for(i=0;i<d;i++){
      var row = "\n\
        <tr style='text-align:center;'>\n\
          <td></td>\n\
          <td><input class='dt-wt deret_std_urea' name='deret_level[]' required></td>\n\
          <td><input class='dt-wt abs' name='abs[]' required></td>\n\
          <td><input class='dt-wt intercept' name='intercept[]'></td>\n\
          <td>\n\
            <input class='dt-wt slope' name='slope[]'>\n\
            <input class='dt-wt d_range' type='hidden' name='d_range[]'>\n\
            \n\
            <input class='dt-wt k_b' type='hidden' name='k_b[]'>\n\
            <input class='dt-wt k_c' type='hidden' name='k_c[]'>\n\
            <input class='dt-wt k_d' type='hidden' name='k_d[]'>\n\
            <input class='dt-wt abs0' type='hidden' name='abs0[]'>\n\
          </td>\n\
          <td><input class='dt-wt c_std' name='c_std[]'></td>\n\
        </tr>\n\
      ";
      $("#tb_deret").before(row);
    }

    // DUMMY DATA
    var deret = [0,4,10,20,40];
    var abs2 = [2.471,1.657,0.890,0.438,0.190];

    var tr = $('#t_body tr');
    for (var i = 0; i < tr.length; i++) {
        var td = $(tr[i]).find('td').first().text(i+1);
        $(tr[i]).find('.deret_std_urea').first().attr('onkeyup', 'cek_rumus('+(i)+')');
        $(tr[i]).find('.deret_std_urea').first().attr('id', 'deret_std_urea'+(i));

        $(tr[i]).find('.abs').first().attr('onkeyup', 'cek_rumus('+(i)+')');
        $(tr[i]).find('.abs').first().attr('id', 'abs'+(i));

        $(tr[i]).find('.intercept').first().attr('id', 'intercept'+(i));
        $(tr[i]).find('.slope').first().attr('id', 'slope'+(i));
        $(tr[i]).find('.c_std').first().attr('id', 'c_std'+(i));

        $(tr[i]).find('.k_b').first().attr('id', 'k_b'+(i));
        $(tr[i]).find('.k_c').first().attr('id', 'k_c'+(i));
        $(tr[i]).find('.k_d').first().attr('id', 'k_d'+(i));

        // DUMMY DATA
        $(tr[i]).find('.abs').first().val(parseFloat(abs2[i]));
        $(tr[i]).find('.deret_std_urea').first().val(parseFloat(deret[i]));
        if(i < 5) {
          cek_rumus(i);
        }
    }

  }
  // DUMMY DATA
  $('#t_deret').val(5);
  add_deret();
</script>
