<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;
  }
  .dt-wt {width: 100px;}
</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">Deret&nbsp;std&nbsp;(ppm)</th>
                        <th rowspan="2">Volume pipet std P<br>(ml)</th>
                        <th rowspan="2">Labu ukur std P<br>(ml)</th>
                        <th rowspan="2">Std P 100 ppm<br>(ml)</th>
                        <th colspan="4">FIXED</th>
                      </tr>
                      <tr class="inverse">
                        <th>Abs<br>(Y)</th>
                        <th>Intercept<br>(a)</th>
                        <th>Slope<br>(b)</th>
                        <th>C std P (ppm)</th>
                      </tr>
                    </thead>
                    <tbody id="t_body">
                      <tr id="tb_deret"></tr>
                      <?php if(!empty($data)) { ?>
                      <?php $i=1; foreach($data as $r) { ?>
                        <tr>
                          <td><?php echo $this->uri->segment(5) + $i++; ?></td>
                          <td><?php echo number_format($r['deret_std_p'],0) ?></td>
                          <td><?php echo number_format($r['volume_pipet_std_p'],($r['volume_pipet_std_p'] == '0.00')? 0:1); ?></td>
                          <td><?php echo $r['labu_ukur_std_p'] ?></td>
                          <td><?php echo $r['std_p_100_ppm'] ?></td>
                          <td><?php echo $r['abs'] ?></td>
                          <td><?php echo $r['intercept'] ?></td>
                          <td><?php echo $r['slope'] ?></td>
                          <td><?php echo $r['c_std_p'] ?></td>
                        </tr>
                      <?php } }?>
                    </tbody>
                  </table>

                </div>
                <div class="panel-footer">
                    <?php if(empty($is_grafik)) : ?>
                        <input type="hidden" name="nomor_batch[]" value="<?= $nomor_batch; ?>">
                        <button type="button" class="btn btn-primary" onclick="$('#form1').submit();">Lanjut ke Uji Fosfor</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> Grafik Deret Standar Fosfor
                                <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 round($grafik[0]['d_range'], 4);?></label>
                        </div>
</div>
<?php } ?>

<?php if(!empty($is_grafik)) : ?>
<?php $a=array(); foreach($grafik as $r) {$a[] = $r['deret_std_p'];}?>
<?php $b=array(); foreach($grafik as $r) {$b[] = $r['abs'];}?>
<?php 
  $n = '';
  for($i=0;$i<=(int)(end($a)+2);$i+=2){
    if(in_array($i,$a)){
      for($c=0;$c<count($a);$c++){
        if($i == $a[$c]){
          $n .= $b[$c].',';
        }
      }
    }else {
      $n .= 'null,';
    }
  }
?>

<script>
new Chart(document.getElementById("line-chart"), {
  type: 'line',
  data: {
    labels: [<?php for($i=0; $i<=(int)(end($a)+2);$i+=2) {echo $i.',';}?>],
    datasets: [{
        data: [<?php echo $n; ?>],
        label: '',//"Data Uji Sampel",
    borderColor: "#00e6e6",
        fill: true
      }
    ]
  },
  options: {
    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: {
                autoSkip: false,
                //maxRotation: 90
            },
					display: true,
					scaleLabel: {
							display: true,
							labelString: ''//'Bulan'
					}
                }],
                yAxes: [{
						display: true,
						scaleLabel: {
							display: true,
							labelString: ''//'Jumlah Sampel'
						},
						ticks: {
							min: 0.000,
							max: 1.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 = [];

  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;

    x[z] = parseFloat($('#deret_std_fosfor'+z).val());
    y[z] = parseFloat($('#abs'+z).val());

    if(isNaN(x[z])) x[z] = 0;
    if(isNaN(y[z])) y[z] = 0;

    for (var i = 0; i < x.length; i++) {
        xy[i] = x[i] * y[i];
        x2[i] = Math.pow(x[i], 2);
    }

    for (var i = 0; i < x.length; i++) {
        ty += y[i];
        tx += x[i];
        txy += xy[i];
        tx2 += x2[i];
    }

    var rx = tx / x.length;
    var ry = ty / y.length;

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

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

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

    for(i=0;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/(x.length-1))*(cxx2));
    var ay = Math.sqrt((1/(y.length-1))*(cyy2));

    for(i=0;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 c_std = (y[i]-intercept)/slope;
      $('#c_std'+i).val(c_std.toFixed(3));
    }

    var range = ((1/((x.length)-1))*cxxayy);

    console.log(range);

    $('.intercept').val(intercept);
    $('.slope').val(slope); 
    $('.d_range').val(range.toFixed(4));   

  }

  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 text-center deret_std_fosfor' name='deret_level[]' required></td>\n\
          <td><input class='dt-wt text-center volume_pipet_std_p' name='volume_pipet_std_p[]' required></td>\n\
          <td><input class='dt-wt text-center labu_ukur_std_p' name='labu_ukur_std_p[]' required></td>\n\
          <td><input class='dt-wt text-center std_p_100_ppm' name='std_p_100_ppm[]' required></td>\n\
          <td><input class='dt-wt text-center abs' name='abs[]' required></td>\n\
          <td><input class='dt-wt text-center intercept' name='intercept[]'></td>\n\
          <td>\n\
            <input class='dt-wt text-center slope' name='slope[]'>\n\
            <input class='dt-wt text-center d_range' type='hidden' name='d_range[]'>\n\
          </td>\n\
          <td><input class='dt-wt text-center c_std' name='c_std[]'></td>\n\
        </tr>\n\
      ";
      $("#tb_deret").before(row);
    }


    var deret = [0,2,4,6,8,10];
    var volume_pipet_std_p = [0,0.5,1,1.5,2,2.5];
    var labu_ukur_std_p = [25,25,25,25,25,25];
    var std_p_100_ppm = [100,100,100,100,100,100];
    var abs2 = [0.001,0.168,0.342,0.511,0.687,0.855];

    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_fosfor').first().attr('onkeyup', 'cek_rumus('+(i)+')');
        $(tr[i]).find('.deret_std_fosfor').first().attr('id', 'deret_std_fosfor'+(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('.abs').first().val(parseFloat(abs2[i]));
        $(tr[i]).find('.deret_std_fosfor').first().val(parseFloat(deret[i]));
        $(tr[i]).find('.volume_pipet_std_p').first().val(parseFloat(volume_pipet_std_p[i]));
        $(tr[i]).find('.labu_ukur_std_p').first().val(parseFloat(labu_ukur_std_p[i]));
        $(tr[i]).find('.std_p_100_ppm').first().val(parseFloat(std_p_100_ppm[i]));

        if(i < 6) {
        cek_rumus(i);
        }
    }

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