<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>Buat Tagihan</h5>
              </div>
              <div class="col-sm-6"></div>
            </div>
          </div>
          <!-- /.card-header -->
          <div class="card-body">
            <form method="post" enctype="multipart/form-data">
             <div class="row">
                <div class="col-md-6">
                  <div class="form-group">
                    <label>Nama Pelanggan</label>
                    <select class="form-control select2bs4" required="required" name="idpel">
                      <option value="">Pilih</option>
                      <?php 
                      $List->set_list("pelanggan", $SqlDataWHId);
                      foreach ($List->get_list() as $key => $value): ?>
                        <option value="<?php echo htmlspecialchars($value['id']); ?>"><?php echo htmlspecialchars($value['nama'].' ('.$value['alamat'].')'); ?></option>
                      <?php endforeach ?>
                    </select>
                  </div>
                  <div class="form-group">
                    <label>Limit Pembayaran</label>
                    <input class="form-control" type="date" name="tanggal" required="required">
                  </div>
                </div>
                <div class="col-md-6">
                </div>
              </div>
              <div id="form-content"></div>
            </div>
            <div class="card-footer">
              <input type="submit" name="tambah" class="btn btn-primary" value="Tambah">
            </div>
            </form>

<?php

if (isset($_POST['tambah'])) {
    try {
        // Prepare and execute statement to fetch customer data
        $stmt = $pdo->prepare("SELECT * FROM pelanggan WHERE id = :id");
        $stmt->bindParam(':id', $_POST['idpel'], PDO::PARAM_INT);
        $stmt->execute();
        $pelanggan = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$pelanggan) {
            throw new Exception('Customer not found.');
        }

        // Fetch package price
        $stmt = $pdo->prepare("SELECT harga_paket FROM profile_paket WHERE id = :id_profile_paket");
        $stmt->bindParam(':id_profile_paket', $pelanggan['id_profile_paket'], PDO::PARAM_INT);
        $stmt->execute();
        $tagihan = $stmt->fetchColumn();

        // Fetch payment gateway data
        $stmt = $pdo->prepare("SELECT payment_gateway, apikey_payment_gateway, url_payment_gateway,status_payment_gateway FROM data_server WHERE id = :id_data");
        $stmt->bindParam(':id_data', $pelanggan['id_data_server'], PDO::PARAM_INT);
        $stmt->execute();
        $paygw = $stmt->fetch(PDO::FETCH_ASSOC);

        // Fetch PPN data
        $stmt = $pdo->prepare("SELECT ppn FROM profile_tagihan WHERE id = :id_profile_tagihan");
        $stmt->bindParam(':id_profile_tagihan', $pelanggan['id_profile_tagihan'], PDO::PARAM_INT);
        $stmt->execute();
        $ppn = $stmt->fetchColumn();

        if ($ppn == 1 ) {
            $nominal_tagihan = $tagihan;
            $jumlah_tagihan = $tagihan;
            $ppn_amount = 0;
            $total_tagihan = $jumlah_tagihan + $ppn_amount;
            $kode_unik = 0;
            $verifikasi_tagihan = $total_tagihan + $kode_unik;
        }
        elseif($ppn == 2 ) {
            $nominal_tagihan = $tagihan;
            $jumlah_tagihan = $tagihan;
            $ppn_amount = $jumlah_tagihan / 100 * 11;
            $total_tagihan = $jumlah_tagihan + $ppn_amount;
            $kode_unik = 0;
            $verifikasi_tagihan = $total_tagihan + $kode_unik;
        }
        elseif($ppn == 3 ) {
            $nominal_tagihan = $tagihan;
            $jumlah_tagihan = $tagihan - ($tagihan / 100 * 9.91);
            $ppn_amount = $jumlah_tagihan / 100 * 11;
            $total_tagihan = $jumlah_tagihan + $ppn_amount;
            $kode_unik = 0;
            $verifikasi_tagihan = $total_tagihan + $kode_unik;
        }
        elseif($ppn == 4 ) {
            $nominal_tagihan = $tagihan;
            $jumlah_tagihan = $tagihan;
            $ppn_amount = $jumlah_tagihan / 100 * 11;
            $total_tagihan = $jumlah_tagihan + $ppn_amount;
            $kode_unik = substr($total_tagihan, -3);
            $verifikasi_tagihan = $total_tagihan - $kode_unik;
        }

        // Calculate billing details
        $limit_tag = $_POST['tanggal'];
        $keterangan = "Tagihan Layanan Internet bulan " . formatIndo($limit_tag, 'F Y');
        $status = 'pending';

        // Payment gateway processing
        $transaction_id = '';
        $transaction_link = '';
        $transaction_status = '';
        
        $total_desimal = round($verifikasi_tagihan);

        if (!empty($paygw['apikey_payment_gateway']) && $paygw['status_payment_gateway'] === 'ACTIVE') {
            require 'payment/flip/Flip/Transaction.php';
            $flip = new FlipPaymentGateway($paygw['apikey_payment_gateway'], $paygw['url_payment_gateway']);
            $response = $flip->createBill($keterangan, $total_desimal, $pelanggan['email'], $pelanggan['nama'], $pelanggan['nomor_whatsapp'], $pelanggan['alamat']);

            if (isset($response['link_id'])) {
                $transaction_id = $response['link_id'];
                $transaction_link = $response['link_url'];
                $transaction_status = $response['status'];
            } else {
              $er = implode(",", $response);
              throw new Exception($er);
            }
        }

        // Insert into the tagihan table
        $stmt = $pdo->prepare("INSERT INTO tagihan 
            (id_data_server, id_pelanggan, id_profile_paket, id_profile_tagihan, nominal_tagihan, jumlah_tagihan, ppn, total_tagihan, verifikasi_tagihan, keterangan, limit_pembayaran, status, transaction_link, transaction_id, transaction_status, kode_unik)
            VALUES (:id_data_server, :id_pelanggan, :id_profile_paket, :id_profile_tagihan, :nominal_tagihan, :jumlah_tagihan, :ppn, :total_tagihan, :verifikasi_tagihan, :keterangan, :limit_pembayaran, :status, :transaction_link, :transaction_id, :transaction_status, :kode_unik)");

        $stmt->execute([
            ':id_data_server' => $pelanggan['id_data_server'],
            ':id_pelanggan' => $pelanggan['id'],
            ':id_profile_paket' => $pelanggan['id_profile_paket'],
            ':id_profile_tagihan' => $pelanggan['id_profile_tagihan'],
            ':nominal_tagihan' => round($nominal_tagihan),
            ':jumlah_tagihan' => round($jumlah_tagihan),
            ':ppn' => round($ppn_amount),
            ':total_tagihan' => round($total_tagihan),
            ':verifikasi_tagihan' => round($verifikasi_tagihan),
            ':keterangan' => $keterangan,
            ':limit_pembayaran' => $limit_tag,
            ':status' => $status,
            ':transaction_link' => $transaction_link,
            ':transaction_id' => $transaction_id,
            ':transaction_status' => $transaction_status,
            ':kode_unik' => $kode_unik,
        ]);

        $last_id = $pdo->lastInsertId();
        sweetAlert("Tagihan telah ditambahkan", "success", '?' . encrypt_url('tagihan_detail|' . $last_id . '|tagihan_sedang_berjalan'));
    } catch (Exception $e) {
        // Handle exceptions and errors gracefully
        sweetAlert("Terjadi kesalahan: " . $e->getMessage(), "error");
    }
}
?>

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