<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title></title>

<!-- Content Header (Page header) -->
<div class="content-header ">
  <div class="container-fluid">
    <div class="row mb-2">
      <div class="col-sm-12">
        <!-- <h1 class="m-0 text-dark">Judul Atas</h1> -->
      </div><!-- /.col -->
    </div><!-- /.row -->
  </div><!-- /.container-fluid -->
</div>
<!-- /.content-header -->

<!-- Main content -->
    <section class="content">
      <div class="container-fluid">
        <div class="row">
          <div class="col-12">
            <!-- Default box -->
            <div class="card">
              <div class="card-header bg-info">
                <h3 class="card-title ">Edit Angsuran</h3>
                <div class="card-tools">
                  <button type="button" class="btn btn-tool" data-card-widget="collapse" title="Collapse">
                    <i class="fas fa-minus"></i>
                  </button>
                  <button type="button" class="btn btn-tool" data-card-widget="remove" title="Remove">
                    <i class="fas fa-times"></i>
                  </button>
                </div>
              </div>
              <!-- /.card-header -->
        <div class="card-body">

         

<script language="javascript" type="text/javascript">
/*https://www.diskusiweb.com/discussion/31709/entry-pake-key-enter-kok-gak-berhasil*/
var fromEnter = false ;
function changeFocus (event,nextFocus)
{
if (event.keyCode==13)
{
var obj = document.getElementsByName( nextFocus )[ 0 ] ;
if (obj)
obj.focus() ;
}
fromEnter = true ;
}
function checkSubmit ()
{
fromEnter = !fromEnter ;
return fromEnter ;
}
</script>
    
    

                  <?php
                  error_reporting(E_ALL^(E_NOTICE|E_WARNING));
                  ini_set('display_errors',1);
                  error_reporting(0);
                 include 'koneksi.php'; 

         if(isset($_POST['no_faktur'])){                  
          $no_faktur=$_POST['no_faktur'];
          $query1 = "SELECT rekening,no_bukti,tgl,pokok as byrpokok,margin AS byrmargin,plafond,keterangan,tglsystem AS tglsystem  FROM angsuran WHERE no_bukti='".$no_faktur."'  "; 
            $hasil2 = mysqli_query($koneksi, $query1);
            $reg = mysqli_fetch_assoc($hasil2); 

               }

           $byrpokok= $reg['byrpokok'];
           $byrmargin= $reg['byrmargin'];
           $jumlah = $byrpokok+$byrmargin;

          function Rp($angka) { 
          $jadi = number_format($angka,2,'.',',');
          return $jadi;
          }

           ?>

            <form action="" method="POST">
          <div class="row">
            <div class="col-sm-6">
              
             <div class="form-group row ">
              <label for="nama" class=" col-sm-4">No Faktur </label>
        
              <input type="text" name="no_faktur" id="no_faktur" class="form-control col-sm-6" value="<?php echo $reg['no_bukti'];?>" onchange="this.form.submit();" onKeyDown="changeFocus(event,'tgl')"/>
              
                    
                 <button type="submit" class="  btn btn-info"  ><i class="fas fa-search"></i></button>
               </div>
              </form>

              

              <form name="myform" action="" method="POST"  class="form-simpanangsuran" id="form-simpanangsuran">

                
              <input type="hidden" name="no_faktur" id="no_faktur"  class="form-control col-sm-7" value="<?php echo  $_POST['no_faktur'];?>"/>
              <input type="hidden" name="tglsystem" id="tglsystem"  class="form-control col-sm-7" value="<?php echo  $reg['tglsystem'];?>"/>


              <div class="form-group row">
                <label for="nama" class="col-sm-4">Tanggal</label>
                <input type="text" name="tgl" id="tgl" class="tgl form-control col-sm-7" value="<?php echo date('d-m-Y',strtotime($reg['tgl']));?>" max="<?=date('Y-m-d')?>" onKeyDown="changeFocus(event,'rekening')" autofocus />
              </div>

              <div class="form-group row">
                <label for="nama" class="col-sm-4">Rekening</label>
                <input type="text" name="rekening" id="rekening"  class="form-control col-sm-7" value="<?php echo  $reg['rekening'];?>" onKeyDown="changeFocus(event,'pokok')"/>
              </div>

        
              
              <div class="form-group row">
                <label for="nama" class="col-sm-4">Pokok</label>
                <input type="text" name="pokok" id="pokok" class="form-control col-sm-7" value="<?php echo Rp($byrpokok);?>" onKeyDown="changeFocus(event,'margin')"/> 
              </div>             

            
      
        </div>


        <div class="col-sm-6">
        <div class="form-group row">
                <label for="nama" class="col-sm-3">Ujroh</label>
                <input type="text" name="margin" id="margin" class="form-control col-sm-8" value="<?php echo Rp($byrmargin);?>" onKeyDown="changeFocus(event,'jumlah')"/>      
            </div>   
            
              <div class="form-group row">
                <label for="nama" class="col-sm-3">Jumlah</label>
                <input type="text" name="jumlah" id="jumlah" class="form-control col-sm-8" value="<?php echo Rp($jumlah);?>" onKeyDown="changeFocus(event,'keterangan')"/>
            </div>
              
              <div class="form-group row">
                <label for="nama" class="col-sm-3">Keterangan</label>
                <input type="text" name="keterangan" id="keterangan" class="form-control col-sm-8" required="" value="<?php echo $reg['keterangan'];?>"  onKeyDown="changeFocus(event,'simpanangsuran')"/>
            </div>
            <?php
            $query1 = "SELECT a.plafond-SUM(b.pokok) AS bakidebet,(a.plafond*a.margin/100*a.jangkawaktu-SUM(b.margin)) AS sisamargin,sum(b.pokok)as pokokdibyar,(a.plafond*a.margin/100*a.jangkawaktu) AS totalmargin,sum(b.margin) AS margindibayar FROM pinjaman a left join angsuran b on a.rekening=b.rekening WHERE b.rekening='".$reg['rekening']."' AND b.no_bukti !='".$reg['no_bukti']."' GROUP BY a.rekening "; 
              $hasil2 = mysqli_query($koneksi, $query1);
              $baki = mysqli_fetch_assoc($hasil2); 
                ?>
            <div class="form-group row">
                <label for="nama" class="col-sm-3">Bakidebet</label>
            <input type="text" name="bakidebet" readonly="bakidebet" id="bakidebet" class="form-control col-sm-8" required="" value="<?php echo Rp($baki['bakidebet']);?>" />
          </div>


         </div> 
            
            <!-- /.card-body -->
            <div class="card-footer ">
              <input type="button" name="simpanangsuran" id="simpanangsuran" 
              class="btn btn-primary"  value="Simpan" onclick='document.geElementById("myform").submit()'>
              <a href="home.php?home=<?php echo md5("angsuran");?>" id="batal" class="btn btn-secondary">
                Tambah
              </a>
              <?php if($_SESSION['level']<0){ ?>
              <a href="home.php?home=<?php echo md5("editangsuran");?>" class="btn btn-warning">
                Edit
              </a>
             <a href="home.php?home=<?php echo md5("deleteangsuran");?>" class="btn btn-danger">
                Hapus
              </a>
            <?php }?>
            </div>
           
          </form>
           
        </div>
        <!-- /.card -->
      </div>
      <!--/.col (left) -->
    </div>
    <!-- /.row -->
  </div><!-- /.container-fluid -->
</section>
<!-- /.content -->


<!-- <style>
input:out-of-range {
  border:2px solid red;
}
</style> -->
<!-- <script type="text/javascript" src="jquery.js"></script>  -->
<script type="text/javascript">

 $(document).ready(function(){
    $("#simpanangsuran").click(function(){
      var data       = $('#form-simpanangsuran').serialize(); 
      var rekening   = $('#rekening');
      var no_faktur   = $('#no_faktur');
      var tgl        = $('#tgl').val()
      var pokok      = $('#pokok').val().replace(/,(?=\d{3})/g, '');
      var margin     = $('#margin').val();
      var keterangan = $('#keterangan').val();
      var bakidebet  = $('#bakidebet').val().replace(/,(?=\d{3})/g, '');
      

      if(no_faktur== "0"|| tgl=="0" ||  keterangan=="0"){ 
Swal.fire({
  icon: 'error',
  title: 'Hati-hati...',
  text: 'Data masih ada yg belum diisi!',
  footer: '<a href="">Anda Perlu teliti sedikit lagi?</a>'
});
      
    } else if(no_faktur== ""|| tgl==""|| keterangan==""){ 

      Swal.fire(
  'Data Masih ada yang Kosong !',
  'Mohon data dilengkapi dlu !',
  'question'
);
    }else if(parseInt(pokok)>parseInt(bakidebet)){
      Swal.fire(
  'Pembayaran Pokok Kelebihan !',
  'Mohon dilakukan Pengurangan !',
  'question'
);
               
    }else{

      $.ajax({
        type: 'POST',
        url: 'simpan/simpan_angsuran_edit.php',
        data: data,
        /*data: {rekening:rekening,tgl:tgl,pokok:pokok,margin:margin,keterangan:keterangan,bakidebet:bakidebet},*/
        success: function(data) {
         console.log(data)
         let timerInterval
Swal.fire({
  title: 'Alhamdulillah..! Data Tersimpan.',
  html: 'Silahkan Cek <b></b> Sendiri.',
  timer: 3000,
  timerProgressBar: true,
  didOpen: () => {
    Swal.showLoading()
    const b = Swal.getHtmlContainer().querySelector('b')
    timerInterval = setInterval(() => {
      b.textContent = Swal.getTimerLeft()
    }, 100)
  },
  willClose: () => {
    clearInterval(timerInterval)
  }
}).then((result) => {
  /* Read more about handling dismissals below */
  if (result.dismiss === Swal.DismissReason.timer) {
    console.log('I was closed by the timer')
  }
})

         /*alert("Data Sukses Disimpan");
         window.location.href='home.php?home=registrasi'; */
        },
        error: function(error){
          console.log(`error ${error}`)
         
        }
      });
    }
    });
  });
  
</script>

<script type="text/javascript">
  // untuk format koma
  //https://cobangoding.com/tips-dan-trick/memberi-titik-otomatis-pada-angka-saat-menginput-dengan-javascript/#comment-757
  //https://codepen.io/cobangoding/pen/QWOoLXN
 $('#pokok').on('keyup',function(){
  var angka = $(this).val(); 
  var hasilAngka = formatRibuan(angka);
  $(this).val(hasilAngka);
  });
 $('#margin').on('keyup',function(){
  var angka = $(this).val(); 
  var hasilAngka = formatRibuan(angka);
  $(this).val(hasilAngka);
  });

  function formatRibuan(angka) {
  var number_string = angka.replace(/[^\.\d]/g, '').toString(),
    split = number_string.split('.'),
    sisa = split[0].length % 3,
    angka_hasil = split[0].substr(0, sisa),
    ribuan = split[0].substr(sisa).match(/\d{3}/gi);

  // tambahkan titik jika yang di input sudah menjadi angka ribuan
  if (ribuan) {
    separator = sisa ? ',' : '';
    angka_hasil += separator + ribuan.join(',');
  }

  angka_hasil =
    split[1] != undefined ? angka_hasil + '.' + split[1] : angka_hasil;
  return angka_hasil;
}
</script>  
 
</head>
</html>