<!-- <style>
    #suggestions {
      border: 1px solid #ccc;
      max-height: 150px;
      overflow-y: auto;
      position: absolute;
      background: white;
      width: 95%;
      display: none;
      z-index: 1000;
    }

    #suggestions div {
      padding: 8px;
      cursor: pointer;
    }

    #suggestions div:hover {
      background: #f0f0f0;
    }
</style>
 -->
<style>
    .suggestion-box {
        border: 1px solid #ccc;
        max-height: 150px;
        overflow-y: auto;
        position: absolute;
        background: white;
        width: 95%;
        display: none;
        z-index: 1000;
    }

    .suggestion-box div {
        padding: 8px;
        cursor: pointer;
    }

    .suggestion-box div:hover {
        background: #f0f0f0;
    }
</style>

<?php
$nama_barang_list = array();
$nbarang = mysqli_query($con,"SELECT nama FROM v_jumlah_data_gudang $SqlDataWHId");
while ($barang = mysqli_fetch_assoc($nbarang)) {
  $nama_barang_list[] = $barang['nama'];
}
?>
<script>
    // Contoh data untuk pencarian
    const dataList = <?php echo json_encode($nama_barang_list); ?>;

    function showSuggestions() {
      const input = document.getElementById('searchInput');
      const suggestionsDiv = document.getElementById('suggestions');
      const query = input.value.toLowerCase();

      // Bersihkan saran sebelumnya
      suggestionsDiv.innerHTML = '';

      // Jika input kosong, sembunyikan saran
      if (!query) {
        suggestionsDiv.style.display = 'none';
        return;
      }

      // Filter data berdasarkan query
      const filteredData = dataList.filter(item =>
        item.toLowerCase().includes(query)
      );

      if (filteredData.length > 0) {
        // Tampilkan saran
        filteredData.forEach(item => {
          const div = document.createElement('div');
          div.textContent = item;
          div.onclick = () => {
            input.value = item; // Set nilai input
            suggestionsDiv.style.display = 'none'; // Sembunyikan saran
          };
          suggestionsDiv.appendChild(div);
        });
        suggestionsDiv.style.display = 'block';
      } else {
        suggestionsDiv.style.display = 'none';
      }
    }

    function submitForm() {
      const inputValue = document.getElementById('searchInput').value.trim();
    }

    // Klik di luar untuk menyembunyikan saran
    document.addEventListener('click', (e) => {
      const suggestionsDiv = document.getElementById('suggestions');
      if (!suggestionsDiv.contains(e.target) && e.target.id !== 'searchInput') {
        suggestionsDiv.style.display = 'none';
      }
    });
</script>

<!-- Main content -->
<section class="content" style="zoom: 90%;">
  <div class="container-fluid">
    <div class="row">
      <div class="col-12">
        <div class="card">
          <div class="card-header">
            <div class="row">
              <div class="col-sm-6">
                <h3 class="card-title">Barang di Gudang</h3>
              </div>
              <div class="col-sm-6">
                <ol class="float-sm-right mb-0">
                  <a type="button" class="btn btn-danger btn-sm m-1" data-toggle="modal" data-target="#staticBackdrop">Tambah Barang</a>
                  <a type="button" class="btn btn-warning btn-sm m-1" data-toggle="modal" data-target="#staticKurangi">Kurangi Stok</a>
                  <a type="button" class="btn btn-primary btn-sm m-1" data-toggle="modal" data-target="#staticReturn">Return Barang</a>
                </ol>
              </div>
              <!-- Modal Tambah -->
              <div class="modal fade" id="staticBackdrop" data-backdrop="static" data-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
                <div class="modal-dialog modal-xl">
                  <div class="modal-content">
                    <form method="post" enctype="multipart/form-data">
                      <div class="modal-header bg-danger">
                        <h5 class="modal-title" id="staticBackdropLabel">Tambah Barang</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                          <span aria-hidden="true">&times;</span>
                        </button>
                      </div>
                      <div class="modal-body">
                        <div class="row">
                          <div class="card-body pb-0">
                            <div class="row">
                              <div class="col-md-6">
                                <div class="form-group">
                                    <label>Nama Server</label>
                                    <select class="form-control" name="ids" required="required">
                                        <option value="">Pilih</option>
                                        <?php 
                                        $List = new Listdata();
                                        $List->set_list("data_server", $SqlDataWH);
                                        foreach ($List->get_list() as $key => $value): ?>
                                            <option value="<?php echo $value['id']; ?>"><?php echo $value['nama_server']; ?></option>
                                        <?php endforeach ?>
                                    </select>
                                </div>
                                <div class="form-group">
                                  <label for="searchInput">Nama Barang</label>
                                  <input type="text" id="searchInput" name="nama" class="form-control" placeholder="Isi Nama Barang" autocomplete="off" oninput="showSuggestions()" required="required"/>
                                  <div id="suggestions" class="suggestion-box"></div>
                                </div>
                                <div class="form-group">
                                  <label>Tanggal Pembelian</label>
                                  <input type="date" name="tanggal" class="form-control" required="required" />
                                </div>
                                <div class="row">
                                  <div class="col-6">
                                    <div class="form-group">
                                      <label>Jenis Barang</label>
                                      <select class="form-control" name="jenis" required="required">
                                        <option value="">Pilih</option>
                                        <option value="Baru">Baru</option>
                                        <option value="Bekas">Bekas</option>
                                      </select>
                                    </div>
                                  </div>
                                  <div class="col-6">
                                    <div class="form-group">
                                      <label>Jumlah Awal Barang</label>
                                      <input type="text" class="form-control" name="jumlah" required="required">
                                    </div>
                                  </div>
                                </div>
                              </div>
                              <div class="col-md-6">
                                <div class="form-group">
                                  <label>Harga Barang Satuan</label>
                                  <input type="text" class="form-control rupiah" id="rupiah0" name="nominal" required="required">
                                </div>
                                <div class="row">
                                  <div class="col-6">
                                    <div class="form-group">
                                      <label>Jenis Kas</label>
                                      <select class="form-control" name="metode_pembayaran" required="required">
                                        <option value="">Pilih</option>
                                        <option value="Bank">Bank</option>
                                        <option value="Tunai">Tunai</option>
                                        <option value="Hutang Barang">Hutang Barang</option>
                                      </select>
                                    </div>
                                  </div>
                                  <div class="col-6">
                                    <div class="form-group">
                                      <label>Penyusutan</label>
                                      <select class="form-control" name="penyusutan" required="required">
                                        <option value="">Pilih</option>
                                        <option value="1">1 Tahun</option>
                                        <option value="2">2 Tahun</option>
                                        <option value="3">3 Tahun</option>
                                        <option value="4">4 Tahun</option>
                                        <option value="5">5 Tahun</option>
                                        <option value="6">6 Tahun</option>
                                        <option value="7">7 Tahun</option>
                                        <option value="8">8 Tahun</option>
                                        <option value="9">9 Tahun</option>
                                        <option value="10">10 Tahun</option>
                                      </select>
                                    </div>
                                  </div>
                                </div>
                                <div class="form-group">
                                  <label>Keterangan</label>
                                  <textarea  class="form-control" name="keterangan" required="required" rows="5"></textarea>
                                </div>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                      <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <input type="submit" name="tambah" class="btn btn-primary" value="Tambah">
                      </div>
                    </form>
                    <?php
                   if (isset($_POST['tambah'])) {
                        $waktu = $_POST['tanggal'].date(' H:i:s');
                        $harga_satuan = preg_replace("/[^0-9]/","",$_POST['nominal']);

                        $sql = "INSERT INTO gudang (id_data_server, id_user_akses, start_time, nama, status, jenis, jumlah, keterangan, harga_satuan, penyusutan, metode_pembayaran) 
                                VALUES (:ids, :userId, :waktu, :nama, 'masuk', :jenis, :jumlah, :keterangan, :harga_satuan, :penyusutan, :metode_pembayaran)";
                        try {
                            // Prepare the statement
                            $stmt = $pdo->prepare($sql);

                            // Bind the parameters
                            $stmt->bindParam(':ids', $_POST['ids']);
                            $stmt->bindParam(':userId', $UserId); // Ensure $UserId is defined and properly initialized
                            $stmt->bindParam(':waktu', $waktu);
                            $stmt->bindParam(':nama', $_POST['nama']);
                            $stmt->bindParam(':jenis', $_POST['jenis']);
                            $stmt->bindParam(':jumlah', $_POST['jumlah']);
                            $stmt->bindParam(':keterangan', $_POST['keterangan']);
                            $stmt->bindParam(':harga_satuan', $harga_satuan);
                            $stmt->bindParam(':penyusutan', $_POST['penyusutan']);
                            $stmt->bindParam(':metode_pembayaran', $_POST['metode_pembayaran']);

                            // Execute the statement
                            $stmt->execute();

                            // Success message
                            sweetAlert("Barang telah di tambah", "success");

                        } catch (PDOException $e) {
                            // Handle error
                            echo 'Error: ' . $e->getMessage();
                        }
                    }
                    ?>
                  </div>
                </div>
              </div>
              <!-- END Modal Tambah -->
              <!-- Modal Kurangi  Stok -->
              <div class="modal fade" id="staticKurangi" data-backdrop="static" data-keyboard="false" tabindex="-1" aria-labelledby="staticTambahLabel" aria-hidden="true">
                <div class="modal-dialog modal-xl">
                  <div class="modal-content">
                    <form method="post" enctype="multipart/form-data">
                      <div class="modal-header bg-warning">
                        <h5 class="modal-title" id="staticBackdropLabel">Kurangi Stok Barang</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                          <span aria-hidden="true">&times;</span>
                        </button>
                      </div>
                      <div class="modal-body">
                        <div class="row">
                          <div class="card-body pb-0">
                            <div class="row">
                              <div class="col-md-6">
                                <div class="form-group">
                                    <label>Nama Server</label>
                                    <select class="form-control dropoption1" name="ids" required="required">
                                        <option value="">Pilih</option>
                                        <?php 
                                        $List = new Listdata();
                                        $List->set_list("data_server", $SqlDataWH);
                                        foreach ($List->get_list() as $key => $value): ?>
                                            <option value="<?php echo $value['id']; ?>"><?php echo $value['nama_server']; ?></option>
                                        <?php endforeach ?>
                                    </select>
                                </div>
                                <div class="form-group">
                                    <label>Nama Barang</label>
                                    <select class="form-control dropoption2" name="id_barang" required="required">
                                        <option value="">Pilih</option>
                                    </select>
                                </div>
                                <input type="hidden" name="nama" class="valueData">
                                <div class="form-group">
                                    <label>Waktu</label>
                                    <input type="date" class="form-control" name="waktu" required="required">
                                </div>
                              </div>
                              <div class="col-md-6">
                                <div class="form-group">
                                  <label>Jumlah</label>
                                  <input type="text" class="form-control inputJumlah" name="jumlah" required="required">
                                </div>
                                <div class="form-group">
                                  <label>Keterangan</label>
                                  <textarea  class="form-control" name="keterangan" required="required" rows="5"></textarea>
                                </div>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                      <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <input type="submit" name="kurangi" class="btn btn-primary" value="Tambah">
                      </div>
                    </form>
                    <?php
                   if (isset($_POST['kurangi'])) {
                        $waktu = $_POST['waktu'].date(' H:i:s');

                        $sql = "INSERT INTO gudang (id_data_server, id_user_akses, id_barang, start_time, nama, status, jenis, jumlah, keterangan) 
                                VALUES (:ids, :userId, :id_barang, :waktu, :nama, 'keluar', :jenis, :jumlah, :keterangan)";

                        try {
                            // Prepare the statement
                            $stmt = $pdo->prepare($sql);

                            // Bind the parameters
                            $stmt->bindParam(':ids', $_POST['ids']);
                            $stmt->bindParam(':userId', $UserId); // Ensure $UserId is defined and properly initialized
                            $stmt->bindParam(':id_barang', $_POST['id_barang']);
                            $stmt->bindParam(':waktu', $waktu);
                            $stmt->bindParam(':nama', $_POST['nama']);
                            $stmt->bindParam(':jenis', $_POST['jenis']);
                            $stmt->bindParam(':jumlah', $_POST['jumlah']);
                            $stmt->bindParam(':keterangan', $_POST['keterangan']);

                            // Execute the statement
                            $stmt->execute();

                            // Success message
                            sweetAlert("Stok ".$_POST['nama']." telah berkurang ".$_POST['jumlah'], "success");

                        } catch (PDOException $e) {
                            // Handle error
                            echo 'Error: ' . $e->getMessage();
                        }
                    }
                    ?>
                  </div>
                </div>
              </div>
              <!-- END Modal Kurangi Stok -->
              <!-- Modal Return  Stok -->
              <div class="modal fade" id="staticReturn" data-backdrop="static" data-keyboard="false" tabindex="-1" aria-labelledby="staticTambahLabel" aria-hidden="true">
                <div class="modal-dialog modal-xl">
                  <div class="modal-content">
                    <form method="post" enctype="multipart/form-data">
                      <div class="modal-header bg-primary">
                        <h5 class="modal-title" id="staticBackdropLabel">Return Barang</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                          <span aria-hidden="true">&times;</span>
                        </button>
                      </div>
                      <div class="modal-body">
                        <div class="row">
                          <div class="card-body pb-0">
                            <div class="row">
                              <div class="col-md-6">
                                <div class="form-group">
                                    <label>Nama Server</label>
                                    <select class="form-control dropoption1" name="ids" required="required">
                                        <option value="">Pilih</option>
                                        <?php 
                                        $List = new Listdata();
                                        $List->set_list("data_server", $SqlDataWH);
                                        foreach ($List->get_list() as $key => $value): ?>
                                            <option value="<?php echo $value['id']; ?>"><?php echo $value['nama_server']; ?></option>
                                        <?php endforeach ?>
                                    </select>
                                </div>
                                <div class="form-group">
                                    <label>Nama Barang</label>
                                    <select class="form-control dropoption2" name="id_barang" required="required">
                                        <option value="">Pilih</option>
                                    </select>
                                </div>
                                <input type="hidden" name="nama" class="valueReturn">
                                <div class="form-group">
                                    <label>Waktu</label>
                                    <input type="date" class="form-control" name="waktu" required="required">
                                </div>
                              </div>
                              <div class="col-md-6">
                                <div class="form-group">
                                  <label>Jumlah</label>
                                  <input type="text" class="form-control inputReturn" name="jumlah" required="required">
                                </div>
                                <div class="form-group">
                                  <label>Keterangan</label>
                                  <textarea  class="form-control" name="keterangan" required="required" rows="5"></textarea>
                                </div>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                      <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <input type="submit" name="return" class="btn btn-primary" value="Return">
                      </div>
                    </form>
                    <?php
                   if (isset($_POST['return'])) {
                        $waktu = $_POST['waktu'].date(' H:i:s');

                        $sql = "INSERT INTO gudang (id_data_server, id_user_akses, id_barang, start_time, nama, status, jenis, jumlah, keterangan) 
                                VALUES (:ids, :userId, :id_barang, :waktu, :nama, 'return', :jenis, :jumlah, :keterangan)";

                        try {
                            // Prepare the statement
                            $stmt = $pdo->prepare($sql);

                            // Bind the parameters
                            $stmt->bindParam(':ids', $_POST['ids']);
                            $stmt->bindParam(':userId', $UserId); // Ensure $UserId is defined and properly initialized
                            $stmt->bindParam(':id_barang', $_POST['id_barang']);
                            $stmt->bindParam(':waktu', $waktu);
                            $stmt->bindParam(':nama', $_POST['nama']);
                            $stmt->bindParam(':jenis', $_POST['jenis']);
                            $stmt->bindParam(':jumlah', $_POST['jumlah']);
                            $stmt->bindParam(':keterangan', $_POST['keterangan']);

                            // Execute the statement
                            $stmt->execute();

                            // Success message
                            sweetAlert("Stok ".$_POST['nama']." telah dikembalikan ".$_POST['jumlah'], "success");

                        } catch (PDOException $e) {
                            // Handle error
                            echo 'Error: ' . $e->getMessage();
                        }
                    }
                    ?>
                  </div>
                </div>
              </div>
              <!-- END Modal Return Stok -->
            </div>
          </div>
          <!-- /.card-header -->
          <div class="card-body">
            <table id="example2" class="table table-bordered table-striped">
              <thead>
              <tr>
                <th>No</th>
                <th>Tanggal Pembelian</th>
                <th>Nama Barang</th>
                <th>Harga Satuan</th>
                <th>Barang Masuk</th>
                <th>Barang Keluar</th>
                <th>Sisa Barang</th>
                <th>Nama Server</th>
                <th>Action</th>
              </tr>
              </thead>
              <tbody>
              <?php
                $no = 1;
                $aserver = mysqli_query($con,"SELECT * FROM v_jumlah_data_gudang $SqlDataWHId order by start_time DESC");
                while ($server = mysqli_fetch_assoc($aserver)) 
                {
              ?>
              <tr>
                <td style="max-width: 20px;"><?php echo $no; ?></td>
                <td style="max-width: 200px;"><?php echo $server['start_time']; ?></td>
                <td style="max-width: 200px;"><?php echo $server['nama']; ?></td>
                <td style="max-width: 200px;">Rp. <?php echo number_format($server['harga_satuan']); ?></td>
                <td style="max-width: 200px;"><?php echo $server['masuk']; ?></td>
                <td style="max-width: 200px;"><?php echo $server['keluar']; ?></td>
                <td style="max-width: 200px;"><?php echo $server['sisa']; ?></td>
                <td style="max-width: 30px;"><?php echo $server['nama_server']; ?></td>
                <td>

                  <button type="button" class="btn btn-secondary btn-sm m-1" onclick="openEditModal(<?php echo $server['id']; ?>)">Edit</button>
                  <a href="?<?php echo encrypt_url('master_stok_barang_detail|'.$server['id_data_server'].'|'.$server['id'].'|'.$server['nama']); ?>" class="btn btn-info btn-sm">Detail</a>
                </td>
              </tr>
            <?php $no ++; } ?>
              </tbody>
            </table>
          </div>
          <!-- /.card-body -->
        </div>
        <!-- /.card -->
      </div>
      <!-- /.col -->
    </div>
    <!-- /.row -->
  </div>
  <!-- /.container-fluid -->
</section>
<!-- /.content -->

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Fungsi untuk mengupdate dropdown
    function updateDropdown(dropdown, data) {
        const firstOption = dropdown.querySelector('option[value=""]');

        // Hapus semua opsi kecuali opsi pertama
        dropdown.innerHTML = '';
        if (firstOption) {
            dropdown.appendChild(firstOption.cloneNode(true));
        } else {
            dropdown.innerHTML = '<option value="">Pilih</option>';
        }

        // Tambahkan opsi baru dari data server
        data.forEach(option => {
            const optionElement = document.createElement('option');
            optionElement.value = option.id; // Set ID barang sebagai value
            optionElement.textContent = option.nama + '  ( ' + option.start_time + ' )'; // Nama untuk ditampilkan
            optionElement.setAttribute('data-nama', option.nama); // Tambahkan data-nama
            optionElement.setAttribute('data-sisa', option.sisa); // Tambahkan data-nama
            optionElement.setAttribute('data-keluar', option.keluar); // Tambahkan data-nama
            dropdown.appendChild(optionElement);
        });
    }

    // Fungsi untuk mengupdate dropdown2 berdasarkan pilihan dari dropdown1
    function updateDropdown2(form, selectedOption) {
        const dropoption2 = form.querySelector('.dropoption2');
        
        fetch(`list_data/getItemStokBarang.php?dropdown=dropoption2&option=${encodeURIComponent(selectedOption)}`)
            .then(response => response.json())
            .then(data => updateDropdown(dropoption2, data))
            .catch(error => console.error('Error fetching dropoption2 data:', error));
    }

    // Event listener untuk dropdown1
    document.addEventListener('change', function(e) {
        if (e.target.classList.contains('dropoption1')) {
            const form = e.target.closest('form');
            updateDropdown2(form, e.target.value);
        }
    });

    // Fungsi untuk memvalidasi input jumlah
    function inputJumlah(input, sisaOnly) {
        const inputValue = parseInt(input.value, 10) || 0; // Konversi ke angka, default ke 0 jika kosong atau NaN
        if (inputValue > sisaOnly) {
            input.value = sisaOnly; // Batasi input ke jumlah maksimum stok
        }
    }

    function inputReturn(input, keluarOnly) {
        const inputValue = parseInt(input.value, 10) || 0; // Konversi ke angka, default ke 0 jika kosong atau NaN
        if (inputValue > keluarOnly) {
            input.value = keluarOnly; // Batasi input ke jumlah maksimum stok
        }
    }

    // Event listener untuk dropdown2
    document.addEventListener('change', function (e) {
        if (e.target.classList.contains('dropoption2')) {
            const selectedOption = e.target.selectedOptions[0];

            // Ambil data-nama dan data-sisa dari opsi yang dipilih
            const namaOnly = selectedOption.getAttribute('data-nama');
            const sisaOnly = parseInt(selectedOption.getAttribute('data-sisa'), 10);
            const keluarOnly = parseInt(selectedOption.getAttribute('data-keluar'), 10);

            // Ambil elemen input hidden dan elemen lain
            const valueDataInput = document.querySelector('.valueData');
            if (valueDataInput) valueDataInput.value = namaOnly;

            // Ambil elemen input hidden dan elemen lain
            const valueDataReturn = document.querySelector('.valueReturn');
            if (valueDataReturn) valueDataReturn.value = namaOnly;

            // Validasi jumlah input jika ada
            const jumlahInput = document.querySelector('.inputJumlah'); // Ganti dengan kelas input jumlah Anda
            if (jumlahInput) jumlahInput.placeholder = 'Sisa Stok : ' + sisaOnly;
            if (jumlahInput) {
                jumlahInput.addEventListener('input', function () {
                    inputJumlah(jumlahInput, sisaOnly); // Panggil fungsi validasi
                });
            }

            // Validasi jumlah input jika ada
            const jumlahReturn = document.querySelector('.inputReturn'); // Ganti dengan kelas input jumlah Anda
            if (jumlahReturn) jumlahReturn.placeholder = 'Stok Keluar : ' + keluarOnly;
            if (jumlahReturn) {
                jumlahReturn.addEventListener('input', function () {
                    inputJumlah(jumlahReturn, keluarOnly); // Panggil fungsi validasi
                });
            }
        }
    });

});

</script>



<!-- MODAL EDIT BARANG -->
<div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="editModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl" role="document">
        <div class="modal-content">
            <form id="editForm" method="post">
                <div class="modal-header bg-secondary">
                    <h5 class="modal-title" id="editModalLabel">Edit Pemasukan</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                  <div class="row">
                    <div class="card-body pb-0">
                      <div class="row">
                        <div class="col-md-6">
                          <input type="hidden" name="edit_id" id="edit_id">
                          <div class="form-group">
                          <label>Nama Server</label>
                            <select class="form-control" name="ids" id="serverSelect" required>
                                <!-- Opsi akan diisi oleh JavaScript -->
                            </select>
                          </div>
                          <div class="form-group">
                            <label>Nama Barang</label>
                            <input type="text" id="namaedit" name="nama" class="form-control" placeholder="Isi Nama Barang" autocomplete="off" oninput="showSuggestion()" required="required"/>
                            <div id="suggestion" class="suggestion-box"></div>
                          </div>
                          <div class="form-group">
                            <label>Tanggal Pembelian</label>
                            <input type="date" name="tanggal" id="waktu" class="form-control" required="required" />
                          </div>
                          <div class="row">
                            <div class="col-6">
                              <div class="form-group">
                                <label>Jenis Barang</label>
                                <select class="form-control" name="jenis" id="jenis" required="required">
                                  <option value="">Pilih</option>
                                  <option value="Baru">Baru</option>
                                  <option value="Bekas">Bekas</option>
                                </select>
                              </div>
                            </div>
                            <div class="col-6">
                              <div class="form-group">
                                <label>Jumlah Awal Barang</label>
                                <input type="text" class="form-control" name="jumlah" id="jumlahbarang" required="required">
                              </div>
                            </div>
                          </div>
                        </div>
                        <div class="col-md-6">
                          <div class="form-group">
                            <label>Harga Barang Satuan</label>
                            <input type="text" class="form-control" name="nominal" id="nominal" required oninput="formatRupiah3(this)">
                          </div>
                          <div class="row">
                            <div class="col-6">
                              <div class="form-group">
                                <label>Jenis Kas</label>
                                <select class="form-control" name="metode_pembayaran" id="jenisKas" required="required">
                                  <option value="">Pilih</option>
                                  <option value="Bank">Bank</option>
                                  <option value="Tunai">Tunai</option>
                                  <option value="Hutang Barang">Hutang Barang</option>
                                </select>
                              </div>
                            </div>
                            <div class="col-6">
                              <div class="form-group">
                                <label>Penyusutan</label>
                                <select class="form-control" name="penyusutan" id="penyusutan" required="required">
                                  <option value="">Pilih</option>
                                  <option value="1">1 Tahun</option>
                                  <option value="2">2 Tahun</option>
                                  <option value="3">3 Tahun</option>
                                  <option value="4">4 Tahun</option>
                                  <option value="5">5 Tahun</option>
                                  <option value="6">6 Tahun</option>
                                  <option value="7">7 Tahun</option>
                                  <option value="8">8 Tahun</option>
                                  <option value="9">9 Tahun</option>
                                  <option value="10">10 Tahun</option>
                                </select>
                              </div>
                            </div>
                          </div>
                          <div class="form-group">
                            <label>Keterangan</label>
                            <textarea  class="form-control" name="keterangan" id="keterangan" required="required" rows="5"></textarea>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    <button type="submit" class="btn btn-warning">Edit</button>
                </div>
            </form>
        </div>
    </div>
</div>


<script>
function openEditModal(id) {
    // Fetch data menggunakan AJAX untuk ID yang dipilih
    fetch(`list_data/list_data_gudang.php?id=${id}`)
        .then(response => response.json())
        .then(data => {
            // Isi kolom formulir
            document.getElementById('edit_id').value = data.id;
            document.getElementById('namaedit').value = data.nama;
            document.getElementById('waktu').value = data.start_time.substr(0, 10);
            document.getElementById('jenis').value = data.jenis;
            document.getElementById('jumlahbarang').value = data.jumlah;
            document.getElementById('nominal').value = formatRupiah3Value3(data.harga_satuan);
            document.getElementById('jenisKas').value = data.metode_pembayaran;
            document.getElementById('penyusutan').value = data.penyusutan;
            document.getElementById('keterangan').value = data.keterangan;

            // Ambil daftar server untuk opsi select
            fetch(`list_data/dataServer.php?w=<?php echo $SqlDataWH; ?>`)
                .then(response => response.json())
                .then(servers => {
                    const serverSelect = document.getElementById('serverSelect');
                    serverSelect.innerHTML = ''; // Kosongkan opsi yang ada
                    servers.forEach(server => {
                        const option = document.createElement('option');
                        option.value = server.id;
                        option.textContent = server.nama_server;
                        if (server.id === data.id_data_server) {
                            option.selected = true; // Set opsi yang dipilih
                        }
                        serverSelect.appendChild(option);
                    });
                });
            
            // Tampilkan modal
            $('#editModal').modal('show');
        });
}

function showSuggestion() {
    const input = document.getElementById('namaedit');
    const suggestionDiv = document.getElementById('suggestion');
    const query = input.value.toLowerCase();
    suggestionDiv.innerHTML = '';

    if (!query) {
        suggestionDiv.style.display = 'none';
        return;
    }

    const filteredData = dataList.filter(item => item.toLowerCase().includes(query));
    if (filteredData.length > 0) {
        filteredData.forEach(item => {
            const div = document.createElement('div');
            div.textContent = item;
            div.onclick = () => {
                input.value = item;
                suggestionDiv.style.display = 'none';
            };
            suggestionDiv.appendChild(div);
        });
        suggestionDiv.style.display = 'block';
    } else {
        suggestionDiv.style.display = 'none';
    }
}

function formatRupiah3(input) {
    // Pastikan input adalah string
    let value = input.value.toString().replace(/[^0-9]/g, "");

    // Format menjadi Rupiah
    if (value) {
        input.value = "Rp. " + new Intl.NumberFormat('id-ID').format(value);
    } else {
        input.value = ""; // Kosongkan input jika tidak ada nilai
    }
}

function formatRupiah3Value3(value) {
    // Format nilai menjadi string Rupiah
    return "Rp. " + new Intl.NumberFormat('id-ID').format(value);
}

function deleteAlert(id) {

    const form = document.createElement("form");
    form.method = "POST";
    const input = document.createElement("input");
    input.type = "hidden";
    input.name = "hapus" + id;
    form.appendChild(input);
    document.body.appendChild(form);
    form.submit();
}
</script>

<?php
// Handle edit and delete actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['edit_id'])) {
        // Process edit
        $waktu = $_POST['tanggal'].date(' H:i:s');
        $harga_satuan = preg_replace("/[^0-9]/", "", $_POST['nominal']);

        $sql = "UPDATE gudang 
                SET id_data_server = :ids, 
                    start_time = :waktu, 
                    nama = :nama, 
                    jenis = :jenis, 
                    jumlah = :jumlah, 
                    keterangan = :keterangan, 
                    harga_satuan = :harga_satuan, 
                    penyusutan = :penyusutan, 
                    metode_pembayaran = :metode_pembayaran
                WHERE id = :id";

        try {
            // Prepare the statement
            $stmt = $pdo->prepare($sql);

            // Bind the parameters
            $stmt->bindParam(':ids', $_POST['ids']);
            $stmt->bindParam(':waktu', $waktu);
            $stmt->bindParam(':nama', $_POST['nama']);
            $stmt->bindParam(':jenis', $_POST['jenis']);
            $stmt->bindParam(':jumlah', $_POST['jumlah']);
            $stmt->bindParam(':keterangan', $_POST['keterangan']);
            $stmt->bindParam(':harga_satuan', $harga_satuan);
            $stmt->bindParam(':penyusutan', $_POST['penyusutan']);
            $stmt->bindParam(':metode_pembayaran', $_POST['metode_pembayaran']);
            $stmt->bindParam(':id', $_POST['edit_id']); // Pastikan 'edit_id' diambil dari form input hidden

            // Execute the statement
            $stmt->execute();

            // Success message
            sweetAlert("Barang telah diperbarui", "success");

        } catch (PDOException $e) {
            // Handle error
            echo 'Error: ' . $e->getMessage();
        }

    }

    $stmt = $pdo->prepare("SELECT id FROM v_transaksi WHERE pemasukan != '' $SqlDataId ");
    $stmt->execute();
    $data1 = $stmt->fetchAll(PDO::FETCH_ASSOC);
    // Handle delete
    foreach ($data1 as $server1) {
      if (isset($_POST['hapus'.$server1['id']])) {
          $idtrx = $server1['id'];
          // Call your deleteAlert function or method here
          deleteAlert("transaksi", $idtrx);
      }
    }
}
?>