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

  <!-- Improved form focus handling -->
  <script type="text/javascript">
    function changeFocus(event, nextFocus) {
      if (event.keyCode == 13) {
        event.preventDefault(); // Prevent form submission
        var obj = document.getElementById(nextFocus);
        if (obj) obj.focus();
      }
    }
  </script>

  <!-- Improved number validation -->
  <script language='javascript'>
    function validAngka(a) {
      if(!/^[0-9.]+$/.test(a.value)) {
        a.value = a.value.substring(0, a.value.length-1);
      }
    }
  </script>

  <style>
    .form-control {
      height: 30px;
      border-radius: 5px;
      border: 2px solid #ccc;
      font-size: 13px;
      background-color: white;
      padding: 4px 10px;
      box-sizing: border-box;
    }
    .btn {
      border-radius: 5px;
    }
    .custom-spacing {
      margin-bottom: 2px;
    }
    label {
      font-family: 'Arial', sans-serif;
      font-size: 12px;
      font-weight: bold;
      color: #333;
      margin-bottom: 5px;
      padding: 4px 10px;
    }
    /* Added styles for calendar popup */
    #calendar-popup {
      box-shadow: 0 0 10px rgba(0,0,0,0.2);
      background-color: white;
      z-index: 1000;
    }
  </style>
</head>
<body>
<!-- Content 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>
    </div>
  </div>
</div>

<!-- 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 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>
          
          <div class="card-body">
            <?php
            require './kalenderhijriah.php';
            error_reporting(E_ALL^(E_NOTICE|E_WARNING));
            ini_set('display_errors', 0);
            
            $register = '';
            $where = "where id= '0'";
            
            if(isset($_POST['r_register']) && !empty($_POST['r_register'])){
              $register = $_POST['r_register'];
              $where = "where id='$register'";
            }

            include 'koneksi.php';
            $queryer = "SELECT * FROM registrasi $where";
            $hasilr = mysqli_query($koneksi, $queryer);
            $regis = mysqli_fetch_assoc($hasilr);
            
            // If there's data, extract it
            if($regis) {
              extract($regis);
            }
            ?>

            <!-- Search form -->
            <form action="" method="POST">
              <div class="row">
                <div class="col-sm-6">
                  <div class="form-group row">
                    <label for="nama" class="col-sm-3">Register </label>
                    <input type="text" name="r_register" id="r_register_search" class="form-control col-sm-7" value="<?php echo isset($_POST['r_register']) ? $_POST['r_register'] : ''; ?>"/> 
                    <button type="submit" name="search" class="btn btn-info" value="cari"><i class="fas fa-search"></i></button>
                  
              </div>
            </form>
            
            <!-- Main form -->
            <form action="" class="form-simpanregister" id="form-simpanregister">
             
                  <!-- Hidden field for register ID -->
                  <input type="hidden" name="r_register" id="r_register" class="form-control" value="<?php echo isset($_POST['r_register']) ? $_POST['r_register'] : ''; ?>"/>
                  
                  <!-- Date picker -->
                  <div id="datepicker" class="form-group row">
                    <label for="r_tgl" class="col-sm-3">Tanggal</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 isset($hijri) ? sprintf('%02d', $hijri[1]) . '-' . $calendar->monthName($hijri[0]) . '-' . $hijri[2] : date('d-m-Y'); ?>" 
                        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>
                  
                  <!-- NIK field -->
                  <div class="form-group row custom-spacing">
                    <label for="r_nik" class="col-sm-3">NIK</label>
                    <input type="text" name="r_nik" id="r_nik" class="form-control col-sm-8" 
                      value="<?php echo isset($nik) ? $nik : ''; ?>" 
                      onkeyup="validAngka(this)" onKeyDown="changeFocus(event,'r_nama')">
                  </div>
                  
                  <!-- Name field -->
                  <div class="form-group row custom-spacing">
                    <label for="r_nama" class="col-sm-3">Nama</label>
                    <input type="text" name="r_nama" id="r_nama" 
                      value="<?php echo isset($nama) ? $nama : ''; ?>" 
                      class="form-control col-sm-8" required
                      onkeyup="this.value = this.value.toUpperCase()" 
                      onkeypress='return harusHuruf(event)' 
                      onKeyDown="changeFocus(event,'customRadio111')">
                  </div>
                  
                  <!-- Gender field -->
                  <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="customRadio111" name="r_kelamin" value="L" 
                        onKeyDown="changeFocus(event,'r_ttl')" <?php echo (isset($kelamin) && $kelamin=='L') ? "checked" : "checked"; ?>>
                      <label for="customRadio111" 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="customRadio222" name="r_kelamin" value="P" 
                        onKeyDown="changeFocus(event,'r_ttl')" <?php echo (isset($kelamin) && $kelamin=='P') ? "checked" : ""; ?>>
                      <label for="customRadio222" class="custom-control-label">Perempuan</label>
                    </div>
                  </div>
                  
                  <!-- Birth place field -->
                  <div class="form-group row custom-spacing">
                    <label for="r_ttl" class="col-sm-3">TTL</label>
                    <input type="text" name="r_ttl" id="r_ttl" 
                      value="<?php echo isset($ttl) ? $ttl : ''; ?>" 
                      class="form-control col-sm-8" 
                      onkeyup="this.value = this.value.toUpperCase()" 
                      onKeyDown="changeFocus(event,'r_tgll')">
                  </div>
                  
                  <!-- Birth date field -->
                  <div class="form-group row custom-spacing">
                    <label for="r_tgll" class="col-sm-3">Tgl Lahir</label>
                    <input type="date" name="r_tgll" id="r_tgll" 
                      value="<?php echo isset($tgll) ? date('Y-m-d', strtotime($tgll)) : ''; ?>" 
                      max="<?=date('Y-m-d')?>" 
                      class="form-control col-sm-8" 
                      required onKeyDown="changeFocus(event,'r_ibu')">
                  </div>
                </div>
                
                <div class="col-sm-6">
                  <!-- Mother's name field -->
                  <div class="form-group row custom-spacing">
                    <label for="r_ibu" class="col-sm-3">Ibu Kandung</label>
                    <input type="text" name="r_ibu" id="r_ibu" 
                      value="<?php echo isset($ibu) ? $ibu : ''; ?>" 
                      class="form-control col-sm-8" 
                      onkeyup="this.value = this.value.toUpperCase()" 
                      onkeypress='return harusHuruf(event)' 
                      onKeyDown="changeFocus(event,'r_pekerjaan')">
                  </div>
                  
                  <!-- Occupation field -->
                  <div class="form-group row">
                    <label for="r_pekerjaan" class="col-sm-3">Pekerjaan</label>
                    <input type="text" name="r_pekerjaan" id="r_pekerjaan" 
                      value="<?php echo isset($wali) ? $wali : ''; ?>" 
                      class="form-control col-sm-8" 
                      onkeyup="this.value = this.value.toUpperCase()" 
                      onkeypress='return harusHuruf(event)' 
                      onKeyDown="changeFocus(event,'r_nohp')">
                  </div>
                  
                  <!-- Phone number field -->
                  <div class="form-group row">
                    <label for="r_nohp" class="col-sm-3">No Hp</label>
                    <input type="text" name="r_nohp" id="r_nohp" 
                      value="<?php echo isset($nohp) ? $nohp : ''; ?>" 
                      class="form-control col-sm-8" 
                      minlength="11" maxlength="17" 
                      onkeyup="validAngka(this); addPrefix(this);" 
                      onkeypress="return hanyaAngka(event)" 
                      onKeyDown="changeFocus(event,'customRadio1')">
                  </div>
                  
                  <!-- Class selection -->
                  <div class="form-group row custom-spacing">
                    <label for="nama" class="col-sm-3">Kelas</label>
                    <?php
                    $classes = ['S-A', 'S-B', '1', '2', '3', '4', '5', '6'];
                    $radio_ids = ['customRadio1', 'customRadio2', 'customRadio3', 'customRadio4', 'customRadio5', 'customRadio6', 'customRadio7', 'customRadio8'];
                    $class_labels = ['A', 'B', '1', '2', '3', '4', '5', '6'];
                    
                    for($i = 0; $i < count($classes); $i++) {
                      echo '<div class="custom-control custom-radio col-sm-1">
                        <input class="custom-control-input" type="radio" id="'.$radio_ids[$i].'" name="r_kelas" value="'.$classes[$i].'" '.
                        ((isset($klsNow) && $klsNow==$classes[$i]) ? "checked" : ($i == 0 ? "checked" : "")).'>
                        <label for="'.$radio_ids[$i].'" class="custom-control-label" style="padding: 1px 1px;">'.$class_labels[$i].'</label>
                      </div>';
                    }
                    ?>
                  </div>
                  
                  <!-- Address selection -->
                  <div class="form-group row custom-spacing">
                    <label for="r_alamat" class="col-sm-3">Alamat</label>
                    <div class="col-sm-9">
                      <select id="r_alamat" name="r_alamat" class="form-control select2 col-sm-11">
                        <?php
                        include 'koneksi.php';
                        
                        // First, try to get the current address for this registration
                        $current_address_query = "SELECT alamat FROM registrasi WHERE id = '$register'";
                        $current_address_result = mysqli_query($koneksi, $current_address_query);
                        $current_address = '';
                        if ($current_address_result && mysqli_num_rows($current_address_result) > 0) {
                          $current_address_row = mysqli_fetch_assoc($current_address_result);
                          $current_address = $current_address_row['alamat'];
                          echo "<option value=\"{$current_address}\" selected>{$current_address}</option>";
                        }
                        
                        // Get all addresses from the alamat table
                        $alamat_query = "SELECT k_dusun, dusun FROM alamat";
                        $alamat_result = mysqli_query($koneksi, $alamat_query);
                        
                        while ($item = mysqli_fetch_assoc($alamat_result)) {
                          // Only add if not already the selected option
                          if ($item['dusun'] != $current_address) {
                            echo "<option value=\"{$item['k_dusun']}\">{$item['dusun']}</option>";
                          }
                        }
                        ?>
                      </select>
                    </div>
                  </div>
                  
                  <!-- RT/RW selection -->
                  <div class="form-group row custom-spacing">
                    <label for="r_rtrw" class="col-sm-3">RT/RW</label>
                    <div class="col-sm-9">
                      <select id="r_rtrw" name="r_rtrw" class="form-control select2 col-sm-11">
                        <?php
                        include 'koneksi.php';
                        
                        // First, try to get the current RT/RW for this registration
                        $current_rtrw_query = "SELECT rtrw FROM registrasi WHERE id = '$register'";
                        $current_rtrw_result = mysqli_query($koneksi, $current_rtrw_query);
                        $current_rtrw = '';
                        if ($current_rtrw_result && mysqli_num_rows($current_rtrw_result) > 0) {
                          $current_rtrw_row = mysqli_fetch_assoc($current_rtrw_result);
                          $current_rtrw = $current_rtrw_row['rtrw'];
                          echo "<option value=\"{$current_rtrw}\" selected>{$current_rtrw}</option>";
                        }
                        
                        // Get all RT/RW from the alamat table
                        $rtrw_query = "SELECT k_rtrw, rtrw FROM alamat";
                        $rtrw_result = mysqli_query($koneksi, $rtrw_query);
                        
                        while ($item = mysqli_fetch_assoc($rtrw_result)) {
                          // Only add if not already the selected option
                          if ($item['rtrw'] != $current_rtrw) {
                            echo "<option value=\"{$item['k_rtrw']}\">{$item['rtrw']}</option>";
                          }
                        }
                        ?>
                      </select>
                    </div>
                  </div>
                  
                  <!-- Village selection -->
                  <div class="form-group row custom-spacing">
                    <label for="r_desa" class="col-sm-3">Desa</label>
                    <div class="col-sm-9">
                      <select id="r_desa" name="r_desa" class="form-control select2 col-sm-11">
                        <?php
                        include 'koneksi.php';
                        
                        // First, try to get the current village for this registration
                        $current_desa_query = "SELECT desa FROM registrasi WHERE id = '$register'";
                        $current_desa_result = mysqli_query($koneksi, $current_desa_query);
                        $current_desa = '';
                        if ($current_desa_result && mysqli_num_rows($current_desa_result) > 0) {
                          $current_desa_row = mysqli_fetch_assoc($current_desa_result);
                          $current_desa = $current_desa_row['desa'];
                          echo "<option value=\"{$current_desa}\" selected>{$current_desa}</option>";
                        }
                        
                        // Get all villages from the alamat table
                        $desa_query = "SELECT k_desa, desa FROM alamat";
                        $desa_result = mysqli_query($koneksi, $desa_query);
                        
                        while ($item = mysqli_fetch_assoc($desa_result)) {
                          // Only add if not already the selected option
                          if ($item['desa'] != $current_desa) {
                            echo "<option value=\"{$item['k_desa']}\">{$item['desa']}</option>";
                          }
                        }
                        ?>
                      </select>
                    </div>
                  </div>
                  
                  <!-- District selection -->
                  <div class="form-group row custom-spacing">
                    <label for="r_kecamatan" class="col-sm-3">Kecamatan</label>
                    <div class="col-sm-9 ">
                      <select id="r_kecamatan" name="r_kecamatan" class="form-control select2 col-sm-11">
                        <?php
                        include 'koneksi.php';
                        
                        // First, try to get the current district for this registration
                        $current_kec_query = "SELECT kec FROM registrasi WHERE id = '$register'";
                        $current_kec_result = mysqli_query($koneksi, $current_kec_query);
                        $current_kec = '';
                        if ($current_kec_result && mysqli_num_rows($current_kec_result) > 0) {
                          $current_kec_row = mysqli_fetch_assoc($current_kec_result);
                          $current_kec = $current_kec_row['kec'];
                          echo "<option value=\"{$current_kec}\" selected>{$current_kec}</option>";
                        }
                        
                        // Get all districts from the alamat table
                        $kec_query = "SELECT k_kec, kec FROM alamat GROUP BY k_kec, kec";
                        $kec_result = mysqli_query($koneksi, $kec_query);
                        
                        while ($item = mysqli_fetch_assoc($kec_result)) {
                          // Only add if not already the selected option
                          if ($item['kec'] != $current_kec) {
                            echo "<option value=\"{$item['k_kec']}\">{$item['kec']}</option>";
                          }
                        }
                        ?>
                      </select>
                    </div>
                  </div>
                  
                  <!-- City/Regency selection -->
                  <div class="form-group row custom-spacing">
                    <label for="r_kabupaten" class="col-sm-3">Kabupaten</label>
                    <div class="col-sm-9">
                      <select id="r_kabupaten" name="r_kabupaten" class="form-control select2 col-sm-11">
                        <?php
                        include 'koneksi.php';
                        
                        // First, try to get the current city/regency for this registration
                        $current_kab_query = "SELECT kab FROM registrasi WHERE id = '$register'";
                        $current_kab_result = mysqli_query($koneksi, $current_kab_query);
                        $current_kab = '';
                        if ($current_kab_result && mysqli_num_rows($current_kab_result) > 0) {
                          $current_kab_row = mysqli_fetch_assoc($current_kab_result);
                          $current_kab = $current_kab_row['kab'];
                          echo "<option value=\"{$current_kab}\" selected>{$current_kab}</option>";
                        }
                        
                        // Get all cities/regencies from the alamat table
                        $kab_query = "SELECT k_kab, kab FROM alamat GROUP BY k_kab, kab";
                        $kab_result = mysqli_query($koneksi, $kab_query);
                        
                        while ($item = mysqli_fetch_assoc($kab_result)) {
                          // Only add if not already the selected option
                          if ($item['kab'] != $current_kab) {
                            echo "<option value=\"{$item['k_kab']}\">{$item['kab']}</option>";
                          }
                        }
                        ?>
                      </select>
                    </div>
                  </div>
                </div>
              </div>
              
              <!-- Buttons -->
              <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>
        </div>
      </div>
    </div>
  </div>
</section>

<!-- Scripts -->
<script type="text/javascript">
  // Phone number prefix logic
  function addPrefix(phoneInput) {
    // Get the input value
    let inputValue = phoneInput.value;
    // Check if inputValue already starts with "62"
    if (inputValue && !inputValue.startsWith('62')) {
      // Remove leading 0 if present
      if (inputValue.startsWith('0')) {
        inputValue = inputValue.substring(1);
      }
      // Add prefix "62"
      phoneInput.value = '62' + inputValue;
    }
  }

  // Letters only validation
  function harusHuruf(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode
    if ((charCode < 65 || charCode > 90) && (charCode < 97 || charCode > 122) && charCode > 32 && charCode != 46)
      return false;
    return true;
  }

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

  // Calendar popup positioning and dragging
  function positionDatepicker() {
    var input = document.getElementById('r_tgl');
    var calendar = document.getElementById('calendar-popup');
    var rect = input.getBoundingClientRect();
    
    calendar.style.position = 'absolute';
    calendar.style.left = rect.left + "px";
    
    // Check if there's enough space below the input
    var bottomSpace = window.innerHeight - rect.bottom;
    var calendarHeight = calendar.offsetHeight || 300; // Default height if not set yet
    
    if (bottomSpace < calendarHeight + 10) {
      // Not enough space below, position above the input
      calendar.style.top = (rect.top - calendarHeight - 5) + "px";
    } else {
      // Enough space below, position below the input
      calendar.style.top = (rect.bottom + 5) + "px";
    }
  }

  function pickADate(event) {
    event.preventDefault();
    event.stopPropagation();
    
    var calendar = document.getElementById('calendar-popup');
    if (calendar.style.display === 'none' || calendar.style.display === '') {
      calendar.style.display = 'block';
      positionDatepicker();
    } else {
      calendar.style.display = 'none';
    }
  }

  // Form validation and submission
  $(document).ready(function() {
    $("#simpanregister").click(function() {
      // Get form data
      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 = $('input[name="r_kelamin"]:checked').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();
      
      // Validate required fields
      var requiredFields = [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];
      
      var emptyFields = requiredFields.filter(function(field) {
        return field === "" || field === "0" || field === null || field === undefined;
      });
      
      if (emptyFields.length > 0) {
        Swal.fire({
          icon: 'error',
          title: 'Data Belum Lengkap',
          text: 'Beberapa field masih kosong, silakan lengkapi!',
          confirmButtonColor: '#3085d6'
        });
      } else {
        // All fields are filled, proceed with AJAX submission
        $.ajax({
          type: 'POST',
          url: 'simpan/simpan_register_edit.php',
          data: data,
          success: function(response) {
            console.log(response);
            
            // Show success message
            Swal.fire({
              icon: 'success',
              title: 'Alhamdulillah! Data Tersimpan',
              text: 'Data registrasi berhasil diperbarui',
              timer: 3000,
              timerProgressBar: true,
              showConfirmButton: false
            }).then((result) => {
              // Reload or redirect if needed
              // window.location.href = 'home.php?home=' + <?php echo md5("edit_registrasi"); ?>;
              
              // Or just clear/reset form
              // $('#form-simpanregister')[0].reset();
            });
          },
          error: function(error) {
            console.log('Error: ' + error);
            
            Swal.fire({
              icon: 'error',
              title: 'Gagal Menyimpan Data',
              text: 'Terjadi kesalahan saat menyimpan data. Silakan coba lagi.',
              confirmButtonColor: '#3085d6'
            });
          }
        });
      }
    });
  });
</script>
<script type="text/javascript">
  function cekhuruf(a) {
valid = /^[A-Za-z]{1,}$/;
return valid.test(a);
}
</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>

<link rel="stylesheet" href="calendar.css"/>
<script type="text/javascript" src="hijri-date.js"></script>
<script type="text/javascript" src="calendar.js"></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
    }

    // 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();
        }
    });
    </script>
</head>
</html>
