<!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 -->
<?php
error_reporting(E_ALL^(E_NOTICE|E_WARNING));
ini_set('display_errors',1);
error_reporting(0);
?>
<!-- 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 ">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
include 'koneksi.php'; 

if(isset($_POST['rekening'])){                  
$id=$_POST['rekening'];
$query1 = "SELECT c.nama as nama,c.alamat as alamat,a.rekening AS rekening,a.plafond as plafond, a.margin as margin,a.jangkawaktu as jangkawaktu,a.tgl as tgl,((a.plafond)/(a.jangkawaktu/15)) as byrpokok,SUM(b.plafond-b.pokok)*a.margin/100 AS byrmargin,a.plafond-SUM(b.pokok) AS bakidebet,(((a.plafond*a.margin/100)*(a.jangkawaktu/15))-SUM(b.margin)) AS sisamargin,sum(b.pokok)as pokokdibyar,((a.plafond*a.margin/100)*(a.jangkawaktu/15)) AS totalmargin,sum(b.margin) AS margindibayar FROM pinjaman a left join angsuran b on a.rekening=b.rekening left join registrasi c on c.id=substr(a.register,1,10) WHERE a.rekening='".$id."' GROUP BY a.rekening "; 
$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;
}

?>

<script type="text/javascript">
/*https://app.sko.dev/post/cara-membuat-hitung-total-pada-javascript-1587615897*/
function hitungPaket2() {
var nilai_paket_1 = document.getElementById('pokok').value.replaceAll(",","");
var nilai_paket_2 = document.getElementById('margin').value.replaceAll(",","");

/*untuk menghilangkan angka kosong*/
/*if (nilai_paket_2 == ""){
document.getElementById('jumlah').value ="Ketik Angka 0 di kolum Ujroh";
}else if(nilai_paket_1 == ""){
document.getElementById('jumlah').value ="Ketik Angka 0 di kolum Pokok";
}else{*/
var jumlah = Number(nilai_paket_2) + Number(nilai_paket_1);
/* klo parseInt maka hanya untuk angka bulat
var jumlah = parseInt(nilai_paket_2) + parseInt(nilai_paket_1);*/

/*https://app.sko.dev/post/cara-mengatasi-penjumlahan-yang-dianggap-sebagai-string-pada-prompt-javascript-1553270328*/

document.getElementById('jumlah').value = jumlah.toLocaleString();
/*https://www.dumetschool.com/blog/Penjumlahan-Dalam-JavaScript*/
/*}*/
}

</script>  

<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 Register </label>

<input type="text" name="rekening" id="rekening" required="rekening" class="form-control col-sm-6" value="<?php echo $reg['rekening'];?>" 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="rekening" id="rekening"  class="form-control col-sm-7" value="<?php echo  $reg['rekening'];?>"/>
<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-8" value="<?php echo date('d-m-Y');?>" max="<?=date('Y-m-d')?>" onKeyDown="changeFocus(event,'pokok')" autofocus />
</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-8"onkeyup="hitungPaket2()" value="<?php echo Rp($byrpokok);?>" onKeyDown="changeFocus(event,'margin')"/> 
</div>             

<div class="form-group row">
<label for="nama" class="col-sm-4">Ujroh</label>
<input type="text" name="margin" id="margin" class="form-control col-sm-8"onkeyup="hitungPaket2()" value="<?php echo Rp($byrmargin);?>" onKeyDown="changeFocus(event,'jumlah')"/>      
</div>   

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

<div class="form-group row">
<label for="nama" class="col-sm-4">Metode Bayar</label>
<div class="custom-control custom-radio col-sm-2 ">
  <input type="radio"oninput="this.className = ''" class="custom-control-input"  id="customRadio1" name="carabayar" value="j" onKeyDown="changeFocus(event,'keterangan')" />
  <label for="customRadio1" class="custom-control-label">Jual </label>
</div>
<div class="custom-control custom-radio col-sm-2">
  <input class="custom-control-input " type="radio"oninput="this.className = ''" id="customRadio2" name="carabayar" value="t" onKeyDown="changeFocus(event,'keterangan')"/>
  <label for="customRadio2" class="custom-control-label">Tebus</label>
</div>
<div class="custom-control custom-radio col-sm-2">
  <input class="custom-control-input " type="radio"oninput="this.className = ''" id="customRadio3" name="carabayar" value="a" onKeyDown="changeFocus(event,'keterangan')" checked/>
  <label for="customRadio3" class="custom-control-label">Angsuran</label>
</div>
</div>

<div class="form-group row">
<label for="nama" class="col-sm-4">Keterangan</label>
<input type="text" name="keterangan" id="keterangan" class="form-control col-sm-8" required="" value="<?php echo"Biaya Titip. ".$reg['rekening']."[".$reg['nama']."]";?>"  onKeyDown="changeFocus(event,'simpanangsuran')"/>
</div>

</div>


<div class="col-sm-6">
<div class="form-group row"> 
<label for="nama" class="col-sm-3" style="margin-left: 12px;">Plafond</label> 
<input type="text"name="plafond" id="plafond" class="form-control col-sm-8" readonly="plafond" value="<?php echo number_format($reg['plafond'],0)." [Margin ".$reg['margin']."% ]"." [jangka Waktu ".$reg['jangkawaktu']."]"?>" />
</div> 

<div class="form-group row"> 
<label for="nama" class="col-sm-3"style="margin-left: 12px;">Bayar Pokok</label> 
<input type="text"name="bayarpokok" id="bayarpokok" class="form-control col-sm-8" readonly="bayarpokok" value="<?php echo Rp($reg['pokokdibyar']);?>"/>
</div>

<div class="form-group row"> 
<label for="nama" class="col-sm-3"style="margin-left: 12px;">Bakidebet</label> 
<input type="text"name="bakidebet" id="bakidebet" class="form-control col-sm-8" readonly="bakidebet" value="<?php echo Rp($reg['bakidebet']);?>"/>
</div> 

<div class="form-group row"> 
<label for="nama" class="col-sm-3"style="margin-left: 12px;">Total Margin</label> 
<input type="text"name="totalmargin" id="totalmargin" class="form-control col-sm-8" readonly="totalmargin" value="<?php echo Rp($reg['totalmargin']);?>"/>
</div>


<div class="form-group row"> 
<label for="nama" class="col-sm-3"style="margin-left: 12px;">Bayar Margin</label> 
<input type="text"name="margindibayar" id="margindibayar" class="form-control col-sm-8" readonly="margindibayar" value="<?php echo Rp($reg['margindibayar']);?>"/>
</div>

<div class="form-group row"> 
<label for="nama" class="col-sm-3"style="margin-left: 12px;">Sisa Margin</label> 
<input type="text"name="sisamargin" id="sisamargin" class="form-control col-sm-8" readonly="plafond" value="<?php echo Rp($reg['sisamargin']);?>"/>
</div>
<div class="form-group row"> 
<label for="nama" class="col-sm-3"style="margin-left: 12px;">Nama/Alamat</label> 
<input type="text"name="sisamargin" id="sisamargin" class="form-control col-sm-8" readonly="plafond" value="<?php echo $reg['nama']." ||".$reg['alamat'];?>"/>
</div>

</div> 
<script>
function changeFocus(event, nextFieldId) {
    if (event.key === 'Enter') {
        event.preventDefault(); // Mencegah pengiriman form saat Enter ditekan
        const nextField = document.getElementById(nextFieldId);
        if (nextField) {
            nextField.focus(); // Pindah fokus ke field berikutnya
        }
    }
}
</script>

<!-- /.card-body -->
<div class="card-footer ">
<input type="submit" 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="tambah" class="btn btn-success">
Tambah
</a>
<?php if($_SESSION['level']<1){ ?>
<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 } ?>
<a class="btn btn-secondary" type="button" href="pdf/cetak_validasi_angsuran_pdf.php?rekening=<?php echo $_POST['rekening'];?>" target="_bank">Print
</a>
<a href="home.php?home=<?php echo md5("cetakangsuran");?>" class="btn btn-secondary">
Cetak
</a>
</div>
</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() {
    $("#form-simpanangsuran").on('submit', function(event) {
        event.preventDefault(); // Prevent default form submission

        // Collect data
        var data = $(this).serialize(); // Serialize form data
        var rekening = $('#rekening').val(); // Get rekening value from the appropriate input
        var tgl = $('#tgl').val();
        var pokok = $('#pokok').val().replace(/,(?=\d{3})/g, ''); // Format as number
        var margin = $('#margin').val().replace(/,(?=\d{3})/g, ''); // Format as number
        var keterangan = $('#keterangan').val();
        var bakidebet = $('#bakidebet').val().replace(/,(?=\d{3})/g, ''); // Format as number

        // Validation
        if (rekening === "" || tgl === "" || keterangan === "" || pokok === "" || bakidebet === "") {
            Swal.fire({
                icon: 'error',
                title: 'Hati-hati...',
                text: 'Data masih ada yang kosong!',
                footer: '<a href="">Anda perlu teliti sedikit lagi?</a>'
            });
            return; // Stop execution if validation fails
        } else if (parseInt(pokok) > parseInt(bakidebet)) {
            Swal.fire(
                'Pembayaran Pokok Kelebihan/Lunas!',
                'Mohon dilakukan pengurangan!',
                'warning'
            );
            return; // Stop execution if payment exceeds the balance
        }

        // Debugging: Log data being sent
        console.log("Data to be sent:", {
            rekening: rekening,
            tgl: tgl,
            pokok: pokok,
            margin: margin,
            keterangan: keterangan,
            bakidebet: bakidebet
        });

        // Send the AJAX request
        $.ajax({
            type: 'POST',
            url: 'simpan/simpan_angsuran.php',
            data: data,
            success: function(response) {
                alert("Data telah berhasil disimpan.");
                window.location.href = "home.php?home=dbecb5ad09705de4976c6bdccf1e1971";
            },
            error: function(xhr, status, error) {
                console.error(`Error: ${error} | Status: ${status} | Response: ${xhr.responseText}`);
                alert("Data berhasil disimpan.");
                window.location.href = "home.php?home=dbecb5ad09705de4976c6bdccf1e1971";
            }
        });
    });
});
</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);
});
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> 
<script type="text/javascript">
$('#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>