<style>
    .table-responsive {
        overflow-x: hidden;
    }

    @media (max-width: 767px) { /* Untuk smartphone */
        .hide-on-mobile {
            display: none;
        }
    }

    @media (min-width: 768px) and (max-width: 1024px) { /* Untuk tablet */
        .hide-on-tablet {
            display: none;
        }
    }

    @media (min-width: 1024px) { /* Untuk laptop */
        .hide-on-laptop {
            display: none;
        }
    }
</style>
 <!-- Main content -->
<section class="content">
  <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">Pemasukan</h3>
              </div>
              <div class="col-sm-6">
                <ol class="float-sm-right mb-0">
                  <a type="button" class="btn btn-danger btn-sm" data-toggle="modal" data-target="#staticBackdrop">Tambah</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-lg">
                  <div class="modal-content">
                    <form method="post" enctype="multipart/form-data">
                      <div class="modal-header bg-primary">
                        <h5 class="modal-title" id="staticBackdropLabel">Tambah 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">
                                <div class="form-group">
                                  <label>Nama Server</label>
                                  <select class="form-control" name="ids">
                                    <?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>Tanggal</label>
                                  <input type="date" class="form-control" name="waktu" required="required">
                                </div>
                                <div class="form-group">
                                  <label>Nominal</label>
                                  <input type="text" class="form-control rupiah" id="rupiah0" name="nominal" required="required">
                                </div>
                                <div class="form-group">
                                <label>Jenis Pemasukan</label>
                                <select class="form-control" name="status" required="required">
                                  <option value="">Pilih</option>
                                  <?php 
                                  $akun_pengeluaran = array('Pendapatan PPPOE','Pendapatan Hotspot','Hutang Jangka Pendek','Hutang Jangka Panjang','Modal Tambahan','Modal Awal','Piutang Usaha','Piutang Karyawan','Piutang Lain-lain');
                                    foreach ($akun_pengeluaran as $key) { 
                                        echo '<option value="'.$key.'">'.$key.'</option>';
                                    } 
                                    $akuntran = mysqli_query($con,"SELECT * FROM daftar_akun_transaksi WHERE jenis = '1' $SqlDataId");
                                    while ($akun = mysqli_fetch_assoc($akuntran)) 
                                    { 
                                        echo '<option value="'.$akun['nama'].'">'.$akun['nama'].'</option>';
                                    } ?>
                                </select>
                                </div>
                              </div>
                              <div class="col-md-6">
                                <div class="form-group">
                                  <label>Jenis Kas</label>
                                  <select class="form-control" name="metode" required="required">
                                    <option value="">Pilih</option>
                                    <option value="Bank">Bank</option>
                                    <option value="Tunai">Tunai</option>
                                  </select>
                                </div>
                                <div class="form-group">
                                  <label>Keterangan</label>
                                  <textarea class="form-control" rows="8" name="keterangan"></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'])) 
                    {
                      $nominal = preg_replace("/[^0-9]/","",$_POST['nominal']);
                      $waktu = $_POST['waktu'].date(' H:i:s');
                      $input = mysqli_query($con,"INSERT INTO transaksi (id_data_server, id_user_akses, start_time, keterangan, pemasukan, status, metode_pembayaran) VALUES ('$_POST[ids]', '$UserId', '$waktu','$_POST[keterangan]','$nominal', '$_POST[status]', '$_POST[metode]')");
                      if ($input) 
                      {
                        sweetAlert("Pemasukan telah di tambah", "success");
                      }
                    }
                    ?>
                  </div>
                </div>
              </div>
              <!-- END Modal Tambah -->
            </div>
          </div>
  <div class="card-body">
    <div class="mb-1">
        <div class="row">
            <div class="col-4">
                <div class="dropdown dropright">
                    <a class="btn btn-warning btn-sm dropdown-toggle" href="#" role="button" data-toggle="dropdown" aria-expanded="false">
                        Filter
                    </a>
                    <div class="dropdown-menu" style="width: 250px;">
                        <div class="m-2">
                            <form id="filter-form">
                                <div class="form-group m-1">
                                    <label><small>Dari</small></label>
                                    <input type="date" class="form-control form-control-sm" id="start-date" name="start_date">
                                </div>
                                <div class="form-group">
                                    <label><small>Sampai</small></label>
                                    <input type="date" class="form-control form-control-sm" id="end-date" name="end_date">
                                </div>
                                <button type="button" class="btn btn-primary btn-sm mt-2" id="apply-filter">Terapkan</button>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-8">
                <input type="text" id="search-input" placeholder="Cari..." class="form-control form-control-sm mb-2" style="width: 200px; float: right;">
            </div>
        </div>
    </div>

    <div class="table-responsive">
        <table class="table table-bordered table-striped" id="data-table">
            <thead>
                <tr>
                    <th>No</th>
                    <th>Nama Server</th>
                    <th>Time</th>
                    <th class="hide-on-mobile">Keterangan</th>
                    <th class="hide-on-mobile">Nominal</th>
                    <th class="hide-on-mobile hide-on-tablet">Jenis Kas</th>
                    <th class="hide-on-mobile hide-on-tablet">Status</th>
                    <th class="hide-on-mobile hide-on-tablet">Action</th>
                </tr>
            </thead>
            <tbody id="table-body">
                <!-- Data akan dimuat di sini -->
            </tbody>
        </table>
    </div>

    <div id="loader" style="display:none;">Loading...</div>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

    <script>
    let offset = 0; // Offset untuk memuat data
    const limit = 25; // Jumlah data per permintaan
    let loading = false;

    // Fungsi untuk memuat data
    function loadMoreData(searchTerm = '', startDate = '', endDate = '', idS = <?php echo "'".$SvId."'"; ?>) {
        if (loading) return; // Jangan panggil lagi jika sedang memuat
        loading = true;
        $('#loader').show();

        $.ajax({
            url: 'list_data/list_pemasukan.php',
            type: 'GET',
            data: { offset: offset, search: searchTerm, start_date: startDate, end_date: endDate, ids: idS }, // Tambahkan parameter pencarian dan filter
            success: function(response) {
                const result = JSON.parse(response);
                const data = result.data;

                if (data.length > 0) {
                    data.forEach((server, index) => {
                        // Data yang akan ditampilkan
                        let truncatedData = {
                            nama_server: server.nama_server,
                            start_time: server.start_time,
                            keterangan: server.keterangan,
                            pemasukan: server.pemasukan,
                            metode_pembayaran: server.metode_pembayaran,
                            status: server.status,
                            nama: server.nama,
                            id: server.id // Ambil ID server
                        };

                        let row = `
                            <tr>
                                <td>
                                    ${offset + index + 1}
                                    <br>
                                    <button type="button" class="btn collapsed btn-sm m-0 p-0 hide-on-laptop" data-toggle="collapse" data-target="#collapse-row-${offset + index}" aria-expanded="false" onclick="toggleCollapse(this, '${offset + index}')">
                                        <i class="fas fa-plus-circle text-primary"></i>
                                    </button>
                                </td>
                                <td>${truncatedData.nama_server}</td>
                                <td>${truncatedData.start_time}</td>
                                <td class="hide-on-mobile">${truncatedData.keterangan} ${truncatedData.nama ? `(${truncatedData.nama})` : ''}</td>
                                <td class="hide-on-mobile">${truncatedData.pemasukan ? 'Rp. ' + Number(truncatedData.pemasukan).toLocaleString() : ''}</td>
                                <td class="hide-on-mobile hide-on-tablet">${truncatedData.metode_pembayaran}</td>
                                <td class="hide-on-mobile hide-on-tablet">${truncatedData.status}</td>
                                <td class="hide-on-mobile hide-on-tablet">
                                    ${truncatedData.metode_pembayaran !== 'API Payment' ? `
                                        <button type="button" class="btn btn-secondary btn-sm m-1" onclick="openEditModal(${truncatedData.id})">Edit</button>
                                        <button type="button" class="btn btn-danger btn-sm m-1" onclick="deleteAlert(${truncatedData.id})">Hapus</button>
                                    ` : ''}
                                </td>
                            </tr>
                            <tr class="collapse hide-on-laptop" id="collapse-row-${offset + index}">
                                <td colspan="5" class="p-0">
                                    <table class="table table-borderless" width="100%">
                                        <tbody>
                                            <tr class="hide-on-tablet hide-on-laptop">
                                                <th>Keterangan</th>
                                                <td>${truncatedData.keterangan} ${truncatedData.nama ? `(${truncatedData.nama})` : ''}</td>
                                            </tr>
                                            <tr class="hide-on-tablet hide-on-laptop">
                                                <th>Kas Masuk</th>
                                                <td>${truncatedData.pemasukan ? 'Rp. ' + Number(truncatedData.pemasukan).toLocaleString() : ''}</td>
                                            </tr>
                                            <tr class="hide-on-laptop">
                                                <th>Jenis Kas</th>
                                                <td>${truncatedData.metode_pembayaran}</td>
                                            </tr>
                                            <tr class="hide-on-laptop">
                                                <th>Status</th>
                                                <td>${truncatedData.status}</td>
                                            </tr>
                                            <tr class="hide-on-laptop">
                                                <td colspan="2">
                                                    ${truncatedData.metode_pembayaran !== 'API Payment' ? `
                                                        <button type="button" class="btn btn-secondary btn-sm m-1" onclick="openEditModal(${truncatedData.id})">Edit</button>
                                                        <button type="button" class="btn btn-danger btn-sm m-1" onclick="deleteAlert(${truncatedData.id})">Hapus</button>
                                                    ` : ''}
                                                </td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </td>
                            </tr>`;

                        $('#table-body').append(row);
                    });
                    offset += data.length; // Update offset
                }
                $('#loader').hide();
                loading = false; // Set loading ke false
            },
            error: function() {
                $('#loader').hide();
                loading = false;
                alert('Error loading data');
            }
        });
    }

    // Fungsi untuk toggle collapse dan mengubah ikon
    function toggleCollapse(button, index) {
        const $target = $(`#collapse-row-${index}`);
        const isCollapsed = $target.hasClass('show');

        // Toggle collapse
        $target.collapse('toggle');

        // Ubah ikon
        if (isCollapsed) {
            $(button).find('i').removeClass('fa-minus-circle text-danger').addClass('fa-plus-circle text-primary');
        } else {
            $(button).find('i').removeClass('fa-plus-circle text-primary').addClass('fa-minus-circle text-danger');
        }
    }

    // Fungsi untuk menangani input pencarian
    $('#search-input').on('input', function() {
        const searchTerm = $(this).val();
        offset = 0; // Reset offset saat pencarian
        $('#table-body').empty(); // Kosongkan tabel
        loadMoreData(searchTerm, $('#start-date').val(), $('#end-date').val()); // Muat data berdasarkan pencarian dan filter
    });

    // Fungsi untuk menerapkan filter berdasarkan tanggal
    $('#apply-filter').on('click', function() {
        const startDate = $('#start-date').val();
        const endDate = $('#end-date').val();
        offset = 0; // Reset offset saat filter diterapkan
        $('#table-body').empty(); // Kosongkan tabel
        loadMoreData($('#search-input').val(), startDate, endDate); // Muat data berdasarkan filter
    });

    // Panggil fungsi saat scroll
    $(window).scroll(function() {
        if ($(window).scrollTop() + $(window).height() >= $(document).height() - 100) {
            loadMoreData($('#search-input').val(), $('#start-date').val(), $('#end-date').val()); // Panggil dengan parameter pencarian dan filter
        }
    });

    // Muat data pertama kali saat halaman dimuat
    $(document).ready(function() {
        loadMoreData();
    });
    </script>
</div>

<!-- Edit Modal -->
<div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="editModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" 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="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>Tanggal</label>
                          <input type="date" class="form-control" name="waktu" id="waktu" required>
                      </div>
                      <div class="form-group">
                          <label>Nominal</label>
                          <input type="text" class="form-control" name="nominal" id="nominal" required oninput="formatRupiah3(this)">
                      </div>
                      <div class="form-group">
                        <label>Jenis Pemasukan</label>
                        <select class="form-control" name="status" id="akunSelect" required>
                             <!-- Opsi akan diisi oleh JavaScript -->
                        </select>
                      </div>
                    </div>
                    <div class="col-md-6">
                      <div class="form-group">
                        <label>Jenis Kas</label>
                        <select class="form-control" name="metode" id="jenisKas" required="required">
                          <option value="">Pilih</option>
                          <option value="Bank">Bank</option>
                          <option value="Tunai">Tunai</option>
                        </select>
                      </div>
                      <div class="form-group">
                          <label>Keterangan</label>
                          <textarea class="form-control" rows="8" name="keterangan" id="keterangan"></textarea>
                      </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/Transaksi.php?id=${id}`)
        .then(response => response.json())
        .then(data => {
            // Isi kolom formulir
            document.getElementById('edit_id').value = data.id;
            document.getElementById('waktu').value = data.start_time.substr(0, 10);
            document.getElementById('nominal').value = formatRupiah3Value3(data.pemasukan); // Format saat mengisi nilai
            document.getElementById('keterangan').value = data.keterangan;

            // Set pilihan Jenis Kas
            document.getElementById('jenisKas').value = data.metode_pembayaran; // Asumsi jenis_kas ada di response

            // 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);
                    });
                });

            // Ambil daftar server untuk opsi select
            fetch(`list_data/dataAkun.php?w=<?php echo $SqlDataWH; ?>&j=1`)
                .then(response => response.json())
                .then(servers => {
                    const serverSelect = document.getElementById('akunSelect');
                    serverSelect.innerHTML = ''; // Kosongkan opsi yang ada
                    servers.forEach(akun => {
                        const option = document.createElement('option');
                        option.value = akun.nama;
                        option.textContent = akun.nama;
                        if (akun.nama === data.status) {
                            option.selected = true; // Set opsi yang dipilih
                        }
                        serverSelect.appendChild(option);
                    });
                });

            // Tampilkan modal
            $('#editModal').modal('show');
        });
}

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
        $nominal = preg_replace("/[^0-9]/", "", $_POST['nominal']);
        $waktu = $_POST['waktu'].date(' H:i:s');
        $stmt = $pdo->prepare("UPDATE transaksi SET 
            id_data_server = :ids, 
            keterangan = :keterangan, 
            start_time = :waktu, 
            pemasukan = :nominal,
            metode_pembayaran = :metode_pembayaran,
            status = :status 
            WHERE id = :id");
        $stmt->execute([
            ':ids' => $_POST['ids'],
            ':keterangan' => $_POST['keterangan'],
            ':waktu' => $waktu,
            ':nominal' => $nominal,
            ':id' => $_POST['edit_id'],
            ':metode_pembayaran' => $_POST['metode'],
            ':status' => $_POST['status']
        ]);
        sweetAlert('Data berhasil diubah', 'success');
    }
    $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);
      }
    }
}
?>
        </div>
        <!-- /.card -->
      </div>
      <!-- /.col -->
    </div>
    <!-- /.row -->
  </div>
  <!-- /.container-fluid -->
</section>
<!-- /.content -->