<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/2.2.1/css/dataTables.dataTables.css">
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
<script src="https://cdn.datatables.net/2.2.1/js/dataTables.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js"></script>
<script>
const ENCRYPTION_KEY = CryptoJS.enc.Hex.parse('9a307dfcf16ac2e4406b1a59a31c1d096eafe37e40c60ddee4bb827b6a947079');

function encrypt_url_js(data) {
    const iv = CryptoJS.lib.WordArray.random(16);

    const encrypted = CryptoJS.AES.encrypt(data, ENCRYPTION_KEY, {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });

    // IV ke hex
    const ivHex = iv.toString(CryptoJS.enc.Hex);
    // Ciphertext base64
    const encryptedBase64 = encrypted.ciphertext.toString(CryptoJS.enc.Base64);

    // Gabung ivHex + "::" + encryptedBase64 (string)
    const combined = ivHex + "::" + encryptedBase64;

    // Base64 encode seluruh string agar aman
    return btoa(combined);
}
</script>

<section class="content" style="zoom: 85%;">
  <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">
                <h4>Tagihan Lunas</h4>
              </div>
              <div class="col-sm-6 text-right">
                <!-- Placeholder untuk tombol filter atau aksi tambahan -->
              </div>
            </div>
          </div>
          <!-- /.card-header -->
          <div class="card-body">
            <table id="tableLunas" class="table table-bordered table-striped" style="width: 100%;">
              <thead>
                <tr class="bg-success">
                  <th>No</th>
                  <th>Nama</th>
                  <th>Id Pelanggan</th>
                  <th>Alamat</th>
                  <th>Keterangan</th>
                  <th>Paket Berlanggan</th>
                  <th>Jumlah Tagihan</th>
                  <th>Nama Server</th>
                  <th>Tgl Bayar</th>
                  <th>Marketing</th>
                  <th>Pelunas</th>
                  <th>Catatan</th>
                  <th>Action</th>
                </tr>
              </thead>
              <tbody>
                <!-- Data akan dimuat melalui server-side processing -->
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  </div>
</section>


<script>
  $(document).ready(function () {
    $('#tableLunas').DataTable({
      processing: true,
      serverSide: true,
      responsive: true,
      autoWidth: false,
      ajax: {
        url: "list_data/list_tagihan_lunas.php?idsv=<?php echo $SqlSvData; ?>",
        type: "GET"
      },
      columns: [
        { data: 'id', render: (data, type, row, meta) => meta.row + 1 }, // Nomor urut
        { data: 'nama' },
        { data: 'akun' },
        { data: 'alamat' },
        { data: 'keterangan' },
        { data: 'nama_paket' },
        { 
          data: 'verifikasi_tagihan', 
          render: data => `Rp. ${parseInt(data).toLocaleString('id-ID')}` 
        },
        { data: 'nama_server' },
        { data: 'tanggal_bayar' },
        { data: 'nama_marketing' },
        { data: 'pelunas' },
        { data: 'catatan' },
        {
          data: 'id',
          render: data => {
            const encryptedUrl = encrypt_url_js('tagihan_detail_lunas|' + data);
        
            return `
              <a href="?${encryptedUrl}" class="btn btn-sm btn-info m-1">Detail</a>
              <form method="POST" action="" style="display:inline;">
                <input type="hidden" name="thermal" value="${data}">
                <button type="submit" class="btn btn-sm btn-secondary m-1">Struk</button>
              </form>
            `;
          }
        }
      ],
      order: [[8, 'desc']], // Mengurutkan berdasarkan Tgl Bayar
      columnDefs: [
        { targets: 3, width: "250px" }, // Alamat
        { targets: 4, width: "250px" }, // Keterangan
      ],
      language: {
        infoFiltered: ""  // Menonaktifkan teks "(filtered from X total entries)"
      }
    });
  });
</script>

<?php
if (isset($_POST['thermal'])) {
    
    require("invoice/thermal.php");
    $idpost = $_POST['thermal'];
    
    $stmt = $pdo->prepare("SELECT nama, akun, verifikasi_tagihan, nama_server, nama_marketing, pelunas, catatan, tanggal_bayar, limit_pembayaran FROM v_tagihan WHERE id = :id");
    $stmt->bindParam(':id', $idpost, PDO::PARAM_INT);
    $stmt->execute();
    $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // 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 = 90; // 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>';
}
?>
