<!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 ">Realisasi Gadai</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">

          <!-- Croping Photo -->

<!-- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/css/bootstrap.min.css">
 -->  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/croppie/2.6.2/croppie.min.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/croppie/2.6.2/croppie.js"></script>

<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>  
    
<!-- <link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet"> -->


       <?php
                  error_reporting(E_ALL^(E_NOTICE|E_WARNING));
                  ini_set('display_errors',1);
                  error_reporting(0);
                 include 'koneksi.php'; 
                      if(isset($_POST['r_register'])){                  
                      $id=$_POST["r_register"];
                   
                        $query4 = "SELECT register, COUNT(register) as jml FROM pinjaman where register='".$id."' ";
                         
                        $hasil1 = mysqli_query($koneksi, $query4);
                        $reg = mysqli_fetch_assoc($hasil1);       
                         }
                         ?>

              

            <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="r_register" id="r_register" placeholder="Ketik Register" class="form-control col-sm-6" value="<?php if(isset($_POST['r_register'])){ echo  $_POST['r_register'].".".sprintf("%02d",$reg['jml']+1);}?>" onchange="this.form.submit();" onKeyDown="changeFocus(event,'tgl')"/>
              
                    
                <button type="submit" class="  btn btn-info"  ><i class="fas fa-search"></i></button>
               </div>
            </form>
                    <?php

                    if(isset($_POST['r_register'])){                  
                      $id=$_POST["r_register"]; 
                       
                    ?> 
        

          <form name="form-simpanpencairan" action=".../../simpan/simpan_pinjaman.php" method="POST" class="form-simpanpencairan" id="form-simpanpencairan" onsubmit="return validateForm();" >
              <input type="hidden" name="register" id="register"class="form-control col-sm-6" value="<?php echo $_POST['r_register'];?>">
              
              <input type="hidden" name="rekening" id="rekening" class="form-control col-sm-7" value="<?php echo  $_POST['r_register'].".".sprintf("%02d",$reg['jml']+1) ?>" readonly="rekening"/>
              

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

              <div class="form-group row">
                <label for="nama" class="col-sm-4">Plafond</label>
                <input type="text" name="plafond" id="plafond"  class="form-control col-sm-7" onKeyDown="changeFocus(event,'jcair')"/> 
              </div>

              <div class="form-group row">
                <label for="nama" class="col-sm-4">Jenis Cair</label>
                <div class="custom-control custom-radio col-sm-3 ">
                          <input type="radio" class="custom-control-input"  id="customRadio1" name="jcair" value="B" onKeyDown="changeFocus(event,'pbarang')"  /> <!-- checked -->
                          <label for="customRadio1" class="custom-control-label">Baru </label>
                </div>
                <div class="custom-control custom-radio col-sm-3">
                          <input class="custom-control-input " type="radio" id="customRadio2" name="jcair" value="P" onKeyDown="changeFocus(event,'pbarang')" />
                          <label for="customRadio2" class="custom-control-label">Perpanjangan</label>
                 </div>
              </div>
               

            <div class="form-group row">
                <label for="nama" class="col-sm-4">Pengajuan Barang</label>
                <input type="text" name="pbarang" id="pbarang" class="form-control col-sm-7" onkeyup="this.value = this.value.toUpperCase()" onKeyDown="changeFocus(event,'jbarang')"/>

            </div>
            
            <div class="form-group row">
                <label for="nama" class="col-sm-4">Jenis Barang</label>
                <div class="custom-control custom-radio col-sm-3 ">
                          <input class="custom-control-input " type="radio"id="customRadio3" name="jbarang" value="Elektronik" onKeyDown="changeFocus(event,'kelengkapan')" />
                          <label for="customRadio3" class="custom-control-label">Elektronik </label>
                        </div>
                        <div class="custom-control custom-radio col-sm-3">
                          <input class="custom-control-input " type="radio" id="customRadio4" name="jbarang" value="Kendaraan" onKeyDown="changeFocus(event,'kelengkapan')" />
                          <label for="customRadio4" class="custom-control-label">Kendaraan</label>
                 </div>
              </div>
 
            <div class="form-group row">
                <label for="nama" class="col-sm-4">Kelengkapan</label>
                <select id="kelengkapan" name="kelengkapan" class="form-control col-sm-7 select2" onKeyDown="changeFocus(event,'jaminan')" >
                    <!--<option selected="selected">UNIT CHAS KOTAK</option>
                       -->
                    <option value="" >PILIH----</option>
                    <option value="UNIT KOTAK">UNIT KOTAK</option>
                    <option value="UNIT CHAS">UNIT CHAS</option>
                    <option value="UNIT CHAS KOTAK">UNIT CHAS KOTAK</option>
                    <option value="UNIT CHAS TAS">UNIT CHAS TAS</option>
                    <option value="UNIT KOTAK REMOT">UNIT KOTAK REMOT</option>
                    <option value="UNIT REMOT">UNIT REMOT</option>
                    <option value="UNIT BPKB STNK">UNIT BPKB STNK</option>
                    <option value="STNK KTP">STNK KTP</option>
                  </select>
            </div>
            <div class="form-group row">
                <label for="nama" class="col-sm-4">Jaminan</label>
                <select id="jaminan" name="jaminan" class="form-control col-sm-7 select2" onKeyDown="changeFocus(event,'jwaktu')" >
                    <!-- <option selected="selected">TV</option> -->
                    <option value="">PILIH---</option>
                    <option value="TV">TV</option>
                    <option value="HP">HP</option>
                    <option value="LAPTOP">LAPTOP</option>
                    <option value="SPEKER AKTOR">SPEKER AKTOR</option>
                    <option value="SPEKER AKTIF">SPEKER AKTIF</option>
                    <option value="KAMERA">KAMERA</option>
                    <option value="PRINTER">PRINTER</option>
                    <option value="PS">PS</option>
                    <option value="SEPEDA GUNUNG">SEPEDA GUNUNG</option>
                    <option value="JAM">APPLE WATCH</option>
                    <option value="IPAD">IPAD/TAB</option>
                    <option value="DRON">DRON</option>
                    <option value="PROYEKTOR">PROYEKTOR</option>
                    <option value="SEPEDA YAMAHA">SEPEDA YAMAHA</option>
                    <option value="SEPEDA HONDA">SEPEDA HONDA</option>
                    <option value="SEPEDA SUZUKI">SEPEDA SUZUKI</option>
                    <option value="SEPEDA KAWASAKI">SEPEDA KAWASAKI</option>
                    <option value="MOBIL TOYOTA">MOBIL TOYOTA</option>
                    <option value="MOBIL DAIHATSU">MOBIL DAIHATSU</option>
                    <option value="MOBIL SUZUKI">MOBIL SUZUKI</option>
                    <option value="MOBIL MITSUBISHI">MOBIL MITSUBISHI</option>
                    
                    
                  </select>

            </div>

             </div>
        

          
            <?php 
                        $query1 = "SELECT * FROM registrasi where id='".$id."' ";
                        $hasil2 = mysqli_query($koneksi, $query1);
                        $row = mysqli_fetch_assoc($hasil2);                        
                       ?>

               

              <div class="col-sm-6">

              <div class="form-group row">
                <label for="nama" class="col-sm-4">Nilai Taksiran</label>
                <input type="text" name="taksasi" id="taksasi" class="form-control col-sm-7" onkeyup="validAngka(this)" onkeypress="return  hanyaAngka(event)" onKeyDown="changeFocus(event,'margin')" onfocus="use_number(this)" onblur="use_text(this)"/>    
              </div>

              <div class="form-group row">
                <label for="nama" class="col-sm-4">Jangka Waktu</label>
                <input type="text" name="jwaktu" id="jwaktu" class="form-control col-sm-7" value="45" readonly="jwaktu" onkeyup="validAngka(this)" onkeypress="return  hanyaAngka(event)" minlength="1" maxlength="2" onKeyDown="changeFocus(event,'margin')"/>    
              </div>
              

              <div class="form-group row">
                <label for="nama" class="col-sm-4">Biaya Titip</label>
                <div class="custom-control custom-radio col-sm-3 ">
                          <input type="radio" class="custom-control-input"  id="customRadio11" name="margin" value="5.00" onKeyDown="changeFocus(event,'noseri')"  /> <!-- checked -->
                          <label for="customRadio11" class="custom-control-label">5.00% </label>
                </div>
                <div class="custom-control custom-radio col-sm-3">
                          <input class="custom-control-input " type="radio" id="customRadio12" name="margin" value="7.50" onKeyDown="changeFocus(event,'noseri')" />
                          <label for="customRadio12" class="custom-control-label">7.5%</label>
                 </div>
              </div>
                            
              <div class="form-group row">
                <label for="nama"  class="col-sm-4">SN/Plat</label>
                <input type="text" name="noseri" id="noseri"  class="form-control col-sm-7" onKeyDown="changeFocus(event,'kondisi')"/>    
              </div>
              
               <div class="form-group row">
                <label for="nama"  class="col-sm-4">Kondisi</label>
                <input type="text" name="kondisi" id="kondisi"  class="form-control col-sm-7" onKeyDown="changeFocus(event,'keterangan')"/>    
              </div>

              <div class="form-group row">
                <label for="nama"  class="col-sm-4">Keterangan</label>
               <input type="text" value="Pencairan <?php echo $_POST['r_register'].".".sprintf("%02d",$reg['jml']+1)."[".$row['nama']."]";?>" name="keterangan" id="keterangan" class="form-control col-sm-7" onKeyDown="changeFocus(event,'otp')"/>
                
              </div>

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

              <div class="form-group row">
                <label for="nama" class="col-sm-4">Alamat</label>  
                <input type="text" class="form-control col-sm-7"  value="<?php echo $row['alamat']; ?>" readonly="alamat"/>
                  
              </div>

    <?php
$nik = mysqli_fetch_assoc(mysqli_query($koneksi, "SELECT nik FROM registrasi WHERE id='$id'  "));
$nikjadi = $nik['nik'];

$ceknikganda = mysqli_fetch_assoc(mysqli_query($koneksi, "SELECT COUNT(*) AS jmlnik FROM registrasi b WHERE b.nik = '$nikjadi' AND EXISTS (
        SELECT 1 FROM pinjaman a WHERE a.register = b.id AND a.bakidebet >0
    );  "));
         
     ?>

              
                <input type="hidden" class="form-control col-sm-7" name="nik" id="nik"  value="<?php echo $ceknikganda['jmlnik']; ?>" readonly/>

         
                  
            </div>
            </div>
          </div>

        
      
      <!-- Kedua -->
         
      
              
           
              
            <!-- /.card-body -->
            <div class="card-footer bg-info">
              <input type="button" name="simpanpencairan" id="simpanpencairan" 
              class="btn btn-primary" value="Simpan" onclick='document.geElementById("form-simpanpencairan").submit()'  >
              <!-- <a href="" class="btn btn-secondary">
                Batal
              </a> -->
              <a href="home.php?home=<?php echo md5("pencairan");?>" class="btn btn-success">
                Tambah
              </a>
              <?php if($_SESSION['level']<1){ ?>
              <a href="home.php?home=<?php echo md5("edit_pencairan");?>" class="btn btn-warning">
                Edit
              </a>
              <a href="home.php?home=<?php echo md5("delet_pencairan");?>" class="btn btn-danger">
                Hapus
              </a>
            <?php } ?>
              <a class="btn btn-secondary" type="button" href="faktur/cetak_faktur_pinjaman.php" target="_bank">Print</a>
            </div>  
          </form>
        <?php } ?>
          

          </div>
        </div>
        <!-- /.card -->
      </div>
      <!--/.col (left) -->
    </div>
    <!-- /.row -->
  </div><!-- /.container-fluid -->
</section>
<!-- /.content -->

<?php
$otprek= $_POST['r_register'].".".sprintf("%02d",$reg['jml']+1);
$otp = mysqli_fetch_assoc(mysqli_query($koneksi, "SELECT * FROM otp_pjm WHERE rekening='$otprek'  "));
$otpdatabase = $otp['no_otp'];
?>


<!-- <script type="text/javascript" src="jquery.js"></script>  -->
<script type="text/javascript">
$(document).ready(function() {
    // Format number dengan separator ribuan
    function formatNumber(num) {
        return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }

    // Parse number dari format ribuan
    function parseNumber(str) {
        return parseInt(str.replace(/,/g, ''), 10) || 0;
    }

    // Validasi form sebelum submit
    function validateForm() {
        const plafond = parseNumber($('#plafond').val());
        const taksasi = parseNumber($('#taksasi').val());
        const noseri = $('#noseri').val();
  const nik = parseInt($('#nik').val());
        const errors = [];

        // Validasi field wajib
        const requiredFields = {
            'rekening': $('#rekening').val(),
            'tgl': $('#tgl').val(),
            'plafond': plafond,
            'jenis cair': $('input[name="jcair"]:checked').val(),
            'pembelian barang': $('#pbarang').val(),
            'jenis barang': $('input[name="jbarang"]:checked').val(),
            'kelengkapan': $('#kelengkapan').val(),
            'jaminan': $('#jaminan').val(),
            'taksasi': taksasi,
            'jangka waktu': $('#jwaktu').val(),
            'margin': $('input[name="margin"]:checked').val(),
            'noseri': $('#noseri').val(),
            'kondisi': $('#kondisi').val()
        };

        Object.entries(requiredFields).forEach(([field, value]) => {
            if (!value || value.toString().trim() === '') {
                errors.push(`${field} harus diisi!`);
            }
        });
  
  if (noseri) {
            // Menggunakan AJAX untuk memeriksa noseri
            $.ajax({
                type: 'POST',
                url:  'simpan/check_noseri.php',
                data: { noseri: noseri },
                async: false, // Consider changing to async true for better UX
                dataType: 'json',
                success: function(response) {
                    if (response.error) {
                        errors.push('Error: ' + response.error);
                    } else if (response.exists) {
                        errors.push('Sudah pernah direalisasikan dengan bakidebet ' + formatNumber(response.bakidebet) + '.');
                    }
                },
                error: function(xhr, status, error) {
                    errors.push('Gagal melakukan validasi nomor seri: ' + error);
                }
            });
        }
  
  // Check if NIK count exceeds allowed limit
  //errors.push('Sudah Pernah Cair di ' + nik + ' kantor lain. ');

        if (nik > 3) {
            errors.push('Sudah Pernah Pengajuan di kantor lain. ');

        }

        // Validasi plafond dan taksasi
        if (plafond > taksasi) {
            errors.push('Plafond tidak boleh lebih besar dari nilai taksasi!');
        }

        // Validasi OTP untuk plafond >= 5.000.000
        if (plafond >= 3000000) {
            const otp = $('#otp').val();
            const validOtp = "<?php echo $otpdatabase; ?>";
            console.log(`OTP: ${otp}, Valid OTP: ${validOtp}`); //menampilkan error
            
            if (!otp) {
                errors.push('OTP wajib diisi untuk plafond â‰¥ Rp 5.000.000');
            } else if (otp !== validOtp) {
                errors.push('OTP tidak valid!');
            }
        }

        return errors;
    }

    // Handle form submission
    $("#simpanpencairan").click(function(e) {
        e.preventDefault();
        
        const errors = validateForm();
        if (errors.length > 0) {
            Swal.fire({
                icon: 'error',
                title: 'Validasi Gagal',
                html: errors.join('<br>'),
                confirmButtonText: 'Perbaiki'
            });
            return;
        }

        // Show loading
        alert ("Data Berhasil Disimpan");
        window.location.href = 'home.php?home=<?php echo md5("pencairan");?>';

        // Submit form
        $.ajax({
            type: 'POST',
            url: 'simpan/simpan_pinjaman.php',
            data: $('#form-simpanpencairan').serialize(),
            success: function(response) {
              console.log(`Response received: ${response}`);//menampilkan error
              
                try {
                    // Cek apakah response berupa JSON
                    const result = JSON.parse(response);
                    
                    if (result.success) {
                        Swal.fire({
                            icon: 'success',
                            title: 'Berhasil',
                            text: result.message || 'Data berhasil disimpan',
                            confirmButtonText: 'OK'
                        }).then((result) => {
                            if (result.isConfirmed) {
                                window.location.href = 'home.php?home=<?php echo md5("pencairan");?>';
                            }
                        });
                    } else {
                        throw new Error(result.message || 'Gagal menyimpan data');
                    }
                } catch (e) {
                    // Jika response bukan JSON, cek apakah ada redirect script
                    if (response.includes("window.location")) {
                        eval(response);
                    } else {
                        throw new Error('Terjadi kesalahan dalam memproses response');
                    }
                }
            },
            error: function(xhr, status, error) {
                Swal.fire({
                    icon: 'error',
                    title: 'Gagal',
                    text: 'Terjadi kesalahan saat menyimpan data: ' + error,
                    confirmButtonText: 'OK'
                });
            }
        });
    });

    // Format input plafond dan taksasi saat diketik
    $('#plafond, #taksasi').on('input', function() {
        const value = $(this).val().replace(/[^\d]/g, '');
        if (value) {
            $(this).val(formatNumber(value));
        }
    });
});
</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

 $('#plafond').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;
}

$('#taksasi').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>   

<!-- 
input huruf besar
https://bloggerbodrex.blogspot.com/2017/05/cara-agar-input-data-menjadi-huruf.html
  <td><input type="text" name="vnama" size="20" onkeyup="this.value = this.value.toUpperCase()" required></td>
 -->
<script>
  /*required onkeypress='return harusHuruf(event)' tinggal pasang ke input
  https://kursuswebdesign.org/cara-membuat-validasi-input-form-hanya-text-dengan-javascript/*/
function harusHuruf(evt){
        var charCode = (evt.which) ? evt.which : event.keyCode
        if ((charCode < 65 || charCode > 90)&&(charCode < 97 || charCode > 122)&&charCode>32)
            return false;
        return true;
}
</script>

<script>
    function hanyaAngka(evt) {
      var charCode = (evt.which) ? evt.which : event.keyCode
       if (charCode > 31 && (charCode < 48 || charCode > 57))
 
        return false;
      return true;
    }
  </script>

<script type="text/javascript">
  function ClearFields() {
    /*https://stackoverflow.com/questions/14837466/clearing-a-text-field-on-button-click*/

     /*document.getElementById("tgl").value = "";
     document.getElementById("register").value = "";
     document.getElementById("plafond").value = "";*/
}
</script>



}



</head>
</html>