<nav class="navbar fixed-top">
    <div id="specificCard" class="card col-12" style="border-radius: 20px; background: none; border: none; margin-top: 10px;">
        <div class="row">
            <div class="col-6 icon-container">
                <a href="index.php" class="fa fa-arrow-left text-light"></a>
            </div>
            <div class="col-6 text-right">
                <h6 class="text-light mt-2 mb-2">Isi Saldo</h6>
            </div>
        </div>
    </div>
</nav>
<div class="card" style="border-radius: 0px; background: none; border: none; margin-top: 50px;">
	<div class="card-body">
	</div>
</div>
<div class="card" id="2" style="border-top-right-radius: 40px; border-top-left-radius: 40px; min-height: 850px; border: none; z-index: 1;">
	<div class="card-body">
		<center>
			<h6>Isi Saldo Agen Voucher</h6><br>
		</center>
		<?php 
			// Cari Payment Gateway
			$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', $pcmem['id_data_server'], PDO::PARAM_INT);
			$stmt->execute();
			$paygw = $stmt->fetchAll(PDO::FETCH_ASSOC);
			if (!empty($paygw[0]['apikey_payment_gateway']) && isset($paygw[0]['status_payment_gateway']) && $paygw[0]['status_payment_gateway'] === 'ACTIVE') { 

				$stmt = $pdo->prepare("SELECT * FROM agen_tambah_saldo WHERE id_agen_voucher = :id_agen_voucher AND status_payment = 'ACTIVE'");
				$stmt->bindParam(':id_agen_voucher', $_SESSION['agen'], PDO::PARAM_INT);
				$stmt->execute();
				$ada = $stmt->fetch(PDO::FETCH_ASSOC);

				if($ada) { ?>
				<center>
					<p class="text-danger">Silahkan klik "Bayar Saldo" untuk melanjutkan pembayaran, dan klik "Ubah Nominal" untuk merubah nominal isi saldo anda</p>
					<h2><small>Rp.</small> <b><?php echo number_format($ada['nominal']); ?></b></h2>
					<br>
					<h5>Untuk Pembayaran Silahkan salin Link di bawah ini dan buka di Google Chrome</h5>
					<br>
					<a href="javascript:void(0);" onclick="copyText()"><?php echo $ada['url_payment']; ?></a>

					<br><br>
					<!--<a href="https://detik.com/">TESTTT</a>-->
					
					<!--<a href="https://<?php echo $ada['url_payment']; ?>" class="btn btn-warning btn-block btn-md mb-4" target="_blank" style="border-radius: 30px;">Bayar Saldo</a>-->

					<!--<a href="?<?php echo base64_encode('isi_saldo_bayar|https://'.$ada['url_payment']); ?>">Bayar</a>-->
					<button type="button" class="btn btn-secondary btn-block btn-md" style="border-radius: 30px;" data-toggle="modal" data-target="#myModal">Ubah Nominal</button>
				</center>
				<?php } else { ?>
					<form method="post">
						<div class="form-group">
							<label><small>Masukan Nominal</small></label>
							<input type="text" class="form-control rupiah" id="rupiah0" name="nominal" required="required">
							<i class="text-danger">Untuk isi saldo minimal Rp. 25,000</i>
						</div><br>
						<input type="submit" name="tambah_saldo" value="Tambah Saldo" class="btn btn-warning btn-md btn-block" style="border-radius: 30px;" >
					</form>
				<?php } ?>

				<!-- Detail riwayat isi saldo dengan payment gateway -->
				<div class="mt-4">
					<hr>
					<center>
						<p>Riwayat isi saldo otomatis</p>
					</center>
					<table class="table">
				<?php
					$stmt = $pdo->prepare("SELECT * FROM agen_tambah_saldo WHERE id_agen_voucher = :id_agen_voucher AND status_payment != 'ACTIVE' ORDER BY waktu DESC, id DESC");
					$stmt->bindParam(':id_agen_voucher', $_SESSION['agen'], PDO::PARAM_INT);
					$stmt->execute();
					while($saldo = $stmt->fetch(PDO::FETCH_ASSOC)) { ?>
						<tbody>
							<tr>
								<td>
									<?php echo $saldo['waktu']; ?>
									<p><b>Rp. <?php echo number_format($saldo['nominal']); ?></b></p>
								</td>
								<td class="text-right">
									<?php echo $saldo['status_payment']; ?>
								</td>
							</tr>
						</tbody>
				<?php } ?>
					</table>
				</div>
				<!-- END Detail riwayat isi saldo dengan payment gateway -->
			<?php } else { ?>
			<center>
				<h6>PERHATIAN !</h6><br><hr>
				<p>Untuk pengisian saldo aplikasi ini silahkan hubungi admin yang bersangkutan</p>
				<p>Terimakasih !!</p>
			</center>
		<?php } ?>
	</div>
</div>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['tambah_saldo'])) {
        try {

	        $nominal = preg_replace("/[^0-9]/", "", $_POST['nominal']);

	        if($nominal >= 25000) {
		        $waktu = date('Y-m-d H:i:s');
		        $keterangan = "Tambah saldo agen voucher";
		        $urlback = 'https://agen.bilspro.com/?'.base64_encode('isi_saldo');

				$apiKey = $paygw[0]['apikey_payment_gateway'];
				$apiUrl = $paygw[0]['url_payment_gateway'];

				require '../payment/flip/Flip/Transaction.php';
				$flip = new FlipPaymentGateway($apiKey,$apiUrl);

				$response = $flip->createBill($keterangan, $nominal, $pcmem['email'], $pcmem['nama'], $pcmem['nomor_whatsapp'], $pcmem['alamat'], $urlback);

		        $id_payment = $response['link_id'];
		        $url_payment = $response['link_url'];
		        $status_payment = $response['status'];

		        // print_r($response);

	            $stmt = $pdo->prepare("INSERT INTO agen_tambah_saldo (id_data_server, id_agen_voucher, nominal, waktu, id_payment, url_payment, status_payment, keterangan) VALUES (:id_data_server, :id_agen_voucher, :nominal, :waktu, :id_payment, :url_payment, :status_payment, :keterangan)");
	            $stmt->bindParam(':id_data_server', $pcmem['id_data_server'], PDO::PARAM_INT);
	            $stmt->bindParam(':id_agen_voucher', $_SESSION['agen'], PDO::PARAM_INT);
	            $stmt->bindParam(':nominal', $nominal, PDO::PARAM_INT); // Pastikan nominal di-bind sebagai integer
	            $stmt->bindParam(':waktu', $waktu);
	            $stmt->bindParam(':id_payment', $id_payment);
	            $stmt->bindParam(':url_payment', $url_payment);
	            $stmt->bindParam(':status_payment', $status_payment);
	            $stmt->bindParam(':keterangan', $keterangan);

	            // Eksekusi statement
	            $stmt->execute();
	            sweetAlert("Permintaan Tambah Saldo Berhasil", "success");
	        } else {
	        	sweetAlert("Nominal yang anda masukan kurang dari Rp. 25,000", "error");
	        }

        } catch (PDOException $e) {
            // Menangani kesalahan saat eksekusi
            sweetAlert("Terjadi kesalahan: " . htmlspecialchars($e->getMessage()), "error");
        }
    }

    if (isset($_POST['ubah_moninal'])) {
    	try {

	        $nominal = preg_replace("/[^0-9]/", "", $_POST['nominal']);

	        if($nominal >= 25000) {
		        $keterangan = "Tambah saldo agen voucher";
		        $transactionId = $ada['id_payment'];
		        $status = $ada['status_payment'];

				$apiKey = $paygw[0]['apikey_payment_gateway'];
				$apiUrl = $paygw[0]['url_payment_gateway'];

				require '../payment/flip/Flip/Transaction.php';
				$flip = new FlipPaymentGateway($apiKey,$apiUrl);

				$response = $flip->editBill($transactionId,$status,$keterangan, $nominal);

		        $id_payment = $response['link_id'];
		        $url_payment = $response['link_url'];
		        $status_payment = $response['status'];

	            $stmt = $pdo->prepare("UPDATE agen_tambah_saldo SET nominal = :nominal, url_payment = :url_payment, status_payment = :status_payment WHERE id_payment = :id_payment");
	            $stmt->bindParam(':nominal', $nominal);
	            $stmt->bindParam(':url_payment', $url_payment);
	            $stmt->bindParam(':status_payment', $status_payment);
	            $stmt->bindParam(':id_payment', $ada['id_payment']);
	            // Eksekusi statement
	            $stmt->execute();

	            sweetAlert("Nominal Permintaan telah di ubah", "success");
            } else {
	        	sweetAlert("Nominal yang anda masukan kurang dari Rp. 25,000", "error");
	        }
        } catch (PDOException $e) {
            // Menangani kesalahan saat eksekusi
            sweetAlert("Terjadi kesalahan: " . htmlspecialchars($e->getMessage()), "error");
        }
    }
}


?>

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">Ubah Nominal Isi Saldo</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
			<form method="post">
            <div class="modal-body">
                <div class="form-group">
					<label><small>Masukan Nominal</small></label>
					<input type="text" class="form-control rupiah" id="rupiah0" value="<?php echo $ada['nominal']; ?>" name="nominal" required="required">
					<i class="text-danger">Untuk isi saldo minimal Rp. 25,000</i>
				</div><br>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">Tutup</button>
                <button type="submit" class="btn btn-primary btn-sm" name="ubah_moninal">Ubah Nominal</button>
            </div>
	        </form>
        </div>
    </div>
</div>

<script>
  function copyText() {
    // Membuat elemen textarea sementara untuk menyalin teks
    const textToCopy = "<?php echo $ada['url_payment']; ?>"; // Teks yang ingin disalin
    const tempTextArea = document.createElement('textarea');
    
    // Menambahkan teks ke dalam textarea sementara
    tempTextArea.value = textToCopy;
    document.body.appendChild(tempTextArea);
    
    // Memilih dan menyalin teks
    tempTextArea.select();
    tempTextArea.setSelectionRange(0, 99999); // Untuk perangkat mobile

    // Menyalin teks ke clipboard
    document.execCommand('copy');
    
    // Menghapus textarea sementara setelah digunakan
    document.body.removeChild(tempTextArea);

    // Menampilkan pemberitahuan atau alert bahwa teks telah disalin
    alert("Teks telah disalin: " + textToCopy);
  }
</script>
