<?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-5">
                  <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>Saldo</b></td>
                        <td class="p-1"><b>:</b></td>
                        <td class="p-1"><b>Rp. <?php echo number_format($data[0]['saldo']); ?></b></td>
                      </tr>
                    </tbody>
                  </table>
                <form method="post" enctype="multipart/form-data">
                  <a type="button" class="btn btn-primary btn-sm m-1" data-toggle="modal" data-target="#staticBackdrop">Tambah Saldo</a>
                  <?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>
                </div>
                <div class="col-md-7">
                  <center>
                    <h6>Riwayat Transaksi Agen</h6>
                  </center>
                  <table id="example2" class="table table-bordered table-striped" style="zoom: 85%">
                    <thead>
                    <tr>
                      <th>Waktu</th>
                      <th>Keterangan</th>
                      <th>Debet</th>
                      <th>Kredit</th>
                      <th>Status</th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php
                      // Teknik CHUNGKING
                      $chunkSize = 200;
                      $idagen = $page[1];

                      // Query untuk menghitung total baris
                      $stmt = $pdo->prepare("SELECT COUNT(id) FROM v_detail_transaksi_per_agen WHERE id_agen_voucher = :idagen");
                      $stmt->bindValue(':idagen', $idagen, PDO::PARAM_INT);
                      $stmt->execute();
                      $totalRows = $stmt->fetchColumn();
                      for ($offset = 0; $offset < $totalRows; $offset += $chunkSize) {
                          $stmt = $pdo->prepare("SELECT id, input_time, keterangan, debet, kredit, status, expaired_time FROM v_detail_transaksi_per_agen WHERE id_agen_voucher = :idagen ORDER BY id DESC, input_time DESC LIMIT :limit OFFSET :offset");
                          $stmt->bindValue(':idagen', $idagen, PDO::PARAM_INT);
                          $stmt->bindValue(':limit', $chunkSize, PDO::PARAM_INT);
                          $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
                          $stmt->execute();
                          // Ambil data
                          $datarow = $stmt->fetchAll(PDO::FETCH_ASSOC);
                          foreach ($datarow as $row) {
                              // Format data sesuai kebutuhan
                              $inputTime = htmlspecialchars($row['input_time']);
                              $keterangan = htmlspecialchars($row['keterangan']);
                              $debet = htmlspecialchars($row['debet']);
                              $kredit = htmlspecialchars($row['kredit']);
                              $status = htmlspecialchars($row['status']);
                              $expair = htmlspecialchars($row['expaired_time']);
                              // Format debet dan kredit
                              $debetFormatted = $debet ? 'Rp. ' . number_format($debet, 0, ',', '.') : '';
                              $kreditFormatted = $kredit ? 'Rp. ' . number_format($kredit, 0, ',', '.') : '';
                              if($keterangan == "Isi Saldo"){ $exp = $inputTime; }
                              else { $exp = "Create ".$inputTime."<br> Expair ".$expair; }
                        ?>
                      <tr>
                        <td><?php echo $exp; ?></td>
                        <td style="max-width: 300px;"><?php echo $keterangan; ?></td>
                        <td><?php echo $debetFormatted; ?></td>
                        <td><?php echo $kreditFormatted; ?></td>
                        <td>
                          <?php
                            if ($row['status'] == '0') {?>
                              <a type="button" class="btn btn-danger btn-sm m-1" data-toggle="modal" data-target="#staticBackdrop<?php echo $row['id']; ?>">NUNGGAK</a>
                            <?php } elseif ($row['status'] == '1' || $row['status'] == '3') {
                              //Status transaksi agen 3 itu dari Payment Gateway, dan 1 sudah di bayar langsung
                              echo "LUNAS";
                            } else {
                              echo "SUKSES";
                            }
                          ?>
                        </td>
                      </tr>
                      <?php 
                        if ($row['status'] == '0') { ?>

                              <!-- Modal Tambah -->
                              <div class="modal fade" id="staticBackdrop<?php echo $row['id']; ?>" data-backdrop="static" data-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
                                <div class="modal-dialog">
                                  <div class="modal-content">
                                    <form method="post" enctype="multipart/form-data">
                                      <div class="modal-header bg-primary">
                                        <h5 class="modal-title" id="staticBackdropLabel">Lunasi Saldo</h5>
                                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                          <span aria-hidden="true">&times;</span>
                                        </button>
                                      </div>
                                      <div class="modal-body">
                                        <center>
                                          <h4><b><?php echo $debetFormatted; ?></b></h4>
                                        </center><hr>
                                        <div class="form-group">
                                          <label>Jenis Kas</label>
                                          <select class="form-control" name="metode1" 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="bayar<?php echo $row['id']; ?>" class="btn btn-primary" value="LUNASI">
                                      </div>
                                    </form>
                                  </div>
                                </div>
                              </div>

                            <?php
                              if (isset($_POST['bayar'.$row['id']])) {
                                $nominal = $row['debet'];
                                $waktu = date('Y-m-d H:i:s');
                                $keteranganTransaksi = "Top Up saldo agen voucher (".$data[0]['nama'].")";

                                $stmt = $pdo->prepare("UPDATE transaksi_agen_voucher SET status = '1' WHERE id = :idtrx");
                                $stmt->bindParam(':idtrx', $row['id'], PDO::PARAM_INT);
                                $stmt->execute();

                                $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);
                                $stmt->bindParam(':keterangan', $keteranganTransaksi);
                                $stmt->bindParam(':metode', $_POST['metode1']);
                                $stmt->bindParam(':pemasukan', $nominal);
                                $stmt->execute();

                                sweetAlert("Saldo agen ".$data[0]['nama']." sebesar ".$data[0]['debet']." telah LUNAS", "success");
                              } 
                            }
                      }} ?>
                    </tbody>
                  </table>
                </div>
              </div>
              <div id="form-content"></div>
            </div>
            <div class="card-footer">
              
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</section>

<!-- 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">
    <div class="modal-content">
      <form method="post" enctype="multipart/form-data">
        <div class="modal-header bg-primary">
          <h5 class="modal-title" id="staticBackdropLabel">Tambah Saldo</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>Jenis Pembayaran</label>
            <select class="form-control select2bs4" name="jenis" required="required">
              <option value="">Pilih</option>
              <option value="1">Bayar Lunas</option>
              <option value="0">Bayar Nunggak</option>
            </select>
          </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 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" class="btn btn-primary" value="Tambah">
        </div>
      </form>
    </div>
  </div>
</div>

<?php
if (isset($_POST['tambah'])) {

  $nominal = preg_replace("/[^0-9]/","",$_POST['nominal']);
  $waktu = date('Y-m-d H:i:s');
  $keteranganTransaksi = "Top Up saldo agen voucher (".$data[0]['nama'].")";
  $metode = $_POST['metode'];

  $stmt = $pdo->prepare("INSERT INTO transaksi_agen_voucher (id_data_server, id_agen_voucher, id_ganerate_voucher, debet, keterangan, status, input_time) VALUES 
    (:idds, :idagen, '0', :nominal, 'Isi Saldo', :jenis, :input_time)");
  $stmt->bindParam(':idds', $data[0]['id_data_server'], PDO::PARAM_INT);
  $stmt->bindParam(':idagen', $page[1], PDO::PARAM_INT);
  $stmt->bindParam(':nominal', $nominal);
  $stmt->bindParam(':jenis', $_POST['jenis']);
  $stmt->bindParam(':input_time', $waktu);
  $stmt->execute();

  if ($_POST['jenis'] == 1) {
    $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);
    $stmt->bindParam(':metode', $metode);
    $stmt->bindParam(':keterangan', $keteranganTransaksi);
    $stmt->bindParam(':pemasukan', $nominal);
    $stmt->execute();
  }

  $Pesan = "Saldo anda telah bertambah Rp." . number_format($nominal). "
  
  _==> Pesan Otomatis Sistem <==_";
  $APIwa = new PesanWA();
  $APIwa->Send_Pesan($data[0]['id_data_server'], 'sendMessage', [$data[0]['nomor_whatsapp']], $Pesan);

  sweetAlert("Saldo agen ".$data[0]['nama']." telah di tambah", "success");
}


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

?>