<?php
$aserver = mysqli_query($con,"SELECT $page[1],backround_kwitansi,status_koneksi_off, interval_koneksi_off, status_payment_gateway FROM data_server WHERE id = '$SvId' ");
$server = mysqli_fetch_assoc($aserver);
// print_r($_SESSION);
?>
<!-- Main content -->
<section class="content" style="zoom: 90%;">
  <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">
                <h3 class="card-title">Setting <?php echo $page[1]; ?></h3>
              </div>
              <div class="col-sm-6">
              </div>
            </div>
          </div>
          <!-- /.card-header -->
          <div class="card-body">
          	<div class="row">
          		<div class="col-sm-6">
          			<div class="text-danger" style="margin: 20px;">
						<h6><b>Warning..!!</b></h6>
						<p>Untuk memposisikan data dari pelanggan silahkan isi dengan Variabel di bawah ini :<br>
            #usr => Nama Pelanggan<br>
            #add => Alamat Pelanggan<br>
            #ppp => PPPOE Pelanggan / ID Pelanggan<br>
            #lyn => Paket Berlangganan<br>
            #hly => Harga Layanan<br>
            #jns => Jenis Layanan<br>
            <?php if($page[1] == 'pesan_melunasi_tagihan' OR $page[1] == 'pesan_isolir_pelanggan' OR $page[1] == 'pesan_peringatan_tagihan' OR $page[1] == 'pesan_kirim_tagihan') { ?>
            #ket => Keterangan Tagihan<br>
            #jum => Jumlah Tagihan<br>
            #ppn => PPN<br>
            #unk => Kode Unik (for payment gateway)<br>
            #tot => Total Tagihan<br>
            #lmt => Limit Pembayaran
            <?php } 
            if($server['status_payment_gateway'] == 'ACTIVE' AND $page[1] == 'pesan_kirim_tagihan') { 
              echo "<br>#lnk => Link Payment Gateway";
            } 
            ?>
            </p>
						<p><b>Contoh :</b><br>
						*Tagihan layanan internet*<br>
						Nama : #usr<br>
						Jumlah Tagihan : #jum<br>
						PPN 11% : #ppn<br>
						Total Tagihan : #tot 
						</p>
            <?php if ($page[1] == 'pesan_koneksi_off') { ?>
              <hr>
              <h5><u>PERHATIAN..!!</u></h5>
              <p>Jika Status Pesan <b>Aktif</b> dan <b>Interval</b> di isi, maka pelanggan yang aktif dan koneksi nya mati akan di beri pesan otomatis setelah Interval yang telah anda tentukan</p>
            <?php } ?>
					</div>
				</div>
          		<div class="col-sm-6">
          			<form method="post" enctype="multipart/form-data">
          				<?php 
						if ($page[1] == 'pesan_melunasi_tagihan')
						{ ?>
						<center>
              <label>CONTOH</label>
              <img src="img/<?php echo $server['backround_kwitansi']; ?>" width="100%"><br><br>
              <div class="form-group">
                <label>Upload Backround Kwitansi</label>
                <input type="file" class="form-control" name="gambar">
              </div>
          	</center>
          	<hr>
				    	<?php } ?>
          				<center><label>Edit Pesan</label></center>
          				<div class="form-group">
          					<textarea type="text" class="form-control" rows="15" name="fpesan"><?php echo $server[$page[1]]; ?></textarea>
          				</div>
                  <?php if ($page[1] == 'pesan_koneksi_off') { ?>
                  <div class="row">
                    <div class="col-6">
                      <div class="form-group">
                        <label>Status Pesan</label>
                        <select class="form-control" name="status_koneksi_off" required="required">
                          <option value="Tidak Aktif" <?php if ($server['status_koneksi_off'] == "Tidak Aktif") { echo "selected"; }?>>Tidak Aktif</option>
                          <option value="Aktif" <?php if ($server['status_koneksi_off'] == "Aktif") { echo "selected"; }?>>Aktif</option>
                        </select>
                      </div>
                    </div>
                    <div class="col-6">
                      <label>Interval Saat Kirim Pesan</label>
                      <div class="input-group mb-4">
                        <input type="number" class="form-control" value="<?php echo $server['interval_koneksi_off']; ?>" name="interval">
                        <div class="input-group-append">
                            <div class="input-group-text">
                                <span> Menit </span>
                            </div>
                        </div>
                      </div>
                    </div>
                  </div>
                  <?php } ?>
          				<input type="submit" class="btn btn-sm btn-secondary m-1" name="edit" value="Simpan">
                  <a type="button" class="btn btn-success btn-sm m-1" data-toggle="modal" data-target="#staticBackdrop">Test Kirim Pesan</a>
          			</form>
          			<?php 
          				if(isset($_POST['edit'])){
                    // Periksa apakah file di-upload dan validasi halaman
                    if (isset($page[1]) && $page[1] == 'pesan_melunasi_tagihan' && isset($_FILES['gambar'])) {
                        // Validasi file upload
                        if ($_FILES['gambar']['error'] === UPLOAD_ERR_OK) {
                            
                            $nameFile = basename($_FILES["gambar"]["name"]);
                            $targetDir = "img/";
                            $targetFile = $targetDir . $nameFile;

                            // Memindahkan file ke direktori tujuan
                            if (move_uploaded_file($_FILES["gambar"]["tmp_name"], $targetFile)) {
                                // Menyiapkan string SQL untuk pembaruan
                                $SqlPost = ", backround_kwitansi = '$nameFile'";
                            } else {
                                // Tangani kesalahan jika file gagal dipindahkan
                                echo "Gagal memindahkan file.";
                                $SqlPost = '';
                            }
                        } else {
                            echo "Terjadi kesalahan dalam upload file.";
                            $SqlPost = '';
                        }
                    } else {
                        $SqlPost = '';
                    }

                    if ($page[1] == 'pesan_koneksi_off') {
                      $status_koneksi_off = $_POST['status_koneksi_off'];
                      $interval = preg_replace("/[^0-9]/","",$_POST['interval']);
                      $sqlPostOff = ", status_koneksi_off = '".$status_koneksi_off."', interval_koneksi_off = '".$interval."' ";
                    } else {
                      $sqlPostOff = "";
                    }

          					$update = mysqli_query($con,"UPDATE data_server SET $page[1] = '$_POST[fpesan]' $SqlPost $sqlPostOff WHERE id = '$SvId'");
          					if($update){
          						sweetAlert("Data telah di ubah", "success");
                      // echo $SqlPost;
          					}
          				}
          			?>
          		</div>
          	</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</section>
<!-- Modal Tambah -->
<div class="modal fade" id="staticBackdrop" data-backdrop="static" data-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <form method="post" enctype="multipart/form-data">
        <div class="modal-header bg-primary">
          <h5 class="modal-title" id="staticBackdropLabel">Test Kirim <?php echo $page[1]; ?></h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label>Masukan Nomor WhatsApp</label>
            <input type="text" name="nomor" class="form-control" required="required" placeholder="085*******">
          </div>
        </div>
        <div class="modal-footer">
          <input type="submit" name="kirim" class="btn btn-primary" value="Kirim Pesan">
        </div>
      </form>
    </div>
  </div>
</div>

<?php 
  if (isset($_POST['kirim'])) {
    // Kirim Pesan WhatsApp
    $APIwa = new PesanWA();
    // Menyiapkan query berdasarkan jenis pesan
    if ($page[1] == 'pesan_registrasi' || $page[1] == 'pesan_aktivasi' || $page[1] == 'pesan_koneksi_off') {
      $stmt = $pdo->prepare("SELECT id FROM pelanggan WHERE status = 'aktif' AND id_data_server = '$SvId'");
      $stmt->execute();
      $data = $stmt->fetchAll();
      $id = $data[0]['id'];
      $url = "";
      $APIwa->Create_Pesan($SvId,$id,$page[1]);

    } elseif ($page[1] == 'pesan_melunasi_tagihan' || $page[1] == 'pesan_isolir_pelanggan' || $page[1] == 'pesan_peringatan_tagihan' || $page[1] == 'pesan_kirim_tagihan') {
      if($server['status_payment_gateway'] == 'ACTIVE' AND $page[1] == 'pesan_kirim_tagihan') {
        $sqldata = "SELECT id,img_invoice FROM tagihan WHERE transaction_link != '' AND id_data_server = '$SvId'";
      } else {
        $sqldata = "SELECT id,img_invoice FROM tagihan WHERE status = 'lunas' AND id_data_server = '$SvId'";
      }
      $stmt = $pdo->prepare($sqldata);
      $stmt->execute();
      $data = $stmt->fetchAll();
      $id = $data[0]['id'];
      $url = baseurl()."/invoice/".$data[0]['img_invoice'];

      $APIwa->Create_Pesan($SvId,$id,$page[1],'tag');
    }


    $Pesan = $APIwa->Get_Pesan();
    if ($page[1] == 'pesan_melunasi_tagihan') {
      $APIwa->Send_Pesan($SvId,'sendMediaFromUrl',[$_POST['nomor']],$Pesan, $url);
    } else {
      $APIwa->Send_Pesan($SvId,'sendMessage',[$_POST['nomor']],$Pesan);
    }
    sweetAlert("Pesan akan segera di kirim ke nomor ".$_POST['nomor'],"success");
  }
?>