<?php 
$stmt = $pdo->prepare("SELECT * FROM v_detail_agen_voucher WHERE id = '$page[1]'");
$stmt->execute();
$data = $stmt->fetchAll();
?>
<section class="content">
  <div class="container-fluid">
    <div class="row">
      <div class="col-12">
        <div class="card">
          <div class="card-header bg-info">
            <div class="row">
              <div class="col-sm-6">
                <h5>Detail Agen Voucher</h5>
              </div>
              <div class="col-sm-6"></div>
            </div>
          </div>
          <!-- /.card-header -->
          <div class="card-body">
             <div class="row">
                <div class="col-md-6">
                  <table class="table table-borderless">
                    <tbody>
                      <tr>
                        <td class="p-1">Status</td>
                        <td class="p-1">:</td>
                        <td class="p-1">
                          <?php 
                            if($data[0]['status'] == 'Aktif') {
                              echo '<div class="badge badge-success p-2">Aktif</div>';
                            } else {
                              echo '<div class="badge badge-danger p-2">Tidak Aktif</div>';
                            }
                          ?>
                        </td>
                      </tr>
                      <tr>
                        <td class="p-1">Server</td>
                        <td class="p-1">:</td>
                        <td class="p-1"><?php echo $data[0]['nama_server']; ?></td>
                      </tr>
                      <tr>
                        <td class="p-1">Mikrotik</td>
                        <td class="p-1">:</td>
                        <td class="p-1"><?php echo $data[0]['nama_mikrotik']; ?></td>
                      </tr>
                      <tr>
                        <td class="p-1">Kode Agen</td>
                        <td class="p-1">:</td>
                        <td class="p-1"><?php echo $data[0]['kode_agen']; ?></td>
                      </tr>
                      <tr>
                        <td class="p-1">Email</td>
                        <td class="p-1">:</td>
                        <td class="p-1"><?php echo $data[0]['email']; ?></td>
                      </tr>
                      <tr>
                        <td class="p-1">Nama</td>
                        <td class="p-1">:</td>
                        <td class="p-1"><?php echo $data[0]['nama']; ?></td>
                      </tr>
                      <tr>
                        <td class="p-1">Alamat</td>
                        <td class="p-1">:</td>
                        <td class="p-1"><?php echo $data[0]['alamat']; ?></td>
                      </tr>
                      <tr>
                        <td class="p-1">Nomor WhatsApp</td>
                        <td class="p-1">:</td>
                        <td class="p-1"><?php echo $data[0]['nomor_whatsapp']; ?></td>
                      </tr>
                      <tr>
                        <td class="p-1">Last Login</td>
                        <td class="p-1">:</td>
                        <td class="p-1"><?php echo $data[0]['last_login']; ?></td>
                      </tr>
                      <tr style="border-top: 1px solid #d3d3d3;">
                        <td class="p-1"><b>Total Transaksi</b></td>
                        <td class="p-1"><b>:</b></td>
                        <td class="p-1"><b>Rp. <?php echo substr(number_format($data[0]['saldo']),1); ?></b></td>
                      </tr>
                    </tbody>
                  </table>
                <form method="post" enctype="multipart/form-data">
                  <?php if($data[0]['status'] == "Aktif") { ?>
                  <input type="submit" name="off" class="btn btn-danger btn-sm m-1" value="Non Aktifkan Agen">
                  <?php } else { ?>
                  <input type="submit" name="on" class="btn btn-success btn-sm m-1" value="Aktifkan Agen">
                  <?php } ?>
                </form>
                <center>
                  <h6>Riwayat Transaksi Agen</h6>
                </center>
                  <table class="table table-bordered table-striped table-sm mt-4">
                    <thead>
                        <tr>
                            <th>Bulan</th>
                            <th>Transaksi</th>
                            <th>Belum Dibayar</th>
                            <th>Status</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php
                        $nom = 1;
                        $stmt = $pdo->prepare("SELECT * FROM v_detail_agen_pascabayar WHERE id_agen_voucher = :idagen ORDER BY generate_time DESC");
                        $stmt->bindValue(':idagen', $page[1], PDO::PARAM_INT);
                        $stmt->execute();

                        // Ambil data
                        $datadetail = $stmt->fetchAll(PDO::FETCH_ASSOC);
                        foreach ($datadetail as $rows) {
                            $stmtBayar = $pdo->prepare("SELECT debet, input_time FROM transaksi_agen_voucher WHERE SUBSTR(generate_time, 1, 7) = :generate_time AND id_agen_voucher = :idagen AND (debet IS NOT NULL AND debet != '')");
                            $stmtBayar->bindValue(':generate_time', substr($rows['generate_time'], 0, 7), PDO::PARAM_STR);
                            $stmtBayar->bindValue(':idagen', $page[1], PDO::PARAM_INT);
                            $stmtBayar->execute();

                            // Ambil data
                            $datadetailbayar = $stmtBayar->fetchAll(PDO::FETCH_ASSOC);
                    ?>
                            <tr>
                                <td><?php echo substr(formatIndo($rows['generate_time']), 3); ?></td>
                                <td>Rp. <?php echo number_format($rows['kredit']); ?></td>
                                <td>Rp. <?php echo number_format($rows['saldo']); ?></td>
                                <td class="text-center">
                                    <?php echo ($rows['kredit'] == $rows['debet']) ? '<span class="badge badge-success">LUNAS</span>' : '<span class="badge badge-danger">PENDING</span>'; ?>
                                </td>
                                <td class="text-center">
                                    <a type="button" class="badge badge-info m-1" data-toggle="modal" data-target="#staticBackdrop<?php echo $nom; ?>">Bayar</a>
                                    <a href="#" class="badge badge-secondary m-1" data-toggle="collapse" data-target="#collapse-<?php echo $nom; ?>" aria-expanded="false" aria-controls="collapse-<?php echo $nom; ?>">Detail</a>
                                </td>
                            </tr>
                            <tr class="collapse" id="collapse-<?php echo $nom; ?>">
                                <td colspan="5" class="p-0">
                                    <i><u><small>Riwayat Pembayaran</small></u></i>
                                    <table class="table-bordered table-sm" width="100%">
                                        <tbody>
                                        <?php foreach ($datadetailbayar as $rowbayar) { ?>
                                            <tr class="bg-white">
                                                <td>=> <?php echo $rowbayar['input_time']; ?></td>
                                                <td>Rp. <?php echo number_format($rowbayar['debet']); ?></td>
                                            </tr>
                                        <?php } ?>
                                        </tbody>
                                    </table>
                                </td>
                            </tr>
                    <!-- Modal Tambah -->
                    <div class="modal fade" id="staticBackdrop<?php echo $nom; ?>" data-backdrop="static" data-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" 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="staticBackdropLabel">Bayar Bulan <?php echo substr(formatIndo($rows['generate_time']), 3); ?></h5>
                              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                              </button>
                            </div>
                            <div class="modal-body" style="background-color: rgb(240, 240, 240); text-align: left;">
                              Total Pembayaran
                              <h4><b>Rp. <?php echo number_format($rows['saldo']); ?></b></h4>
                            </div>
                            <div class="modal-body">
                              <div class="form-group">
                                <label>Nominal Pembayaran</label>
                                <input type="text" class="form-control rupiah" id="rupiah0" name="nominal" required="required">
                                <i class="text-danger"><small>Tidak boleh melebihi nominal di atas</small></i>
                              </div>
                              <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>
                            <div class="modal-footer">
                              <input type="submit" name="tambah<?php echo $nom; ?>" class="btn btn-primary" value="Bayar">
                            </div>
                          </form>
                        </div>
                      </div>
                    </div>
                    <?php 
                    
                      // Pastikan $nom di-set sebelumnya
                      if (isset($_POST['tambah' . $nom])) {
                          // Mengambil nilai nominal dan memfilter hanya angka
                          $nominal = preg_replace("/[^0-9]/", "", $_POST['nominal']);

                          // Validasi nominal dan pengecekan lebih lanjut
                          if ($nominal > $rows['saldo']) {
                              sweetAlert("Gagal: Nominal melebihi total pembayaran", "error");
                          } else {
                              // Ambil waktu saat ini
                              $waktu = date('Y-m-d H:i:s');

                              // Keterangan transaksi
                              $keteranganTransaksi = "Pembayaran agen voucher (" . $data[0]['nama'] . ")";

                              // Ambil metode pembayaran dari POST
                              $metode = $_POST['metode'];

                              try {
                                //   $generate_time = $rows['generate_time'].date('-d');
                                  $generate_time = date('Y-m-t', strtotime($rows['generate_time']));
                                  // Menyimpan transaksi agen voucher
                                  $stmt = $pdo->prepare("INSERT INTO transaksi_agen_voucher (id_data_server, id_agen_voucher, id_ganerate_voucher, debet, keterangan, status, input_time, generate_time) VALUES (:idds, :idagen, '0', :nominal, 'Pembayaran Agen', :jenis, :input_time, :generate_time)");

                                  $stmt->bindParam(':idds', $data[0]['id_data_server'], PDO::PARAM_INT);
                                  $stmt->bindParam(':idagen', $page[1], PDO::PARAM_INT);
                                  $stmt->bindParam(':nominal', $nominal, PDO::PARAM_INT); // Pastikan nominal di-bind sebagai integer
                                  $stmt->bindParam(':jenis', $_POST['jenis'], PDO::PARAM_STR); // Bind jenis sebagai string
                                  $stmt->bindParam(':input_time', $waktu, PDO::PARAM_STR);
                                  $stmt->bindParam(':generate_time', $generate_time, PDO::PARAM_STR);
                                  $stmt->execute();

                                  // Menyimpan transaksi umum
                                  $sql = "INSERT INTO transaksi (id_data_server, id_user_akses, start_time, keterangan, pemasukan, metode_pembayaran, status) 
                                          VALUES (:idds, '0', :start_time, :keterangan, :pemasukan, :metode, 'Pendapatan Hotspot')";
                                  $stmt = $pdo->prepare($sql);

                                  $stmt->bindParam(':idds', $data[0]['id_data_server'], PDO::PARAM_INT);
                                  $stmt->bindParam(':start_time', $waktu, PDO::PARAM_STR);
                                  $stmt->bindParam(':metode', $metode, PDO::PARAM_STR);
                                  $stmt->bindParam(':keterangan', $keteranganTransaksi, PDO::PARAM_STR);
                                  $stmt->bindParam(':pemasukan', $nominal, PDO::PARAM_INT); // Bind nominal sebagai integer
                                  $stmt->execute();

// Mengirim pesan WhatsApp
$Pesan = "Pembayaran Rp." . number_format($nominal) . " Telah kami terima, Terimakasih.

_==> Pesan Otomatis Sistem <==_";
                                  $APIwa = new PesanWA();
                                  $APIwa->Send_Pesan($data[0]['id_data_server'], 'sendMessage', [$data[0]['nomor_whatsapp']], $Pesan);

                                  // Tampilkan pesan sukses
                                  sweetAlert("Proses berhasil", "success");
                              } catch (PDOException $e) {
                                  // Menangani error dalam eksekusi query
                                  // sweetAlert("Gagal: Terjadi kesalahan pada proses transaksi", "error");
                                  echo "Error: " . $e->getMessage();
                              }
                          }
                      }

                            $nom++; 
                        } 
                    ?>
                    </tbody>
                </table>
                </div>
                <div class="col-md-6">
                  <center>
                    <h6>Riwayat Generate Voucher</h6>
                  </center>
                  <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>Voucher</th>
                                    <th>Harga</th>
                                    <th>Dibuat</th>
                                    <th>Awal Digunakan</th>
                                    <th>Kadaluarsa</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 (ubah menjadi 25)
let loading = false;

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

    $.ajax({
        url: 'list_data/list_generate_voucher.php',
        type: 'GET',
        data: {
            offset: offset, 
            limit: limit,  // Menambahkan parameter limit
            search: searchTerm, 
            start_date: startDate, 
            end_date: endDate, 
            id: id
        },
        success: function(response) {
            const result = response.data;  // Ambil data yang diterima
            if (result.length > 0) {
                let nomor = offset + 1; // Mulai nomor urut dari offset + 1
                result.forEach((voucher) => {
                    // Menambahkan baris baru ke dalam tabel
                    let row = `
                        <tr>
                            <td>${nomor}</td> <!-- Menampilkan nomor urut -->
                            <td>${voucher.voucher}</td>
                            <td style="min-width: 100px;">Rp. ${parseInt(voucher.harga).toLocaleString()}</td>
                            <td>${voucher.create_time}</td>
                            <td>${voucher.active_time}</td>
                            <td>${voucher.expaired_time}</td>
                        </tr>`;

                    $('#table-body').append(row);
                    nomor++; // Increment nomor untuk baris berikutnya
                });
                offset += result.length;  // Update offset setelah data dimuat
            } else {
                // Jika tidak ada data
                $('#loader').hide();
            }
            $('#loader').hide();
            loading = false;
        },
        error: function() {
            $('#loader').hide();
            loading = false;
            alert('Error loading data');
        }
    });
}

// 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>
                </div>
              </div>
              <div id="form-content"></div>
            </div>
            <div class="card-footer">
              
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</section>

<?php

if (isset($_POST['off'])) {
  $status = "Non Aktif";
  $stmt = $pdo->prepare("UPDATE agen_voucher SET status = :status WHERE id = :idagen");
  $stmt->bindParam(':status', $status);
  $stmt->bindParam(':idagen', $page[1], PDO::PARAM_INT);
  $stmt->execute();

  sweetAlert("Agen ".$data[0]['nama']." telah di Non Aktifkan", "success");
}

if (isset($_POST['on'])) {
  $status = "Aktif";
  $stmt = $pdo->prepare("UPDATE agen_voucher SET status = :status WHERE id = :idagen");
  $stmt->bindParam(':status', $status);
  $stmt->bindParam(':idagen', $page[1], PDO::PARAM_INT);
  $stmt->execute();

  sweetAlert("Agen ".$data[0]['nama']." telah di Aktifkan", "success");
}

?>