<script src="<?php echo base_url();?>/assets/plugins/chart-js/Chart.min.js"></script>
<script src="<?php echo base_url();?>/assets/plugins/chart-js/chartjs-plugin-datalabels.min.js"></script>
<script src="<?php echo base_url();?>/assets/plugins/gritter/js/jquery.gritter.js"></script>
<script src="<?php echo 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: <?php echo (!empty($data[0]['nomor_batch']) ? $data[0]['nomor_batch'] : $this->session->userdata('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>
              <!-- <a href="<?php //echo site_url('sampel/pengajuan/create_deret_fosfor?nomor_batch='); ?>" class="btn btn-primary">
                Tambah Data
              </a> -->
              <?php if(!empty($method) && $method == 'edit') { ?>
                <form method="post" id="form2">
                    <?php
                      if(!empty($id_sampel)){
                        foreach($id_sampel as $s ) echo "<input type='hidden' name='id_sampel[]' value='".$s."'>";
                      }
                      if(!empty($id_kadar)){
                        foreach($id_kadar as $k ) echo "<input type='hidden' name='id_kadar[]' value='".$k."'>";
                      }
                    ?>
                  <input type="hidden" name="method" value="<?php echo $method ?>">
                  <input type="hidden" name="deret_af" value="1">
                  <input type="hidden" name="nomor_batch" value="<?php echo $this->session->userdata('nomor_batch'); ?>">
                  <!-- <button type="button" class="btn btn-primary" onclick="$('#form2').submit();">Tambah Data</button> -->
                  <button type="button" class="btn btn-primary" onclick="add_deret()">Add Data</button>
                  <input id="t_deret" type="number">
                </form>
              <?php } ?>
              <?php if(!empty($method) && $method != 'edit') {?>
                <form method="post" id="form1" action="<?php echo site_url('sampel/analis/form_uji/af'); ?>">
                  <input type="hidden" name = "nomor_batch" value="<?php echo $nomor_batch; ?>">
                  <input type="hidden" name = "method" value="form_deret">
                  <div class="btn-group">
                    <a href="<?php echo site_url('sampel/analis/batch/af'); ?>" class="btn btn-primary btn-md">Kembali</a>
                    <a href="<?php echo site_url('sampel/analis/kontrol_sampel/af?nomor_batch='.$nomor_batch.'&method=kontrol_sampel'); ?>" class="btn btn-warning btn-md">Kontrol Sampel</a>
                    <button class="btn btn-warning active" onclick="$('#form1').submit();">Deret Standart Aflatoksin Total</button>
                  </div>
                </form>
              <?php } ?>
              <hr>
            </div>

            <form class="form-horizontal" id="form1" method="post">
            <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(isset($data[0]['abs'])){
                    $slope = 0;
                    $intercept = 0;
                    $range = 0; 

                    $a=0;
                    foreach($data as $o){
                      $ks[]=$k_s = (float)$o['level_standart'];
                      $abs = (float)($o['abs'] == 0 ? 0.000001 : $o['abs']);
                      $abs0 = (float)($data[0]['abs'] == 0 ? 0.000001 : $data[0]['abs']);
                      $cb[] = $k_b = $abs/$abs0;

                      if($k_s != 0) {
                        $db[] = $c_d = $k_b/(1-$k_b);
                        $dc[] = $k_c = log10($k_s);
                        $dd[] = $k_d = log10($c_d);

                        $x[] = $v = $k_c;
                        $y[] = $z = $k_d;
                        $xy[] = $v*$z;
                        $x2[] = pow($v, 2);
                      }
                      $a++;
                    }

                    if(!empty($x[1])){
                      $tx = array_sum($x);
                      $ty = array_sum($y);
                      $txy = array_sum($xy);
                      $tx2 = array_sum($x2);

                      $rx = $tx/count($x);
                      $ry = $ty/count($y);
                      
                      $ntxy = count($x)*$txy;
                      $txty = ($tx*$ty);
                      $ntx2 = count($x)*$tx2;
                      $ttx2 = pow($tx, 2);

                      $ttx22 = pow($tx, 2);
                      $txtxy = ($tx*$txy);

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

                      for($i=0;$i<count($x);$i++){
                        $h1 = ($x[$i]-$rx);
                        $h2 = ($y[$i]-$ry);
                        $xx2[] = pow($h1, 2);
                        $yy2[] = pow($h2, 2);
                      } 

                      $cxx2 = array_sum($xx2);
                      $cyy2 = array_sum($yy2);

                      $ax = sqrt((1/(COUNT($x)-1))*($cxx2));
                      $ay = sqrt((1/(COUNT($y)-1))*($cyy2));

                      for($i=0;$i<count($x);$i++){
                        $xxax[] = $p1 = (($x[$i]-$rx)/$ax);
                        $yyay[] = $p2 = (($y[$i]-$ry)/$ay);
                        $xxayy[] = ($p1*$p2);
                      }

                      $cxxayy = array_sum($xxayy);

                      $range = ((1/((count($x))-1))*$cxxayy);
                      $range = round($range, 4);
                    }
                  ?>

                  <?php $i=1; foreach($data as $r) { ?>
                    <?php 
                      if($r['level_standart'] != 0){
                        $kg =((float)$r['abs']/$abs0);
                        $kh2 = ($kg/(1-$kg));

                        $kh = (!is_infinite($kh2) || !is_nan($kh2) ? (log10($kh2)) : 0);
                        $ki = (is_nan($kh) || is_nan($intercept) || is_nan($slope) ? 0 : (float)pow(10,(($kh-$intercept)/$slope)));

                        $dilution = 1;
                      }
                      $k_b = doubleval($r['abs']/$data[0]['abs']);
                      $k_c = log10($r['level_standart']);
                      $k_d = $k_b == 1 ? 0 : log10(($k_b/(1-$k_b)));

                    ?>
                    <tr>
                      <td><?php echo $this->uri->segment(5) + $i++; ?></td>
                      <td><?php echo round($r['level_standart'], 0) ?></td>
                      <td><?php echo $r['abs'] ?></td>
                      <td><?php echo $r['intercept']; ?></td>
                      <td><?php echo $r['slope']; ?></td>
                      <td><?php echo $r['total_af']; ?></td>
                    </tr>
                  <?php } }?>
                </tbody>
              </table>

            </div>
            <div class="panel-footer">
              <?php
                  if(!empty($id_sampel)){
                    foreach($id_sampel as $s ) echo "<input type='hidden' name='id_sampel[]' value='".$s."'>";
                  }
                  if(!empty($id_kadar)){
                    foreach($id_kadar as $k ) echo "<input type='hidden' name='id_kadar[]' value='".$k."'>";
                  }
                ?>
              <input type="hidden" name="method" value="<?php echo $method ?>">
              <input type="hidden" name="uji_af" value="1">
              <input type="hidden" name="nomor_batch" value="<?php echo $this->session->userdata('nomor_batch'); ?>">
              <?php if(!empty($method) && $method == 'edit' && empty($data[0])) { ?>
                <button type="button" class="btn btn-primary" onclick="$('#form1').submit();">Lanjut ke Uji Aflatoksin Total</button>
              <?php } ?>
            </div>
            </form>
        </div>
    </div>
</div>

<?php if(!empty($method) && $method != 'edit') { ?>
<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"><?php echo 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 = <?php echo $grafik[0]['slope'].'x '.(strpos('|'.$grafik[0]['intercept'], '-')  == false ? '+' : '').$grafik[0]['intercept']; ?></label>
                          <br>
                          <label> r = <?php echo number_format(round($grafik[0]['d_range'], 4), 4);?></label>
                        </div>
</div>
<?php } ?>
<?php if(!empty($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: [<?php echo $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 } ?>

<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);
    }


    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));

        $(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);
        }
    }

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