<?php
// Periksa dan amankan input query
$idtag = isset($page[1]) ? (int)$page[1] : 0;
// Ambil data dari database
$stmt = $pdo->prepare("SELECT * FROM v_tagihan WHERE $SqlSvData id = :id");
$stmt->bindParam(':id', $idtag, PDO::PARAM_INT);
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);

if (empty($data)) {
    echo "Data tidak ditemukan.";
    exit;
}
$datakonpensasi = ($data[0]['konpensasi'] == 0) ? $data[0]['jumlah_konpensasi'] : 0;
?>

<section class="content">
  <div class="container-fluid">
    <div class="row">
      <div class="col-12">
        <div class="card">
          <div class="card-header bg-primary">
            <div class="row">
              <div class="col-sm-6">
                <h5>Bayar Tagihan</h5>
              </div>
              <div class="col-sm-6"></div>
            </div>
          </div>
          <!-- /.card-header -->
          <div class="card-body">
              <div class="row">
                  <div class="col-md-8">
                      <table class="table table-borderless">
                          <tbody>
                              <tr>
                                <td class="p-1">Status Tagihan</td>
                                <td class="p-1">:</td>
                                <td class="p-1">
                                  <?php 
                                    $status = $data[0]['status'];
                                    if ($status == 'buat') {
                                        echo '<div class="badge badge-warning">Akan datang</div>';
                                    } elseif ($status == 'nunggak') {
                                        echo '<div class="badge badge-danger">Tunggakan</div>';
                                    } elseif ($status == 'lunas') {
                                        echo '<div class="badge badge-success">Telah dibayar</div>';
                                    } else {
                                        echo '<div class="badge badge-primary">Sedang Berjalan</div>';
                                    }
                                  ?>
                                </td>
                              </tr>
                              <tr>
                                <td class="p-1">Id Pelanggan</td>
                                <td class="p-1">:</td>
                                <td class="p-1"><?php echo htmlspecialchars($data[0]['akun']); ?></td>
                              </tr>
                              <tr>
                                <td class="p-1">Nama</td>
                                <td class="p-1">:</td>
                                <td class="p-1"><?php echo htmlspecialchars($data[0]['nama']); ?></td>
                              </tr>
                              <tr>
                                <td class="p-1">Alamat</td>
                                <td class="p-1">:</td>
                                <td class="p-1"><?php echo htmlspecialchars($data[0]['alamat']); ?></td>
                              </tr>
                              <tr>
                                <td class="p-1">Jenis Layanan</td>
                                <td class="p-1">:</td>
                                <td class="p-1"><?php echo htmlspecialchars($data[0]['jenis_layanan']); ?></td>
                              </tr>
                              <tr>
                                <td class="p-1">Keterangan Tagihan</td>
                                <td class="p-1">:</td>
                                <td class="p-1"><?php echo htmlspecialchars($data[0]['keterangan']); ?></td>
                              </tr>
                              <tr>
                                <td class="p-1">Paket Berlangganan</td>
                                <td class="p-1">:</td>
                                <td class="p-1"><?php echo htmlspecialchars($data[0]['nama_paket']); ?></td>
                              </tr>
                              <tr>
                                <td class="p-1">Harga Layanan</td>
                                <td class="p-1">:</td>
                                <td class="p-1">Rp. <?php echo number_format($data[0]['nominal_tagihan'], 0, ',', '.'); ?></td>
                              </tr>
                              <tr>
                                <td class="p-1">Jumlah Potongan</td>
                                <td class="p-1">:</td>
                                <td class="p-1">Rp. <?php echo number_format($data[0]['jumlah_konpensasi'], 0, ',', '.'); ?></td>
                              </tr>
                              <tr>
                                <td class="p-1">Jumlah Tagihan</td>
                                <td class="p-1">:</td>
                                <td class="p-1">Rp. <?php echo number_format($data[0]['jumlah_tagihan'], 0, ',', '.'); ?></td>
                              </tr>
                              <tr>
                                <td class="p-1">PPN 11%</td>
                                <td class="p-1">:</td>
                                <td class="p-1">Rp. <?php echo number_format($data[0]['ppn'], 0, ',', '.'); ?></td>
                              </tr>   
                              <?php 
                              if($data[0]['kode_unik'] != '0') { ?>
                              <tr>
                                <td class="p-1">Subsidi</td>
                                <td class="p-1">:</td>
                                <td class="p-1">Rp. <?php echo number_format($data[0]['kode_unik'], 0, ',', '.'); ?></td>
                              </tr>
                              <?php } ?>
                              <tr>
                                <td class="p-1"><b>Total Tagihan</b></td>
                                <td class="p-1">:</td>
                                <td class="p-1"><b>Rp. <?php echo number_format($data[0]['verifikasi_tagihan'], 0, ',', '.'); ?></b></td>
                              </tr>
                          </tbody>
                      </table>
                  </div>
                  <div class="col-md-4">
                      <form method="post" enctype="multipart/form-data">
                          <div class="form-group">
                              <label>Upload Bukti Pembayaran</label>
                              <div class="uploadImage" data-id="tag<?php echo htmlspecialchars($data[0]['id']); ?>">
                                  <span>Click to upload image</span>
                                  <img src="#" alt="Image preview">
                                  <div class="progressContainer">
                                      <div class="progressBar"></div>
                                  </div>
                              </div>
                          </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 class="form-group">
                              <label for="tanggal">Tanggal Pembayaran</label>
                              <div class="row align-items-center">
                                  <div class="col-6">
                                      <input class="form-control" type="date" id="tanggal" name="tanggal">
                                  </div>
                                  <div class="col-2">
                                      <select class="form-control" id="jam" name="jam"></select>
                                  </div>
                                  <div class="col-2">
                                      <select class="form-control" id="menit" name="menit"></select>
                                  </div>
                                  <div class="col-2">
                                      <select class="form-control" id="detik" name="detik"></select>
                                  </div>
                              </div>
                          </div>
                          <input type="hidden" id="formatted_datetime" name="formatted_datetime">
                          <div class="form-group m-1">
                              <label>Catatan</label>
                              <textarea class="form-control" name="catatan" rows="3"></textarea>
                              <i class="text-danger"><small>Isi jika di perlukan</small></i>
                          </div>
                          <div class="modal-footer">
                              <input type="submit" name="bayar" class="btn btn-primary btn-sm m-1" value="Bayar Tagihan">
                          </div>
                      </form>
                      <?php
                    //   echo date('d-m-Y');
                      if (isset($_POST['bayar'])) {
                        //   echo "<pre>";
                        //   print_r($_POST);
                        //   echo "</pre>";
                          try {
                              if (!isset($_SESSION['uploaded_files']) || empty($data[0])) {
                                  throw new Exception('Data tidak lengkap.');
                              }

                              $bukti = $_SESSION['uploaded_files']['tag' . $data[0]['id']] ?? '';

                              if (empty($bukti)) {
                                  throw new Exception('Bukti pembayaran tidak tersedia.');
                              }

                              // Pastikan variabel berikut sudah didefinisikan sebelumnya
                              $user = $data[0]['akun'];
                              $userHs = $data[0]['user_hotspot'];
                              $nama = $data[0]['nama']; // Contoh nama
                              $nominal = $data[0]['verifikasi_tagihan']; // Contoh nominal
                              $keterangan = 'Pembayaran '.$data[0]['keterangan']; // Contoh keterangan
                              $invoice = 'kwitansi_'.date('Ymd').$idtag.'.png'; // Nama file output
                              $paketint = $data[0]['nama_paket'];
                              $tagihan = 'Rp. '.number_format($data[0]['jumlah_tagihan'], 0, ',', '.');
                              $ppn = 'Rp. '.number_format($data[0]['ppn'], 0, ',', '.');
                              $subsidi = 'Rp. '.number_format($data[0]['kode_unik'], 0, ',', '.');
                              // Buat gambar dari file PNG yang ada
                              $stmt = $pdo->prepare("SELECT backround_kwitansi FROM data_server WHERE id = :id");
                              $stmt->bindParam(':id', $data[0]['id_data_server'], PDO::PARAM_INT);
                              $stmt->execute();
                              $result = $stmt->fetch(PDO::FETCH_ASSOC);
                              $gambarKwitansi = 'img/'.$result['backround_kwitansi']; // Pastikan variabel
                              $tanggalbayar = $_POST['formatted_datetime'];
                            
                              // $img = imagecreatefrompng($gambarKwitansi);
                              // // Buat beberapa warna
                              // $white = imagecolorallocate($img, 245, 245, 245);
                              // $black = imagecolorallocate($img, 0, 0, 0);
                              // $orange = imagecolorallocate($img, 0, 0, 128);
                              // $fontPath = 'dist/X_10x20_LE.gdf';
                              // $font = imageloadfont($fontPath);
                              // $line = '_____________________________________________________________________________________';
                              // imagestring($img, $font, 320, 30, 'KWITANSI PEMBAYARAN', $black);
                              // imagestring($img, 5, 650, 52, 'No. '.date('Ymd').$idtag, $black);
                              // imagestring($img, 2, 650, 67, 'Tanggal pembayaran', $black);
                              // imagestring($img, 2, 650, 82, formatIndo(date('Y-m-d'), 'd F Y'), $black);
                              // imagestring($img, 5, 20, 91, $line, $orange);
                              // imagestring($img, 5, 20, 95, $line, $orange);
                              // imagestring($img, 4, 30, 125, 'Telah Diterima Dari', $black);
                              // imagestring($img, 5, 200, 125, ': '.$nama, $black);
                              // imagestring($img, 4, 30, 150, 'Dengan Nomor Layanan', $black);
                              // imagestring($img, 5, 200, 150, ': '.$user, $black);
                              // imagestring($img, 4, 30, 175, 'Sejumlah Uang', $black);
                              // imagestring($img, 4, 200, 175, ': '.terbilang($nominal).' rupiah', $black);
                              // imagestring($img, 4, 30, 200, 'Untuk Pembayaran', $black);
                              // imagestring($img, 4, 200, 200, ':', $black);
                              // imagestring($img, 5, 100, 225, $keterangan, $black);
                              // imagestring($img, 5, 20, 245, $line, $orange);
                              // imagestring($img, 5, 50, 280, '___________________________', $orange);
                              // imagestring($img, $font, 70, 300, 'Nominal : Rp. '.number_format($nominal, 0, ',', '.'), $black);
                              // imagestring($img, 5, 50, 310, '___________________________', $orange);
                              // imagestring($img, 4, 535, 280, $result['kabupaten'].', '.formatIndo(date('Y-m-d'), 'd F Y'), $black);
                              // // Simpan file ke direktori 'invoice'
                              // $invoicePath = 'invoice/'.$invoice;


                              $img = imagecreatefrompng($gambarKwitansi);
                              // Buat beberapa warna
                              $white = imagecolorallocate($img, 245, 245, 245);
                              $black = imagecolorallocate($img, 0, 0, 0);
                              $orange = imagecolorallocate($img, 0, 0, 128);
                              $fontPath = 'dist/X_10x20_LE.gdf';
                              $font = imageloadfont($fontPath);
                              $line = '_____________________________________________________________________________________';
                              imagestring($img, $font, 320, 30, 'KWITANSI PEMBAYARAN', $black);
                              imagestring($img, 3, 580, 30, 'No Faktur', $black);
                              imagestring($img, 3, 670, 30, ': '.date('Ymd').$idtag, $black);
                              imagestring($img, 3, 580, 50, 'Tanggal', $black);
                              imagestring($img, 3, 670, 50, ': '.formatIndo($tanggalbayar, 'd F Y'), $black);
                              imagestring($img, 3, 580, 70, 'No Pelanggan', $black);
                              imagestring($img, 3, 670, 70, ': '.$user, $black);
                              imagestring($img, 5, 20, 81, $line, $orange);
                              imagestring($img, 5, 20, 85, $line, $orange);
                              imagestring($img, 4, 30, 110, 'Telah Diterima Dari', $black);
                              imagestring($img, 5, 200, 110, ': '.$nama, $black);
                              imagestring($img, 4, 30, 135, 'Sejumlah Uang', $black);
                              imagestring($img, 4, 200, 135, ': '.terbilang($nominal).' rupiah', $black);
                              imagestring($img, 4, 30, 160, 'Untuk Pembayaran', $black);
                              imagestring($img, 4, 200, 160, ': '. $keterangan, $black);
                              imagestring($img, 5, 20, 175, $line, $orange);
                              imagestring($img, 4, 30, 190, 'NO', $black);
                              imagestring($img, 4, 70, 190, 'KETERANGAN', $black);
                              imagestring($img, 4, 620, 190, 'NOMINAL', $black);
                              imagestring($img, 5, 20, 195, $line, $orange);

                              imagestring($img, 4, 30, 215, '1', $black);
                              imagestring($img, 4, 70, 215, $paketint, $black);
                              imagestring($img, 4, 620, 215, $tagihan, $black);

                              if($data[0]['ppn'] != 0 ) {
                                imagestring($img, 4, 30, 235, '2', $black);
                                imagestring($img, 4, 70, 235, 'PPN 11%', $black);
                                imagestring($img, 4, 620, 235, $ppn, $black);
                              }

                              if($data[0]['kode_unik'] != 0 ) {
                                imagestring($img, 4, 30, 255, '3', $black);
                                imagestring($img, 4, 70, 255, 'Subsidi', $black);
                                imagestring($img, 4, 620, 255, $subsidi, $black);
                              }

                              imagestring($img, 5, 20, 265, $line, $orange);
                              imagestring($img, 4, 550, 290, 'TOTAL', $black);
                              imagestring($img, 4, 620, 290, 'Rp. '.number_format($nominal, 0, ',', '.'), $black);
                              imagestring($img, 5, 550, 300, '__________________________   ', $orange);

                              imagestring($img, 5, 50, 320, '______________________________', $orange);
                              imagestring($img, $font, 70, 340, 'Terbilang : Rp. '.number_format($nominal, 0, ',', '.'), $black);
                              imagestring($img, 5, 50, 350, '______________________________', $orange);
                              // Simpan file ke direktori 'invoice'
                              $invoicePath = 'invoice/'.$invoice;



                              if (!imagepng($img, $invoicePath)) {
                                echo "<br>".$invoicePath;
                                  die('Gagal menyimpan gambar.');
                              } else {
                              imagedestroy($img);

                              //Get Mikrotik Setting
                              $Mikro = $pdo->prepare("SELECT ip_address, port_api, username, password FROM setting_mikrotik WHERE id = :idset");
                              $Mikro->bindParam(':idset', $data[0]['id_setting_mikrotik'], PDO::PARAM_INT);
                              $Mikro->execute();
                              $Mikrot = $Mikro->fetchAll(PDO::FETCH_ASSOC);
                              //   print_r($Mikrot);
                              $m_ip   = $Mikrot[0]['ip_address'];
                              $m_user = $Mikrot[0]['username'];
                              $m_pass = $Mikrot[0]['password'];
                              $m_port = $Mikrot[0]['port_api'];

                              $API = new RouterosAPI();
                              $API->debug = false;

                              if ($API->connect2($m_ip, $m_user, $m_pass, $m_port)) {
                                if ($data[0]['jenis_layanan'] == 'Hotspot') {
                                  $arrIDh = $API->comm("/ip/hotspot/user/getall", [
                                      ".proplist" => ".id",
                                      "?name" => $userHs,
                                  ]);

                                  if (!empty($arrIDh)) {
                                      $API->comm("/ip/hotspot/user/set", [
                                          ".id" => $arrIDh[0][".id"],
                                          "disabled" => "false",
                                      ]);
                                  } else {

                                    throw new Exception('Akun Hotspot tidak ada di Mikrotik');
                                  }
                                } else {
                                  $arrID = $API->comm("/ppp/secret/getall", [
                                      ".proplist" => ".id",
                                      "?name" => $user,
                                  ]);

                                  if (!empty($arrID)) {
                                      $API->comm("/ppp/secret/set", [
                                          ".id" => $arrID[0][".id"],
                                          "disabled" => "false",
                                      ]);
                                  } else {
                                    throw new Exception('Akun PPPOE tidak ada di Mikrotik');
                                  }
                                }

                                $stmt = $pdo->prepare("UPDATE pelanggan SET status = 'aktif' WHERE id = :idpel");
                                $stmt->bindParam(':idpel', $data[0]['id_pelanggan'], PDO::PARAM_INT);
                                $stmt->execute();

                                $stmt = $pdo->prepare("UPDATE tagihan SET tanggal_bayar = :tanggal, bukti_pembayaran = :bukti, img_invoice = :inv, status = 'lunas', pelunas = :pelunas, catatan = :catatan WHERE id = :idtag");
                                $stmt->bindParam(':tanggal', $_POST['formatted_datetime']);
                                $stmt->bindParam(':bukti', $bukti);
                                $stmt->bindParam(':inv', $invoice);
                                $stmt->bindParam(':pelunas', $SvNama);
                                $stmt->bindParam(':catatan', $_POST['catatan']);
                                $stmt->bindParam(':idtag', $idtag, PDO::PARAM_INT);
                                $stmt->execute();

                                //Cek transaksi dengan id tagihan
                                $stmt = $pdo->prepare("SELECT id_tagihan FROM transaksi WHERE id_tagihan = :id");
                                $stmt->bindParam(':id', $idtag, PDO::PARAM_INT);
                                $stmt->execute();
                                $tagid = $stmt->fetchColumn();
                                if ($tagid === false) {
                                  $sql = "INSERT INTO transaksi (id_data_server, id_tagihan, id_user_akses, keterangan, pemasukan, start_time, metode_pembayaran, status) VALUES (:idds, :idtag, :idua, :keterangan, :pemasukan, :start_time, :metode, 'Tagihan')";
                                  $stmt = $pdo->prepare($sql);
                                  $stmt->bindParam(':idds', $data[0]['id_data_server'], PDO::PARAM_INT);
                                  $stmt->bindParam(':idtag', $idtag, PDO::PARAM_INT);
                                  $stmt->bindParam(':idua', $data[0]['id_marketing'], PDO::PARAM_INT);
                                  $stmt->bindParam(':keterangan', $data[0]['keterangan']);
                                  $stmt->bindParam(':pemasukan', $data[0]['verifikasi_tagihan']);
                                  $stmt->bindParam(':start_time', $_POST['formatted_datetime']);
                                  $stmt->bindParam(':metode', $_POST['metode']);
                                  $stmt->execute();
                                }
                                
                                if (in_array($data[0]['id_data_server'], [2, 3, 4, 5, 6, 8, 9])) {
                                    $nomor = explode(',', $data[0]['nomor_whatsapp'] . ',6282130888937');
                                } else {
                                    $nomor = explode(',', $data[0]['nomor_whatsapp']);
                                }
                                // Kirim Pesan WhatsApp
                                $Url = baseurl($invoicePath);
                                
                                $APIwa = new PesanWA();
                                $APIwa->Create_Pesan($data[0]['id_data_server'],$idtag,'pesan_melunasi_tagihan','tag');
                                $Pesan = $APIwa->Get_Pesan();
                                $APIwa->Send_Pesan($data[0]['id_data_server'],'sendMediaFromUrl',$nomor,$Pesan,$Url);
                              //   echo $Pesan;
                                sweetAlert("Pembayaran tagihan berhasil", "success", "?".encrypt_url('tagihan_detail_lunas|' . $idtag));

                                  
                                }
                                else{
                                  throw new Exception('Aplikasi Gagal terhubung ke Mikrotik');
                                }
                              }
                          } catch (PDOException $e) {
                              sweetAlert("Gagal: " . $e->getMessage(), "error");
                          } catch (Exception $e) {
                              sweetAlert("Gagal: " . $e->getMessage(), "error");
                          }
                      }
                      ?>
                  </div>
              </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</section>

<script>
// Fungsi untuk mengisi dropdown jam, menit, dan detik
  function isiDropdown(id, max) {
      let select = document.getElementById(id);
      for (let i = 0; i <= max; i++) {
          let option = document.createElement("option");
          option.value = i.toString().padStart(2, '0');
          option.text = i.toString().padStart(2, '0');
          select.appendChild(option);
      }
  }

  isiDropdown("jam", 23);
  isiDropdown("menit", 59);
  isiDropdown("detik", 59);

  // Waktu dari server (PHP)
  const serverDatetime = "<?= date('Y-m-d H:i:s') ?>";
  const [tanggal, waktu] = serverDatetime.split(" ");
  const [jam, menit, detik] = waktu.split(":");

  // Set input default sesuai waktu server
  document.getElementById("tanggal").value = tanggal;
  document.getElementById("jam").value = jam;
  document.getElementById("menit").value = menit;
  document.getElementById("detik").value = detik;

  function updateHiddenDatetime() {
      const tanggal = document.getElementById("tanggal").value;
      const jam = document.getElementById("jam").value;
      const menit = document.getElementById("menit").value;
      const detik = document.getElementById("detik").value;

      const formattedDatetime = `${tanggal} ${jam}:${menit}:${detik}`;
      document.getElementById("formatted_datetime").value = formattedDatetime;
  }

  document.getElementById("tanggal").addEventListener("input", updateHiddenDatetime);
  document.getElementById("jam").addEventListener("change", updateHiddenDatetime);
  document.getElementById("menit").addEventListener("change", updateHiddenDatetime);
  document.getElementById("detik").addEventListener("change", updateHiddenDatetime);

  updateHiddenDatetime();
</script>