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

<?php 

$stmt = $pdo->prepare("SELECT 
    SUM(CASE WHEN metode_pembayaran = 'Bank' THEN pemasukan ELSE 0 END) AS pemasukan_bank, 
    SUM(CASE WHEN metode_pembayaran != 'Bank' THEN pemasukan ELSE 0 END) AS pemasukan_kas 
FROM transaksi $SqlDataWHId");
$stmt->execute();
$neraca = $stmt->fetch(PDO::FETCH_ASSOC);

?>

 <!-- 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">Daftar Akun Transaksi</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="#modalPemasukan">Tambah</a>
                </ol>
              </div>
              <!-- Modal Tambah -->
              <div class="modal fade" id="modalPemasukan" data-backdrop="static" data-keyboard="false" tabindex="-1" aria-labelledby="modalPemasukanLabel" aria-hidden="true">
                <div class="modal-dialog modal-dialog-centered">
                  <div class="modal-content">
                    <form method="post" enctype="multipart/form-data">
                      <div class="modal-header bg-primary">
                        <h5 class="modal-title" id="modalPemasukanLabel">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="form-group">
                          <label>Nama Server</label>
                          <select class="form-control" name="ids" required>
                            <?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</label>
                          <input type="text" class="form-control" name="nama" required="required">
                        </div>
                        <div class="form-group">
                          <label>Jenis</label>
                          <select class="form-control" name="jenis" required>
                            <option value="">Piiih</option>
                            <option value="1">Pemasukan</option>
                            <option value="2">Pengeluaran</option>
                          </select>
                        </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'])) 
                    {
                      $input = mysqli_query($con,"INSERT INTO daftar_akun_transaksi (id_data_server, nama, jenis) VALUES ('$_POST[ids]', '$_POST[nama]', '$_POST[jenis]')");
                      if ($input) 
                      {
                        sweetAlert("Data akun berhasil di tambah", "success");
                      }
                    }
                    ?>
                  </div>
                </div>
              </div>
              <!-- END Modal Tambah -->
            </div>
          </div>
          <div class="card-body">
            <div class="row">
              <div class="col-md-5">
                <div class="row">
                  <div class="col-6">
                    <h5>Pemasukan</h5>
                  </div>
                  <div class="col-6 text-right">
                    
                  </div>
                </div>
                <table class="table table-bordered">
                  <thead>
                    <tr>
                      <th>Nama</th>
                      <th>Action</th>
                    </tr>
                  </thead>
                  <tbody>
                    <?php
                      $akuntran = mysqli_query($con,"SELECT * FROM daftar_akun_transaksi WHERE jenis = '1' $SqlDataId");
                      while ($akun = mysqli_fetch_assoc($akuntran)) 
                      {
                    ?>
                    <tr>
                      <td><?php echo $akun['nama'];?></td>
                      <td class="text-center">
                        <button type="button" class="btn btn-secondary btn-sm m-1" onclick="openEditModal(<?php echo $akun['id'];?>)">Edit</button>
                        <button type="button" class="btn btn-danger btn-sm m-1" onclick="deleteAlert(<?php echo $akun['id'];?>)">Hapus</button>
                      </td>
                    </tr>
                    <?php } ?>
                    <?php 
                    $akun_pengeluaran = array('Pendapatan PPPOE','Pendapatan Hotspot','Modal Tambahan','Modal Awal');
                    foreach ($akun_pengeluaran as $key) { ?>
                    <tr>
                      <td><?php echo $key; ?></td>
                      <td class="text-center">
                      </td>
                    </tr>
                    <?php } ?>
                  </tbody>
                </table>
              </div>
              <div class="col-md-4">
                <div class="row">
                  <div class="col-6">
                    <h5>Pengeluaran</h5>
                  </div>
                  <div class="col-6 text-right">
                  </div>
                </div>
                <table class="table table-bordered">
                  <thead>
                    <tr>
                      <th>Nama</th>
                      <th>Action</th>
                    </tr>
                  </thead>
                  <tbody>
                    <?php 
                    $akun_pengeluaran = array('Bayar Bandwidth','Pajak','Gaji Karyawan','Barang Habis Pakai','Pembayaran Sewa','Admin Bank','Listrik');
                    foreach ($akun_pengeluaran as $key) { ?>
                    <tr>
                      <td><?php echo $key; ?></td>
                      <td class="text-center">
                      </td>
                    </tr>
                    <?php } 

                      $akuntran = mysqli_query($con,"SELECT * FROM daftar_akun_transaksi WHERE jenis = '2' $SqlDataId");
                      while ($akun = mysqli_fetch_assoc($akuntran)) 
                      {
                    ?>
                    <tr>
                      <td><?php echo $akun['nama'];?></td>
                      <td class="text-center">
                        <button type="button" class="btn btn-secondary btn-sm m-1" onclick="openEditModal(<?php echo $akun['id']; ?>)">Edit</button>
                        <button type="button" class="btn btn-danger btn-sm m-1" onclick="deleteAlert(<?php echo $akun['id']; ?>)">Hapus</button>
                      </td>
                    </tr>
                    <?php } ?>
                  </tbody>
                </table>
              </div>
              <div class="col-md-4">
              </div>
            </div>
          </div>
        </div>
        <!-- /.card -->
      </div>
      <!-- /.col -->
    </div>
    <!-- /.row -->
  </div>
  <!-- /.container-fluid -->
</section>
<!-- /.content -->

<!-- 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 for="serverSelect">Server</label>
                                <select class="form-control" name="ids" id="serverSelect" required>
                                    <!-- Opsi akan diisi oleh JavaScript -->
                                </select>
                            </div>
                            <div class="form-group">
                                <label for="nama">Nama</label>
                                <input type="text" class="form-control" name="nama" id="nama" required>
                            </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/akunTransaksi.php?id=${id}`)
        .then(response => response.json())
        .then(data => {
            // Isi kolom formulir
            document.getElementById('edit_id').value = data.id;
            document.getElementById('nama').value = data.nama;

            // 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');
        })
        .catch(error => console.error('Error:', error));
}

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'])) {
        try {
            // Process edit
            $stmt = $pdo->prepare("UPDATE daftar_akun_transaksi SET 
                id_data_server = :ids, 
                nama = :nama
                WHERE id = :id");
            $stmt->execute([
                ':ids' => $_POST['ids'],
                ':nama' => $_POST['nama'],
                ':id' => $_POST['edit_id'],
            ]);
            sweetAlert('Data berhasil diubah', 'success');
        } catch (Exception $e) {
            sweetAlert('Terjadi kesalahan saat mengedit data: ' . $e->getMessage(), 'error');
        }
    }

    // Ambil data dari tabel untuk keperluan delete
    $stmt = $pdo->prepare("SELECT id FROM daftar_akun_transaksi $SqlDataWHId");
    $stmt->execute();
    $data1 = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Handle delete
    foreach ($data1 as $server1) {
        if (isset($_POST['hapus' . $server1['id']])) {
            $idtrx = $server1['id'];
            try {
                deleteAlert("daftar_akun_transaksi", $idtrx);
            } catch (Exception $e) {
                sweetAlert('Terjadi kesalahan saat menghapus data: ' . $e->getMessage(), 'error');
            }
        }
    }
}
?>
