<?php 

// error_reporting(1);
// ini_set('display_errors', 1);
// $idtag = substr($_SERVER['QUERY_STRING'],-10);

$stmt = $pdo->prepare("SELECT * FROM v_tagihan WHERE $SqlSvData id = '$page[1]' AND status = 'lunas'");
$stmt->execute();
$data = $stmt->fetchAll();
if ($data[0]['konpensasi'] == 0) {
  $datakonpensasi = $data[0]['jumlah_konpensasi'];
} else {
  $datakonpensasi = 0;
}

// echo "<pre>";
// print_r($_SERVER);
// echo "</pre>";
?>
<section class="content">
    <div class="container-fluid">
      <div class="row">
          <div class="col-12">
            <div class="card">
                <div class="card-header bg-success">
                  <div class="row">
                      <div class="col-sm-6">
                        <h5>Detail Tagihan Lunas</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 Tagihan</td>
                            <td class="p-1">:</td>
                            <td class="p-1">
                              <?php 
                                if($data[0]['status'] == 'buat') {
                                  echo '<div class="badge badge-warning">Akan datang</div>';
                                } elseif($data[0]['status'] == 'nunggak') {
                                  echo '<div class="badge badge-danger">Tunggakan</div>';
                                } elseif($data[0]['status'] == 'lunas') {
                                  echo '<div class="badge badge-success">Telah dibayar lunas</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 $data[0]['akun']; ?></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">Jenis Layanan</td>
                            <td class="p-1">:</td>
                            <td class="p-1"><?php echo $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 $data[0]['keterangan']; ?></td>
                          </tr>
                          <tr>
                            <td class="p-1">Paket Berlangganan</td>
                            <td class="p-1">:</td>
                            <td class="p-1"><?php echo $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']); ?></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']); ?></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']); ?></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']); ?></td>
                          </tr>
                          <?php 
                          if($data[0]['kode_unik'] != '0') { ?>
                          <tr>
                            <td class="p-1">Kode Unik</td>
                            <td class="p-1">:</td>
                            <td class="p-1"><?php echo $data[0]['kode_unik']; ?></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']); ?></b></td>
                          </tr>
                        </tbody>
                      </table>
                    </div>
                    <div class="col-md-6">
                      <center>
                        <h6>Bukti Pembayaran</h6><hr>
                        <img src="img/user/<?php echo $data[0]['bukti_pembayaran']; ?>" height="400px"><br>
                        <h6>Kwitansi Lunas</h6><hr>
                        <img src="invoice/<?php echo $data[0]['img_invoice']; ?>" width="100%">
                      </center>
                    </div>
                  </div>
                  <div class="modal-footer">
                    <form method="post" enctype="mulipart/form-data">
                      <?php if(in_array("Bayar", $json_array[4]['sub_menu'])){ ?>
                      <input type="submit" name="return" class="btn btn-primary btn-sm m-1" value="Return Pembayaran">
                      <input type="submit" name="kirim" class="btn btn-success btn-sm m-1" value="Kirim Ulang Kwitansi">
                      <input type="submit" name="thermal" class="btn btn-warning btn-sm m-1" value="Ganerate Struk">
                      <?php } ?>
                    </form>
                  </div>
                      <?php
                      if (isset($_POST['return'])) {
                          try {
                              $user = $data[0]['akun'];
                              $userHs = $data[0]['user_hotspot'];

                              // 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);
                              
                              $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)) {
                                  // Cek jenis layanan
                                  if ($data[0]['jenis_layanan'] == 'Hotspot') {
                                      // 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" => "true",
                                          ]);

                                          $arrIDha = $API->comm("/ip/hotspot/active/getall", [
                                              ".proplist" => ".id",
                                              "?user" => $userHs,
                                          ]);

                                          if (!empty($arrIDha)) {
                                              $API->comm("/ip/hotspot/active/remove", [
                                                  ".id" => $arrIDha[0][".id"],
                                              ]);
                                          }
                                      } else {
                                          throw new Exception('Akun Hotspot tidak ada di Mikrotik');
                                      }
                                  } else {
                                      // PPPOE
                                      $arrID = $API->comm("/ppp/secret/getall", [
                                          ".proplist" => ".id",
                                          "?name" => $user,
                                      ]);

                                      if (!empty($arrID)) {
                                          $API->comm("/ppp/secret/set", [
                                              ".id" => $arrID[0][".id"],
                                              "disabled" => "true",
                                          ]);

                                          $arrID1 = $API->comm("/ppp/active/getall", [
                                              ".proplist" => ".id",
                                              "?name" => $user,
                                          ]);

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

                                  // Update status tagihan dan hapus transaksi
                                  $idtag = $page[1];

                                  $stmt = $pdo->prepare("UPDATE tagihan SET status = 'pending' WHERE id = :idtag");
                                  $stmt->bindParam(':idtag', $idtag, PDO::PARAM_INT);
                                  $stmt->execute();

                                  $stmt = $pdo->prepare("DELETE FROM transaksi WHERE id_tagihan = :idtag");
                                  $stmt->bindParam(':idtag', $idtag, PDO::PARAM_INT);
                                  $stmt->execute();

                                  // Success alert
                                  sweetAlert("Return Tagihan Berhasil", "success", "?".encrypt_url('tagihan_sedang_berjalan'));
                              } else {
                                  throw new Exception('Gagal terhubung ke Mikrotik');
                              }

                          } catch (PDOException $e) {
                              sweetAlert("Gagal: " . $e->getMessage(), "error");
                          } catch (Exception $e) {
                              sweetAlert("Gagal: " . $e->getMessage(), "error");
                          }
                      }
                      
                      if (isset($_POST['kirim'])) {
                        $Nomor = array($data[0]['nomor_whatsapp']);
                        $Url = baseurl('invoice/'.$data[0]['img_invoice']);
                        $Pesan = "Kwitansi Pembayaran bulan ".formatIndo($data[0]['tanggal_bayar'], 'F Y'); 
                        $APIwa = new PesanWA();
                        $APIwa->Send_Pesan($data[0]['id_data_server'],'sendMediaFromUrl',$Nomor,$Pesan,$Url);
                        sweetAlert("Kwitansi telah dikirim ulang", "success");
                      }

                      ?>

                    </div>
                  </div>
                </div>
          </div>
        </div>
    </div>
  </div>
</section>

<?php
if (isset($_POST['thermal'])) {
    require("invoice/thermal.php");

    // Pastikan variabel $data sudah tersedia
    if (!isset($data) || !is_array($data) || empty($data[0])) {
        die("Data tidak ditemukan!");
    }

    $lebar = 45; // 4.5 cm = 45 mm
    $tinggi = 100; // Sesuaikan tinggi sesuai kebutuhan
    $margin = 2; // Margin 2 mm
    $pdf = new PDF($lebar, $tinggi, $margin);

    $items = [
        ['Nama', ':', $data[0]['nama']],
        ['No. Id', ':', $data[0]['akun']],
        ['Nominal', ':', 'Rp. ' . number_format($data[0]['verifikasi_tagihan'])],
        ['Server', ':', $data[0]['nama_server']],
        ['Marketing', ':', $data[0]['nama_marketing']],
        ['Pelunas', ':', $data[0]['pelunas']],
        ['Keterangan', ':', $data[0]['catatan']],
    ];
    
    $pdf->dataItems($items, $data[0]['tanggal_bayar'], formatIndo($data[0]['limit_pembayaran'], 'F Y'));
    
    $outputPath = "invoice/thermal/INV-" . preg_replace("/[^a-zA-Z0-9]/", "_", $data[0]['nama']) . "-" . $data[0]['tanggal_bayar'] . ".pdf";
    $pdf->Output('F', $outputPath);
    
    echo '<script type="text/javascript">window.open("' . $outputPath . '", "_blank")</script>';
}
?>

