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

  <script type="text/javascript">
/*  https://erroz.wordpress.com/2009/03/30/fungsi-pindah-baris/
    function nextfield(ID)
{
if (event.keyCode == 13)
document.getElementById(ID).focus();
}*/
</script>
<!-- Validasi Muncul popup -->

<script language='javascript'>
  /*https://senterwebs.com/artikel-415/cara-mudah-membuat-validasi-angka-lengkap.html*/
function validAngka(a)
{
    if(!/^[0-9.]+$/.test(a.value))
    {
    a.value = a.value.substring(0,a.value.length-1000);
    }
}
</script>
<?php
require './kalenderhijriah.php';
$kode= $_SESSION['kode'];
?>

<!-- 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 ">Registrasi</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">
        <style>
  .form-control {
    height: 30px; /* Atur tinggi sesuai kebutuhan */
    /*border-radius: 5px;*/ /* Atur border-radius untuk sudut yang lebih halus */
    /*border: 1px solid #007bff;*/ /* Warna border */
    border-radius: 5px; /* Melengkungkan sudut */
    border: 2px solid #ccc;
    border-radius: 3px;
    font-size: 13px;
    background-color: white;
    padding: 4px 10px;
    box-sizing: border-box; /* Menghitung padding dalam lebar elemen */
  }
  .btn {
    border-radius: 5px; /* Sesuaikan dengan tombol */
  }
  .custom-spacing {
    margin-bottom: 2px; /* Jarak antar input 2px */
    }
    label{

    font-family: 'Arial', sans-serif; /* Ganti dengan font yang Anda suka */
    font-size: 12px; /* Ukuran font */
    font-weight: bold; /* Gaya font */
    color: #333; /* Warna font */
    margin-bottom: 5px; /* Jarak antara label dan input */
    padding: 4px 10px;
    }

</style>

          <!-- 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>

    
    

      <!-- <div class="row">
        <div class="col-md-4 text-center">
        <div id="upload-demo"></div>
        </div>
        <div class="col-md-4" style="padding:5%;">
        <strong>Cari Photo:</strong>
        <input type="file" id="image" nama="image" onkeypress="nextfield('crop')">

        <button di="crop" nama="crop" class="btn btn-info btn-block btn-upload-image" style="margin-top:2%">Crop</button>

        </div>

        <div class="col-md-4">
        <div id="preview-crop-image" style="background:#9d9d9d;width:300px;padding:50px 50px;height:300px;"></div>
        </div>
      </div> -->

    

<!-- https://www-devopsschool-com.translate.goog/blog/image-upload-and-crop-using-php-and-jquery/?_x_tr_sl=en&_x_tr_tl=id&_x_tr_hl=id&_x_tr_pto=tc -->

<!-- <script type="text/javascript">


var resize = $('#upload-demo').croppie({
    enableExif: true,
    enableOrientation: true,    
    viewport: { // Default { width: 100, height: 100, type: 'square' } 
        width: 200,
        height: 200,
        type: 'square' //square
    },
    boundary: {
        width: 300,
        height: 300
    }
});


$('#image').on('change', function () { 
  var reader = new FileReader();
    reader.onload = function (e) {
      resize.croppie('bind',{
        url: e.target.result
      }).then(function(){
        console.log('jQuery bind complete');
      });
    }
    reader.readAsDataURL(this.files[0]);
});


$('.btn-upload-image').on('click', function (ev) {
  resize.croppie('result', {
    type: 'canvas',
    size: 'viewport'
  }).then(function (img) {
    $.ajax({
      url: "menu/croppie.php",
      type: "POST",
      data: {"image":img},
      success: function (data) {
        html = '<img src="' + img + '" />';
        $("#preview-crop-image").html(html);
      }
    });
  });
});

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


              <form action="" method="POST">
              <div class="row">
              <div class="col-sm-6">
              <div class="form-group row custom-spacing">
              <label for="nama" class="col-sm-3">Pilih Alamat </label>
              <select id="desa" name="desa" class="form-control select2 col-sm-7" >
                <!-- onchange="this.form.submit();" -->
                     <?php
                     include 'koneksi.php';
                      // ambil data dari database
                        $query = "SELECT * FROM alamat order by kec,desa";  /*ORDER BY divisi*/                /*https://kodingbagus.blogspot.com/2019/08/cara-membuat-pencarian-di-selectoption.html*/
                        $hasil = mysqli_query($koneksi, $query);
                        while ($row = mysqli_fetch_array($hasil)) {
                          $ket="";
                          if(isset($_POST['desa'])){
                            $desa=trim($_POST['desa']);
                            if($desa==$row['desa'])
                            {
                              $ket="selected";
                            }
                          }
                            ?>
                          
                            <div class="pertama"><option  <?php echo $ket ?> value="<?php echo $row['kode']; ?>"><?php echo $row['dusun']; ?>-<?php echo $row['rtrw']; ?>-<?php echo $row['desa']; ?>-<?php echo $row['kec'];?>-<?php echo $row['kab'];?></option></div>
                            <?php
                        }
                        ?>
                          <!-- https://kelasprogrammer.com/menampilkan-data-berdasarkan-pilihan-combo-box-di-php/ -->

                    </select>
                    
                        
                <!-- <input type="text"name="query" class="form-control select2 col-sm-8"  placeholder="Ketik ID/Nama/ayah" autofocus/> --> <!-- readonly -->
                <button type="submit" name="search" class="btn btn-info"  value="cari"><i class="fas fa-search"></i></button>
              </div>
            </form>
              

              <?php
                                           
                 $a = mysqli_query($koneksi,"SELECT count(kode)+1 as no FROM registrasi where kode='$kode' ");
                  $id = mysqli_fetch_row($a) ;
              ?>
              <form action="" class="form-simpanregister"  id="form-simpanregister">
              
              <div class="form-group row custom-spacing">
                <label for="nama" class="col-sm-3">No Registrasi</label>
                <input type="text" name="r_register" id="r_register" class="form-control col-sm-8" value="<?php echo $kode.".". sprintf("%06d",$id['0']+1) ?>" readonly="r_register"  onkeypress="nextfield('r_tgl')"> 
              </div>

              <div id="datepicker" class="form-group row">
    <label for="nama" class="col-sm-3">Tgl</label>
    <div class="col-sm-8 position-relative">
        <input type="text" name="r_tgl" id="r_tgl" class="form-control" placeholder="Inputkan Tanggal" value="<?php  echo sprintf('%02d', $hijri[1]) . '-' . $calendar->monthName($hijri[0]) . '-' . $hijri[2]; ?>" required="" onKeyDown="changeFocus(event,'r_nik')" autofocus/>
        <img id="pick-button" src="kalender.png" alt="Pick Date" style="cursor: pointer; width: 24px; height: 24px; position: absolute; right: 10px; top: 50%; transform: translateY(-50%);" onclick="pickADate(event);"/>
    </div>
</div>
              
              <div class="form-group row custom-spacing">
                <label for="nama" class="col-sm-3">NIK</label>
                <input type="text" name="r_nik" id="r_nik" class="form-control col-sm-8" required="" placeholder="Tulis No KTP" onkeyup="validAngka(this)" onKeyDown="changeFocus(event,'r_kk')">      
            </div>
            <div class="form-group row custom-spacing">
                <label for="nama" class="col-sm-3">KK</label>
                <input type="text" name="r_kk" id="r_kk" class="form-control col-sm-8" required="" placeholder="Tulis No KK" onkeyup="validAngka(this)" onKeyDown="changeFocus(event,'r_nim')">      
            </div>
            <div class="form-group row custom-spacing">
                <label for="nama" class="col-sm-3">NIM</label>
                <input type="text" name="r_nim" id="r_nim" class="form-control col-sm-8" required="" placeholder="Tulis No KTP" onkeyup="validAngka(this)" onKeyDown="changeFocus(event,'r_nama')">      
            </div>
            <div class="form-group row custom-spacing">
                <label for="nama" class="col-sm-3">Nama</label>
                <input type="text" name="r_nama" id="r_nama" class="form-control col-sm-8" onkeypress='return harusHuruf(event)' placeholder="Tulis Nama Sesuai KTP"required="" onkeyup="this.value = this.value.toUpperCase()" onkeypress='return harusHuruf(event)' onKeyDown="changeFocus(event,'r_kelamin')">      
            </div>
            <div class="form-group row custom-spacing">
                <label for="nama" class="col-sm-3">Kelamin</label>
                <div class="custom-control custom-radio col-sm-3 ">
                          <input class="custom-control-input " type="radio" id="customRadio44" name="r_kelamin" value="L" onKeyDown="changeFocus(event,'r_ttl')" checked>
                          <label for="customRadio44" class="custom-control-label">Laki-laki </label>
                        </div>
                        <div class="custom-control custom-radio col-sm-4">
                          <input class="custom-control-input " type="radio" id="customRadio42" name="r_kelamin" value="P" onKeyDown="changeFocus(event,'r_ttl')" >
                          <label for="customRadio42" class="custom-control-label">Prempuan</label>
                        </div>
                      </div>

                        
            
            <div class="form-group row custom-spacing">
                <label for="nama" class="col-sm-3">TTL</label>
                <input type="text" name="r_ttl" id="r_ttl" class="form-control col-sm-8"required=""  placeholder="Tulis Tempat Lahir Anda" onkeyup="this.value = this.value.toLowerCase()" onkeypress='return harusHuruf(event)' onKeyDown="changeFocus(event,'r_tgll')">      
            </div>

            <div class="form-group row custom-spacing">
                <label for="nama" class="col-sm-3">Tgl Lahir</label>
                <input type="date" name="r_tgll" id="r_tgll" class="form-control col-sm-8" placeholder="Tulis Keterangan" required="" onKeyDown="changeFocus(event,'r_ibu')">      
            </div>

          </div>
                      <?php
                      error_reporting(E_ALL^(E_NOTICE|E_WARNING));
                      ini_set('display_errors',1);
                      error_reporting(0);
                  if(isset($_POST['desa'])){                  

                      $desa=$_POST["desa"];
                   
                        $query1 = "SELECT * FROM alamat where kode='".$desa."' ";
                         /*https://kodingbagus.blogspot.com/2019/08/cara-membuat-pencarian-di-selectoption.html*/
                         /*https://apayangkamu.com/cara-menggunakan-cek-data-kosong-php#:~:text=include%20%22koneksi.php%22%3B%20%24sql%20%3D%20%22select%20%2A%20from%20pengunjung,%2F%2FPengecekan%20apakah%20data%20ada%20%24cek%20%3D%20mysqli_num_rows%20%28%24query%29%3B*/
                        $hasil2 = mysqli_query($koneksi, $query1);
                        $row = mysqli_fetch_assoc($hasil2);       
                       } ?>

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

              <div class="form-group row custom-spacing">
                <label for="nama" class="col-sm-3">Ibu Kandung</label>
                <input type="text" name="r_ibu" id="r_ibu" class="form-control col-sm-8"required="" placeholder="Tulis nama ibu yang melahirkan"onkeyup="this.value = this.value.toUpperCase()" onkeypress='return harusHuruf(event)' onKeyDown="changeFocus(event,'r_pekerjaan')">      
            </div>
            <div class="form-group row custom-spacing">
                <label for="nama" class="col-sm-3">Wali</label>
                <input type="text" name="r_pekerjaan" id="r_pekerjaan"required="" class="form-control col-sm-8" placeholder="Tulis Pekerjaan"onkeyup="this.value = this.value.toLowerCase()" onkeypress='return harusHuruf(event)' onKeyDown="changeFocus(event,'r_kelas')">      
            </div>
            <div class="form-group row custom-spacing">
    <label for="nama" class="col-sm-3">Masuk Kelas</label>
    <div class="custom-control custom-radio col-sm-1">
        <input class="custom-control-input" type="radio" id="customRadio1" name="r_kelas" value="S-A" onKeyDown="changeFocus(event,'r_nohp')" checked>
        <label for="customRadio1" class="custom-control-label" style="padding: 1px 1px;">A</label>
    </div>
    <div class="custom-control custom-radio col-sm-1">
        <input class="custom-control-input" type="radio" id="customRadio2" name="r_kelas" value="S-B" onKeyDown="changeFocus(event,'r_nohp')">
        <label for="customRadio2" class="custom-control-label" style="padding: 1px 1px;">B</label>
    </div>
    <div class="custom-control custom-radio col-sm-1">
        <input class="custom-control-input" type="radio" id="customRadio3" name="r_kelas" value="1" onKeyDown="changeFocus(event,'r_nohp')">
        <label for="customRadio3" class="custom-control-label" style="padding: 1px 1px;">1</label>
    </div>
    <div class="custom-control custom-radio col-sm-1">
        <input class="custom-control-input" type="radio" id="customRadio4" name="r_kelas" value="2" onKeyDown="changeFocus(event,'r_nohp')">
        <label for="customRadio4" class="custom-control-label"style="padding: 1px 1px;">2</label>
    </div>
    <div class="custom-control custom-radio col-sm-1">
        <input class="custom-control-input" type="radio" id="customRadio5" name="r_kelas" value="3" onKeyDown="changeFocus(event,'r_nohp')">
        <label for="customRadio5" class="custom-control-label"style="padding: 1px 1px;">3</label>
    </div>
    <div class="custom-control custom-radio col-sm-1">
        <input class="custom-control-input" type="radio" id="customRadio6" name="r_kelas" value="4" onKeyDown="changeFocus(event,'r_nohp')">
        <label for="customRadio6" class="custom-control-label"style="padding: 1px 1px;">4</label>
    </div>
    <div class="custom-control custom-radio col-sm-1">
        <input class="custom-control-input" type="radio" id="customRadio7" name="r_kelas" value="5" onKeyDown="changeFocus(event,'r_nohp')">
        <label for="customRadio7" class="custom-control-label"style="padding: 1px 1px;">5</label>
    </div>
    <div class="custom-control custom-radio col-sm-1">
        <input class="custom-control-input" type="radio" id="customRadio8" name="r_kelas" value="6" onKeyDown="changeFocus(event,'r_nohp')">
        <label for="customRadio8" class="custom-control-label"style="padding: 1px 1px;">6</label>
    </div>
</div>

            <div class="form-group row custom-spacing">
                <label for="nama" class="col-sm-3">No Hp</label>
                <input type="text" name="r_nohp" id="r_nohp" class="form-control col-sm-8"required="" placeholder="Tidak usan nulis angka 0/nol" minlength="11" maxlength="14" onkeyup="validAngka(this)" onkeypress="return hanyaAngka(event)" onKeyDown="changeFocus(event,'r_biaya')">      
            </div>
            <div class="form-group row custom-spacing">
    <label for="nama" class="col-sm-3">Biaya Rp</label>
    <input type="text" name="r_biaya" id="r_biaya" class="form-control col-sm-8" required="" placeholder="Biaya Pendaftaran" onkeyup="validAngka(this)" onkeypress="return hanyaAngka(event)" onkeydown="changeFocus(event,'simpanregister')">      
</div>



        <script>
    function addPrefix(phoneInput) {
        // Ambil nilai dari input
        let inputValue = phoneInput.value;

        // Cek apakah inputValue sudah diawali dengan "62"
        if (inputValue && !inputValue.startsWith('62')) {
            // Menghapus angka yang terdapat sebelum 0
            if (inputValue.startsWith('0')) {
                inputValue = inputValue.substring(1);
            }
            // Menambahkan prefix "62"
            phoneInput.value = '62' + inputValue;
        }
    }

    document.getElementById('r_nohp').addEventListener('input', function() {
        addPrefix(this);
    });

    document.getElementById('r_nohp2').addEventListener('input', function() {
        addPrefix(this);
    });
</script>
        
              <div class="form-group row custom-spacing">
                <label for="nama" class="col-sm-3">Alamat</label>  
                <input type="hidden" name="r_alamat" id="r_alamat" class="form-control col-sm-1" placeholder="Tulis Alama Sama dg KTP" required="" onkeypress="nextfield('r_desa')">
                <input type="text" name="k_alamat" id="k_alamat" class="form-control col-sm-8" required="" readonly="r_alamat"  onkeypress="nextfield('r_rtrw')">  </div>

                <div class="form-group row custom-spacing">
                <label for="nama" class="col-sm-3">RT/RW</label>  
                <input type="text" name="r_rtrw"id="r_rtrw" class="form-control col-sm-8"required="" readonly="r_rtrw" value="<?php echo $row['rtrw']; ?>" onkeypress="nextfield('r_desa')">  
              </div>
              
                <div class="form-group row custom-spacing">
                <label for="nama"  class="col-sm-3">Desa</label>
                <input type="hidden" name="k_desa" id="k_desa" class="form-control col-sm-1" placeholder="Tulis Nominal" required="" readonly="desa" value="<?php echo $row['k_desa']; ?>" >
                <input type="text" name="r_desa" id="r_desa" class="form-control col-sm-8" required="" readonly="r_desa" value="<?php echo $row['desa']; ?>">
              </div>
              
            <div class="form-group row custom-spacing">
                <label for="nama"  class="col-sm-3">Kecamatan</label>
               <input type="hidden" name="k_kecamatan" id="k_kecamatan" class="form-control col-sm-1" readonly="kecamatan" value="<?php echo $row['k_kec']; ?>" required="">
               <input type="text" name="r_kecamatan" id="r_kecamatan" class="form-control col-sm-8" readonly="kecamatan" value="<?php echo $row['kec']; ?>" required="" onkeypress="nextfield('r_kabupaten')">
                    
                </div>
                <div class="form-group row custom-spacing">
                <label for="nama" class="col-sm-3">Kabupaten</label>
                <input type="hidden" name="k_kabupaten" id="k_kabupaten" class="form-control col-sm-1" required="" readonly="kota"  value="<?php echo $row['k_kab']?>" onkeypress="nextfield('r_ibu')"> 
                
                <input type="text" name="r_kabupaten" id="r_kabupaten" class="form-control col-sm-8" required="" readonly="kota"  value="<?php echo $row['kab']; ?>" onkeypress="nextfield('r_ibu')">      
                
            </div>
            

                </div>
              </div>
        
           


              
            <!-- /.card-body -->
            <div class="card-footer ">
              <input type="button" name="simpanregister" id="simpanregister" 
              class="btn btn-primary" value="Simpan">
              <a href="home.php?home=<?php echo md5("registrasi");?>" class="btn btn-secondary">
                Tambah
              </a>
              <a href="home.php?home=<?php echo md5("edit_registrasi");?>" class="btn btn-warning">
                Edit 
              </a>
              <a href="home.php?home=<?php echo md5("lap_register");?>" class="btn btn-info">
                Lihat
              </a>
              <a href="home.php?home=<?php echo md5("delet_registrasi");?>" class="btn btn-danger">
                Hapus
              </a>
            </div>
            
          </form>
        </div>
        <!-- /.card -->
      </div>
      <!--/.col (left) -->
    </div>
    <!-- /.row -->
  </div><!-- /.container-fluid -->
</section>
<!-- /.content -->

<!-- <script type="text/javascript" src="jquery.js"></script> -->
<script type="text/javascript">

 $(document).ready(function(){
    $("#simpanregister").click(function(){
      var data = $('#form-simpanregister').serialize();
      var r_register= $('#r_register').val();
      var r_tgl= $('#r_tgl').val();
      var r_nik= $('#r_nik').val();
      var r_nama= $('#r_nama').val();
      var r_kelamin= $('#r_kelamin').val();
      var r_ttl= $('#r_ttl').val();
      var r_tgll= $('#r_tgll').val();
      var r_alamat= $('#r_alamat').val();
      var r_rtrw= $('#r_rtrw').val();
      var r_desa= $('#r_desa').val();
      var r_kecamatan= $('#r_kecamatan').val();
      var r_kabupaten= $('#r_kabupaten').val();
      var r_ibu= $('#r_ibu').val();
      var r_pekerjaan= $('#r_pekerjaan').val();
      var r_nohp= $('#r_nohp').val();
      
 
      if(r_register== "0"|| r_tgl=="0" ||r_nik=="0"||r_nama=="0"||r_kelamin=="0"||r_ttl=="0"||r_tgll=="0"||r_alamat=="0"||r_rtrw=="0"||r_desa=="0"||r_kecamatan=="0"||r_kabupaten=="0"||r_ibu=="0"||r_pekerjaan=="0"||r_nohp=="0"){ 
Swal.fire({
  icon: 'error',
  title: 'Hati-hati...',
  text: 'Data masih ada yg belum diisi!',
  footer: '<a href="">Anda Perlu teliti sedikit lagi?</a>'
});
/*https://sweetalert2.github.io/*/
       /* alert ("Data Masih ada yang kosong 1");*/
        //window.location.href='/rakerugt/home.php?page=cap_realita';
      
    } else if(r_register== ""|| r_tgl==""||r_nik==""||r_nama==""||r_kelamin==""||r_ttl==""||r_tgll==""||r_alamat==""||r_rtrw==""||r_desa==""||r_kecamatan==""||r_kabupaten==""||r_ibu==""||r_pekerjaan==""||r_nohp==""){ 

      Swal.fire(
  'Data Masih ada yang Kosong !',
  'Mohon data dilengkapi dlu !',
  'question'
);
        /*alert ("Data Masih ada yang kosong 2");*/
       
    }else{

      $.ajax({
        type: 'POST',
        url: 'simpan/simpan_register.php',
        data: data,
        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) => {
 
  if (result.dismiss === Swal.DismissReason.timer) {
    console.log('I was closed by the timer')
  }
})*/
         Swal.fire({
  title: 'Alhamdulillah...Data Sukses Tersimpan...!!!!',
  text: 'Bisa Anda Cek...!!!',
  imageUrl: 'img/logougt.png',
  imageWidth: 75,
  imageHeight: 80,
  imageAlt: 'Custom image',
  animation: false
})

         alert("Data Sukses Disimpan");
         window.location.href='home.php?home=4b7f5c754b59efd711f61deb0d0541db'; 
        },
        error: function(error){
          console.log(`error ${error}`)
         
        }
      });
    }
    });
  });
  
</script>
<script type="text/javascript">
  function cekhuruf(a) {
valid = /^[A-Za-z]{1,}$/;
return valid.test(a);
}
</script>
<script type="text/javascript">
    // Fungsi untuk validasi input hanya angka dan koma
    function validAngka(a) {
    // Remove non-numeric characters except dots
    if(!/^[0-9.]+$/.test(a.value)) {
        a.value = a.value.replace(/[^0-9.]/g, '');
    }
}

// Improved function for handling number inputs that only allows numeric input
function hanyaAngka(event) {
    var charCode = (event.which) ? event.which : event.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    return true;
}

// Format number as currency with thousands separator
$('#r_biaya').on('keyup', function() {
    var angka = $(this).val().replace(/[^\d]/g, ''); // Remove all non-digits
    
    // Don't format if empty
    if(angka === '') {
        $(this).val('');
        return;
    }
    
    // Format with thousand separators
    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,
        rupiah = split[0].substr(0, sisa),
        ribuan = split[0].substr(sisa).match(/\d{3}/gi);
        
    if (ribuan) {
        separator = sisa ? '.' : '';
        rupiah += separator + ribuan.join('.');
    }
    
    return rupiah;
}
</script>
<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 isValidDate(dateString)
{
    // First check for the pattern
    var regex_date = /^\d{14}\-\d{1,2}\-\d{1,2}$/;

    if(!regex_date.test(dateString))
    {
        return false;
    }

    // Parse the date parts to integers
    var parts   = dateString.split("-");
    var day     = parseInt(parts[2], 10);
    var month   = parseInt(parts[1], 10);
    var year    = parseInt(parts[0], 10);

    // Check the ranges of month and year
    if(year < 1000 || year > 3000 || month == 0 || month > 12)
    {
        return false;
    }

    var monthLength = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];

    // Adjust for leap years
    if(year % 400 == 0 || (year % 100 != 0 && year % 4 == 0))
    {
        monthLength[1] = 29;
    }

    // Check the range of the day
    return day > 0 && day <= monthLength[month - 1];
}
</script>
<script type="text/javascript">
  $(document).ready(function() {
    // Ketika produk dipilih
    $('#desa').on('change', function() {
        var produkId = $(this).val(); // Ambil ID produk yang dipilih

        if (produkId) {
            $.ajax({
                url: 'simpan/tampilkandata_alamat.php', // Script PHP untuk mengambil data produk
                type: 'GET',
                data: {id: produkId},
                success: function(data) {
                    var produk = JSON.parse(data); // Parsing JSON yang diterima

                    // Mengisi form dengan data yang diterima
                    $('#r_alamat').val(produk.tampil1);
                    $('#r_rtrw').val(produk.tampil2);
                    $('#r_desa').val(produk.tampil3);
                     $('#r_kecamatan').val(produk.tampil4);
                      $('#r_kabupaten').val(produk.tampil5);
                       $('#k_alamat').val(produk.tampil1);
                      $('#k_desa').val(produk.tampil7);
                      $('#k_kecamatan').val(produk.tampil8);
                      $('#k_kabupaten').val(produk.tampil9);
                                         
                },
                error: function() {
                  // Handle error jika ada masalah saat permintaan
                  alert('Terjadi kesalahan saat mengambil data produk.');
                }
            });
                    } else {
                // Jika tidak ada produk yang dipilih, kosongkan semua input
                $('#r_dusun').val('');
                $('#r_rtrw').val('');
                $('#r_desa').val('');
                $('#r_kecamatan').val('');
                $('#r_kabupaten').val('');
                $('#k_desa').val('');
                $('#k_kecamatan').val('');
                $('#k_kabupaten').val('');
                
            }
        });
    });
$(document).ready(function() {
    // Menambahkan event listener untuk setiap input dengan kelas .inputAngka
    $('.inputAngka').on('input', function() {
        validateInput($(this)); // Validasi pada input ini
    });
});

</script>
<!-- <link rel="stylesheet" href="https://ZulNs.github.io/libs/calendar.css"/>
<script type="text/javascript" src="https://ZulNs.github.io/libs/hijri-date.js"></script>
<script type="text/javascript" src="https://ZulNs.github.io/libs/calendar.js"></script> -->
<link rel="stylesheet" href="calendar.css"/>
<script type="text/javascript" src="hijri-date.js"></script>
<script type="text/javascript" src="calendar.js"></script>
<!-- https://zulns.github.io/libs/calendar-api-doc.html -->
<!-- <div id="datepicker">
    <input id="picked-text" type="text" size="35"/>
    <input id="pick-button" type="button" onclick="pickADate();" value="Tgl"/>
</div> -->
<!-- <script type="text/javascript">
    var pickedTxt = document.getElementById('r_tgl'),
        pickBtn = document.getElementById('pick-button'),
        datepicker = new Calendar(true, 0, false, true); // Siapkan sebagai kalender Hijriah
    document.getElementById('datepicker').appendChild(datepicker.getElement());

    // Set properti CSS untuk datepicker
    datepicker.getElement().style.position = 'absolute';
    datepicker.getElement().style.zIndex = '1000';

    datepicker.callback = function() {
        var selectedDate = datepicker.getDate();
        var day = selectedDate.getDate().toString().padStart(2, '0');
        var month = (selectedDate.getMonth() + 1).toString().padStart(2, '0');
        var year = selectedDate.getFullYear();
        pickedTxt.value = day + '-' + month + '-' + year;
        pickedTxt.focus();
        datepicker.hide();
    };

    function pickADate() {
        datepicker.show();
        positionDatepicker(); // Atur posisi datepicker
    }

    function positionDatepicker() {
        var rect = pickedTxt.getBoundingClientRect();
        datepicker.getElement().style.left = rect.left + "px";
        datepicker.getElement().style.top = (rect.top - datepicker.getElement().offsetHeight) + "px";
    }

    // Fungsi untuk menambah event listener klik di luar
    addClickOutsideListener(datepicker, datepicker.getElement().id);
</script>

<style>
    .datepicker {
        position: absolute;
        z-index: 1000;
    }
</style>

<script type="text/javascript">
function addClickOutsideListener(datepicker, popupId) {
    function onClick(event) {
        var popup = document.getElementById(popupId);
        if (popup && !popup.contains(event.target) && !datepicker.getElement().contains(event.target)) {
            datepicker.hide(); // Menyembunyikan kalender
        }
    }

    // Menambahkan event listener untuk mendeteksi klik di luar kalender
    document.addEventListener('click', onClick);

    // Menambahkan kemampuan untuk menyeret datepicker
    let isDragging = false;
    let offsetX, offsetY;

    datepicker.getElement().addEventListener('mousedown', function(e) {
        isDragging = true;
        offsetX = e.clientX - datepicker.getElement().getBoundingClientRect().left;
        offsetY = e.clientY - datepicker.getElement().getBoundingClientRect().top;
        document.addEventListener('mousemove', onMouseMove);
    });

    document.addEventListener('mouseup', function() {
        isDragging = false;
        document.removeEventListener('mousemove', onMouseMove);
    });

    function onMouseMove(e) {
        if (isDragging) {
            datepicker.getElement().style.left = (e.clientX - offsetX) + "px";
            datepicker.getElement().style.top = (e.clientY - offsetY) + "px";
        }
    }
}
</script> -->



<script type="text/javascript">
    var pickedTxt = document.getElementById('r_tgl'),
        pickBtn = document.getElementById('pick-button'),
        datepicker = new Calendar(true, 0, false, true); // Siapkan sebagai kalender Hijriah
    
    // Tambahkan ID ke elemen datepicker untuk referensi
    datepicker.getElement().id = 'calendar-popup';
    document.getElementById('datepicker').appendChild(datepicker.getElement());

    // Set properti CSS untuk datepicker
    datepicker.getElement().style.position = 'absolute';
    datepicker.getElement().style.zIndex = '1000';
    datepicker.getElement().style.display = 'none'; // Sembunyikan kalender secara default

    datepicker.callback = function() {
        var selectedDate = datepicker.getDate();
        var day = selectedDate.getDate().toString().padStart(2, '0');
        var month = (selectedDate.getMonth() + 1).toString().padStart(2, '0');
        var year = selectedDate.getFullYear();
        pickedTxt.value = day + '-' + month + '-' + year;
        pickedTxt.focus();
        datepicker.hide();
    };

    function pickADate(event) {
        event.stopPropagation(); // Mencegah event bubbling
        datepicker.show();
        positionDatepicker(); // Atur posisi datepicker
    }

   /*  function positionDatepicker() {
        var rect = pickedTxt.getBoundingClientRect();
        datepicker.getElement().style.left = rect.left + "px";
        datepicker.getElement().style.top = (rect.bottom + 1) + "px"; // Tampilkan di bawah input dengan sedikit jarak
        
        // Cek apakah keluar dari viewport bawah
        var bottomSpace = window.innerHeight - rect.bottom;
        var calendarHeight = datepicker.getElement().offsetHeight;
        
        if (bottomSpace < calendarHeight + 10) {
            // Jika tidak cukup ruang di bawah, tampilkan di atas input
            datepicker.getElement().style.top = (rect.top - calendarHeight - 5) + "px";
        }
    } */

    // Event listener untuk menutup kalender ketika klik di luar
    document.addEventListener('click', function(event) {
        var calendarElement = datepicker.getElement();
        if (calendarElement.style.display !== 'none' && 
            event.target !== pickedTxt && 
            event.target !== pickBtn && 
            !calendarElement.contains(event.target)) {
            datepicker.hide();
        }
    });

    // Menambahkan kemampuan untuk menggeser datepicker
    var isDragging = false;
    var offsetX, offsetY;

    datepicker.getElement().addEventListener('mousedown', function(e) {
        // Pastikan event tidak terpicu pada tombol kalender atau elemen interaktif lainnya
        if (e.target.tagName.toLowerCase() === 'td' || e.target.closest('.calendar-header')) {
            isDragging = true;
            offsetX = e.clientX - datepicker.getElement().getBoundingClientRect().left;
            offsetY = e.clientY - datepicker.getElement().getBoundingClientRect().top;
            
            // Tambahkan cursor saat menggeser
            datepicker.getElement().style.cursor = 'move';
            
            // Mencegah event bubbling agar tidak memicu event klik di luar
            e.stopPropagation();
            e.preventDefault();
        }
    });

    document.addEventListener('mousemove', function(e) {
        if (isDragging) {
            datepicker.getElement().style.left = (e.clientX - offsetX) + "px";
            datepicker.getElement().style.top = (e.clientY - offsetY) + "px";
        }
    });

    document.addEventListener('mouseup', function() {
        if (isDragging) {
            isDragging = false;
            datepicker.getElement().style.cursor = 'default';
        }
    });

    // Untuk menangani resize window
    window.addEventListener('resize', function() {
        if (datepicker.getElement().style.display !== 'none') {
            positionDatepicker();
        }
    });
</script>

<style>
    .position-relative {
        position: relative;
    }
    
    #calendar-popup {
        box-shadow: 0 0 10px rgba(0,0,0,0.2);
        border-radius: 4px;
        background-color: white;
    }
    
    /* Gaya untuk membuat header kalender dapat digunakan untuk menggeser */
    #calendar-popup .calendar-header {
        cursor: move;
        padding: 8px;
        background-color: #f8f9fa;
        border-bottom: 1px solid #dee2e6;
        border-radius: 4px 4px 0 0;
    }
</style>

</head>
</html>