<?php


$balance_history_txt = '';
$body_text = '';

if (login_control()) {

	if (isset($_GET['check-order']) && isset($_POST['order_id'])) {
		$order = $db->from('deposits')->where('deposit_status', 2)->where('deposit_method', 8)->where('user_id', $user['user_id'])->where('deposit_id', intval($_POST['order_id']))->first();
		if ($order !== false) {
			ob_get_clean();
			$payment_method = $db->from('payment_methods')->where('method_id', 8)->first();

			$method_detail = json_decode($payment_method['method_details'], true);

			$amount = $order['deposit_amount'];
			$order_total = ($amount + ($amount * $method_detail['comission'] / 100));

			$inbox = imap_open('{' . $method_detail['imap_server'] . '}', $method_detail['imap_user'], $method_detail['imap_password']) or die('IMAP Error: ' . imap_last_error());

			$emails = imap_search($inbox, 'FROM "bilgi@papara.com"');

			$output = '';

			if (!is_array($emails)) {
				$emails = [];
			}

			$payment_id = $method_detail['prefix'] . $order['deposit_id'];


			foreach ($emails as $mail) {

				$headerInfo = imap_headerinfo($inbox, $mail);

				$subject = mb_decode_mimeheader($headerInfo->subject);

				if (strpos($subject, 'Hesabına') !== false) {
					$amount = str_replace('_', '', explode('TL', explode('Hesabına', $subject)[1])[0]);
					$amount = str_replace('.', '', $amount);
					$amount = str_replace(',', '.', $amount);
					$amount = floatval($amount);

					if ($amount == floatval($order_total)) {

						$emailContent = quoted_printable_decode(imap_fetchbody($inbox, $mail, 1));

						if (strpos($emailContent, 'açıklama ekledi') !== false) {
							$desc = trim(ltrim(trim(explode('</td>', explode('açıklama ekledi', $emailContent)[1])[0]), ':'));

							$amount = trim(explode('gönderdi', explode('sana', $emailContent)[1])[0]);
							$amount = explode(' ', $amount)[0];
							$amount = str_replace('.', '', strval($amount));
							$amount = str_replace(',', '.', strval($amount));

							$amount = floatval($amount);


							if (strpos($desc, $payment_id) !== false) {
								if ($amount === floatval($order_total)) {
									imap_delete($inbox, $mail);
									imap_expunge($inbox);
									imap_close($inbox);

									$userQuery = $user;
									$query = $order;

									$payment_bonus = $db->from('payment_bonus')->where('bonus_method', 8)->where('bonus_from', $query['deposit_amount'], '<=')->orderby('bonus_from', 'DESC')->first();

									if ($payment_bonus) {
										$newBalance = $userQuery['user_balance'] + ($query['deposit_amount'] + ($query['deposit_amount'] + $payment_bonus['bonus_amount'] / 100));
									} else {
										$newBalance = $userQuery['user_balance'] + $query['deposit_amount'];
									}

									$updateBalance = $db->update('users')->where('user_id', $query['user_id'])->set(array('user_balance' => $newBalance));
									$updateDeposit = $db->update('deposits')
										->where('deposit_id', intval($_POST['order_id']))
										->set(array('deposit_status' => 1));
									echo json_encode(array("confirmed" => true));
									die;
								}
							}
						}
					}
				}
			}

			imap_expunge($inbox);
			imap_close($inbox);

			echo json_encode(array("confirmed" => false));
		}
		die();
	}


	if ($_POST) {



		$method_id = $_POST['method'];

		$amount = $_POST['amount'];
		
		$phone = $_POST['phone'];

		$phoneStrLen = strlen($phone);


		$payment_method = $db->from('payment_methods')->where('method_id', $method_id)->first();

		$method_detail = json_decode($payment_method['method_details'], true);

		$paymentCode = uniqid() . $user["user_id"];

		$amount_fee = ($amount + ($amount * $method_detail["comission"] / 100));



		if (empty($method_id)) {

			$error = true;

			$errorText = "Lütfen ödeme yöntemi seçiniz.";
		} elseif (!is_numeric($amount)) {

			$error = true;

			$errorText = "Lütfen geçerli bir tutar giriniz.";
		} elseif ($phoneStrLen < 10) {

			$error = true;

			$errorText = "Geçerli Bir Telefon Numarası Giriniz.";
	    } elseif ($phoneStrLen > 11) {

			$error = true;

			$errorText = "Geçerli Bir Telefon Numarası Giriniz.";
		} elseif ($amount < $method_detail['min']) {

			$error = true;

			$errorText = "Yatırılacak tutar " . $method_detail['min'] . " miktarından düşük olamaz.";
		} elseif ($amount > $method_detail['max']) {

			$error = true;

			$errorText = "Yatırılacak tutar " . $method_detail['max'] . " miktarından yüksek olamaz.";
		} else {



			if ($method_id == 1) { // PayTR Kredi Kartı



				$merchant_id      = $method_detail["mid"];

				$merchant_key     = $method_detail["key"];

				$merchant_salt    = $method_detail["salt"];

				$email            = $user["user_email"];

				$payment_amount   = intval($amount_fee * 100);

				$merchant_oid     = $paymentCode;

				$user_name        = $user["user_first_name"] . " " . $user["user_last_name"];

				$user_address     = "Belirtilmemiş";

				$user_phone       = $phone;

				$currency         = "TL";

				$merchant_ok_url  = site($siteLinks['add-funds']['url']);

				$merchant_fail_url = site($siteLinks['add-funds']['url']);

				$user_basket      = base64_encode(json_encode(array(array($amount . " " . $currency . " Bakiye", $amount_fee, 1))));

				if (isset($_SERVER["HTTP_CLIENT_IP"])) {

					$ip = $_SERVER["HTTP_CLIENT_IP"];
				} elseif (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {

					$ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
				} else {

					$ip = $_SERVER["REMOTE_ADDR"];
				}

				$user_ip = $ip;

				$timeout_limit    = "360";

				$debug_on         = 1;

				$test_mode        = 0;

				$no_installment   = 0;

				$max_installment  = 0;

				$hash_str         = $merchant_id . $user_ip . $merchant_oid . $email . $payment_amount . $user_basket . $no_installment . $max_installment . $currency . $test_mode;

				$paytr_token      = base64_encode(hash_hmac('sha256', $hash_str . $merchant_salt, $merchant_key, true));

				$post_vals = array(

					'merchant_id' => $merchant_id,

					'user_ip' => $user_ip,

					'merchant_oid' => $merchant_oid,

					'email' => $email,

					'payment_amount' => $payment_amount,

					'paytr_token' => $paytr_token,

					'user_basket' => $user_basket,

					'debug_on' => $debug_on,

					'no_installment' => $no_installment,

					'max_installment' => $max_installment,

					'user_name' => $user_name,

					'user_address' => $user_address,

					'user_phone' => $user_phone,

					'merchant_ok_url' => $merchant_ok_url,

					'merchant_fail_url' => $merchant_fail_url,

					'timeout_limit' => $timeout_limit,

					'currency' => $currency,

					'test_mode' => $test_mode

				);

				$ch = curl_init();

				curl_setopt($ch, CURLOPT_URL, "https://www.paytr.com/odeme/api/get-token");

				curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

				curl_setopt($ch, CURLOPT_POST, 1);

				curl_setopt($ch, CURLOPT_POSTFIELDS, $post_vals);

				curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

				curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

				curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);

				curl_setopt($ch, CURLOPT_TIMEOUT, 20);

				$result = @curl_exec($ch);

				if (curl_errno($ch)) {

					$error = true;

					$errorText = "PAYTR IFRAME connection error. err:" . curl_error($ch);
				}

				curl_close($ch);

				$result  = json_decode($result, true);



				if ($result['status'] == "success") {



					$newbalance = $user['user_balance'] + $amount;
					$eskibakiye = $user['user_balance'];
					$yenibakiye = $newbalance;


					$token  = $result['token'];

					$insertOrder = $db->insert('deposits')

						->set(array(

							'user_id' => $user['user_id'],

							'order_id' => $merchant_oid,

							'deposit_date' => time(),

							'deposit_amount' => $amount,

							'deposit_method' => 1,

							'deposit_status' => 2,
							'eskib' => $eskibakiye,
							'yenib' => $yenibakiye


						));



					$success = true;

					$successText = "3D Güvenli ödeme sayfasına yönlendiriliyorsunuz.";

					$payment_url = "https://www.paytr.com/odeme/guvenli/" . $token;
				} else {



					$error = true;

					$errorText = "Ödeme işlemi başlatılamadı. Sebep: " . $result['reason'];
				}
			} elseif ($method_id == 3) { // Paywant



				$hashOlustur = base64_encode(hash_hmac('sha256', $user["user_email"] . "|" . $user["user_email"] . "|" . $user['user_id'] . $method_detail['key'], $method_detail['secret'], true));



				if (isset($_SERVER["HTTP_CLIENT_IP"])) {

					$ip = $_SERVER["HTTP_CLIENT_IP"];
				} elseif (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {

					$ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
				} else {

					$ip = $_SERVER["REMOTE_ADDR"];
				}

				$user_ip = $ip;



				$postData = array(

					'apiKey' => $method_detail['key'],

					'hash' => $hashOlustur,

					'returnData' => $user["user_email"],

					'userEmail' => $user["user_email"],

					'userIPAddress' => $user_ip,

					'userID' => $user["user_id"],

					'proApi' => TRUE,

					'productData' => [

						"name" =>  $amount . " TL Tutarında Bakiye (" . $paymentCode . ")",

						"amount" => $amount_fee * 100,

						"extraData" => $amount,

						"paymentChannel" => 2,

						"commissionType" => 2

					]

				);



				$curl = curl_init();

				curl_setopt_array($curl, array(

					CURLOPT_URL => "https://secure.paywant.com/gateway",

					CURLOPT_RETURNTRANSFER => true,

					CURLOPT_ENCODING => "",

					CURLOPT_MAXREDIRS => 10,

					CURLOPT_TIMEOUT => 30,

					CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,

					CURLOPT_CUSTOMREQUEST => "POST",

					CURLOPT_POSTFIELDS => http_build_query($postData),

				));

				$response = curl_exec($curl);
				$err = curl_error($curl);



				if (!$err) {



					$jsonDecode = json_decode($response, false);

					if ($jsonDecode->status == "true") {



						$success = true;

						$successText = "3D Güvenli ödeme sayfasına yönlendiriliyorsunuz.";

						$payment_url = $jsonDecode->message;
					} else {



						$error = true;

						$errorText = "Ödeme işlemi başlatılamadı. Sebep: " . $jsonDecode->message;

						$payment_url = false;
					}
				} else {



					$error = true;

					$errorText = "Ödeme işlemi başlatılamadı.";

					$payment_url = false;
				}
			} elseif ($method_id == 99) { // Payhesap

				if (isset($_SERVER["HTTP_CLIENT_IP"])) {

					$ip = $_SERVER["HTTP_CLIENT_IP"];
				} elseif (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {

					$ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
				} else {

					$ip = $_SERVER["REMOTE_ADDR"];
				}

				$user_ip = $ip;


				/*
					İFrame ödeme yönteminde ödeme işlemi için sipariş  iframe popup açılır ve müşteri ödemesini yaptıktan sonra
					ödeme başarılı ise success.php hatalı ise fail.php dosyasına GET ile yönlendirilir.
					
					Ödeme sonrası yönlendirme işlemi gerçekleşmeden önce callback.php dosyasına ödeme bilgisi
					POST ile gönderilir.
				*/

				$orderID = $paymentCode;

				$posts = [
					"hash" => $method_detail['key'], // Mağaza API Hash
					"order_id" => $orderID, // Kendi yazılımınızdaki sipariş numarası
					"callback_url" => site('notify/weepay'), //İşlem durumu hakkında bilgiler ve Payhesap üzerinden ödeme sorgulama aşaması
					"amount" => $amount_fee, // İşlem tutarı
					"installment" => "1", // Taksit sayısı
					"success_url" => site($siteLinks['add-funds']['url']), //Ödeme başarılı ise sayfa buraya yönlencek
					"fail_url" => site($siteLinks['add-funds']['url']),  //Ödeme başarısız ise sayfa buraya yönlencek
					"name" =>  $user["user_first_name"] . ' ' . $user["user_last_name"], // Ödeme yapan müşteri bilgisi
					"email" => $user["user_email"], // Ödeme yapan müşteri bilgisi
					"phone" => $phone, // Ödeme yapan müşteri bilgisi
					"city" => "İstanbul", // Ödeme yapan müşteri bilgisi
					"state" => "Şişli", // Ödeme yapan müşteri bilgisi
					"address" => "Belirtilmemiş", // Ödeme yapan müşteri bilgisi
					"ip" => $user_ip
				];


				$encode = json_encode($posts, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

				$ch = curl_init('https://www.payhesap.com/api/iframe/pay');
				curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
				curl_setopt($ch, CURLOPT_POSTFIELDS, $encode);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				curl_setopt(
					$ch,
					CURLOPT_HTTPHEADER,
					[
						'Content-Type: application/json',
						'Content-Length: ' . strlen($encode)
					]
				);
				$result = curl_exec($ch);

				$decode = json_decode($result, true);

				if (isset($decode['data']['token'])) {

					$newbalance = $user['user_balance'] + $amount;
					$eskibakiye = $user['user_balance'];
					$yenibakiye = $newbalance;


					$insertOrder = $db->insert('deposits')

						->set(array(

							'user_id' => $user['user_id'],

							'order_id' => $paymentCode,

							'deposit_date' => time(),

							'deposit_amount' => $amount,

							'deposit_method' => 99,

							'deposit_status' => 2,
							'eskib' => $eskibakiye,
							'yenib' => $yenibakiye

						));


					
						$body_text = '
					<script src="https://www.payhesap.com/iframe/iframeResizer.min.js"></script>
					<iframe src="https://payhesap.com/api/iframe/' . $decode['data']['token'] . '" id="payhesapiframe" frameborder="0" scrolling="yes" style="width: 100%;height:100%"></iframe>
					<script>iFrameResize({},\'#payhesapiframe\');</script>
						';
						echo $body_text;
						exit;


				} else {
					$error = true;
					$errorText = "Ödeme işlemi başlatılamadı. "/* . print_r($decode)*/;
					$payment_url = false;
				}
			} elseif ($method_id == 4) { // Shopier



				if ($method_detail['fee'] == 1) {

					$amount_fee = $amount_fee + "0.49";
				}



				$form_data = [

					"website_index" => $method_detail['callbackurl'],

					"apikey" => $method_detail['key'],

					"apisecret" => $method_detail['secret'],

					"item_name" => "Bakiye Yükleme İşlemi",

					"order_id" => $paymentCode,

					"buyer_name" => $user["user_first_name"],

					"buyer_surname" => $user["user_last_name"],

					"buyer_email" => $user['user_email'],

					"buyer_phone" => $phone,

					"city" => "NA",

					"billing_address" => "NA",

					"ucret" => $amount_fee

				];



				print_r(generate_shopier_form(json_decode(json_encode($form_data))));



				if ($_SESSION['data']['payment_shopier'] == true) {

					$newbalance = $user['user_balance'] + $amount;
					$eskibakiye = $user['user_balance'];
					$yenibakiye = $newbalance;


					$insertOrder = $db->insert('deposits')

						->set(array(

							'user_id' => $user['user_id'],

							'order_id' => $paymentCode,

							'deposit_date' => time(),

							'deposit_amount' => $amount,

							'deposit_method' => 4,

							'deposit_status' => 2,
							'eskib' => $eskibakiye,
							'yenib' => $yenibakiye

						));



					$success = true;

					$successText = "3D Güvenli ödeme sayfasına yönlendiriliyorsunuz.";

					@$payment_url = @$response;

					unset($_SESSION['data']);
				} else {



					$error = true;

					$errorText = "Ödeme işlemi başlatılamadı.";

					$payment_url = false;
				}
			} elseif ($method_id == 5) { // Shoplemo



				$shoplemo = new \Shoplemo\Config();

				$shoplemo->setAPIKey($method_detail["key"]);

				$shoplemo->setSecretKey($method_detail["secret"]);

				$shoplemo->setServiceBaseUrl('https://payment.shoplemo.com');



				$request = new \Shoplemo\Paywith\CreditCard($shoplemo);

				$request->setUserEmail($user["user_email"]);

				$request->setCustomParams(json_encode(['payment_code' => $paymentCode, 'client_id' => $user["user_id"]]));



				$basket = new \Shoplemo\Model\Basket;

				$basket->setTotalPrice($amount_fee * 100);



				$item1  = new \Shoplemo\Model\BasketItem;

				$item1->setName($amount . ' TL Bakiye Ekleme');

				$item1->setPrice($amount_fee * 100);

				$item1->setType(\Shoplemo\Model\BasketItem::DIGITAL);

				$item1->setQuantity(1);

				$basket->addItem($item1);

				$request->setBasket($basket);

				$request->setRedirectUrl(site());



				if ($request->execute()) {



					$request = json_decode(json_encode($request->getResponse()), true);

					$newbalance = $user['user_balance'] + $amount;
					$eskibakiye = $user['user_balance'];
					$yenibakiye = $newbalance;



					$insertOrder = $db->insert('deposits')

						->set(array(

							'user_id' => $user['user_id'],

							'order_id' => $paymentCode,

							'deposit_date' => time(),

							'deposit_amount' => $amount,

							'deposit_method' => 5,

							'deposit_status' => 2,
							'eskib' => $eskibakiye,
							'yenib' => $yenibakiye

						));



					$success    	= 1;

					$successText	= "3D Güvenli Ödeme sayfasına yönlendiriliyorsunuz.";

					$payment_url  	= $request['url'];
				} else {

					$response =  json_decode($request->getError(), true);

					$error    		= 1;

					$errorText		= "Ödeme işlemi başlatılamadı. Sebep: " . $response['details'];
				}
			} elseif ($method_id == 6) { // PayTR Banka Havale



				$merchant_id      = $method_detail["mid"];

				$merchant_key     = $method_detail["key"];

				$merchant_salt    = $method_detail["salt"];

				$email            = $user["user_email"];

				$payment_amount   = $amount_fee * 100;

				$merchant_oid     = $paymentCode;

				$user_name        = $user["user_first_name"];

				$user_address     = "Belirtilmemiş";

				$user_phone       = $phone;

				$payment_type     = "eft";

				if (isset($_SERVER["HTTP_CLIENT_IP"])) {

					$ip = $_SERVER["HTTP_CLIENT_IP"];
				} elseif (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {

					$ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
				} else {

					$ip = $_SERVER["REMOTE_ADDR"];
				}

				$user_ip          = $ip;

				$timeout_limit    = "360";

				$debug_on         = 1;

				$test_mode        = 0;

				$no_installment   = 0;

				$max_installment  = 0;

				$hash_str         = $merchant_id . $user_ip . $merchant_oid . $email . $payment_amount . $payment_type . $test_mode;

				$paytr_token      = base64_encode(hash_hmac('sha256', $hash_str . $merchant_salt, $merchant_key, true));

				$post_vals = array(

					'merchant_id'	=>	$merchant_id,

					'user_ip'		=>	$user_ip,

					'merchant_oid'	=>	$merchant_oid,

					'email'			=>	$email,

					'payment_amount' =>	$payment_amount,

					'payment_type'	=>	$payment_type,

					'paytr_token'	=>	$paytr_token,

					'debug_on'		=>	$debug_on,

					'timeout_limit'	=>	$timeout_limit,

					'test_mode'		=>	$test_mode

				);



				$ch = curl_init();

				curl_setopt($ch, CURLOPT_URL, "https://www.paytr.com/odeme/api/get-token");

				curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

				curl_setopt($ch, CURLOPT_POST, 1);

				curl_setopt($ch, CURLOPT_POSTFIELDS, $post_vals);

				curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

				curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

				curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);

				curl_setopt($ch, CURLOPT_TIMEOUT, 20);

				$result = @curl_exec($ch);



				if (curl_errno($ch)) {

					$error = true;

					$errorText = "PAYTR IFRAME connection error. err:" . curl_error($ch);
				}

				curl_close($ch);

				$result  = json_decode($result, 1);



				if ($result['status'] == "success") {



					$token  = $result['token'];


					$newbalance = $user['user_balance'] + $amount;
					$eskibakiye = $user['user_balance'];
					$yenibakiye = $newbalance;


					$insertOrder = $db->insert('deposits')->set(array(

						'user_id' => $user['user_id'],

						'order_id' => $merchant_oid,

						'deposit_date' => time(),

						'deposit_amount' => $amount,

						'deposit_method' => 1,

						'deposit_status' => 2,

						'eskib' => $eskibakiye,
						'yenib' => $yenibakiye

					));



					$success = true;

					$successText = "3D Güvenli ödeme sayfasına yönlendiriliyorsunuz.";

					$payment_url = "https://www.paytr.com/odeme/api/" . $token;
				} else {



					$error = true;

					$errorText = "Ödeme işlemi başlatılamadı. Sebep: " . $result['reason'];
				}
			} elseif ($method_id == 8) { // Papara Bireysel Ödeme Modülü

				$newbalance = $user['user_balance'] + $amount;
				$eskibakiye = $user['user_balance'];
				$yenibakiye = $newbalance;


				$insertOrder = $db->insert('deposits')->set(array(

					'user_id' => $user['user_id'],

					'order_id' => uniqid() . $user["user_id"],

					'deposit_date' => time(),

					'deposit_amount' => $amount,

					'deposit_method' => 8,

					'deposit_status' => 2,

					'eskib' => $eskibakiye,
					'yenib' => $yenibakiye

				));

				$orderId = $db->lastId();

				$callback_url = strtok('http' . (isset($_SERVER['HTTPS']) ? 's' : '') . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], '?') . '?check-order';

				$payment_id = $method_detail['prefix'] . $orderId;

				$amount_fee = number_format(floatval($amount_fee), 2, '.', '');

				$currency = 'TL';

				$papara_number = $method_detail['number'];

				$body_text .= '
				<link href="https://fonts.googleapis.com/css2?family=Montserrat&display=swap" rel="stylesheet">
				<link rel="stylesheet" href="' . public_url('papara/modal.css') . '">
				<div class="modal" tabindex="-1" role="dialog" id="paparaModal" style="font-family:Montserrat,sans-serif">
				<div class="modal-dialog modal-lg" role="document">
				<div class="modal-content" style="background:#fff!important;color:#000">
				<div class="modal-header" style="display:flex;align-items:center">
				<h5 class="modal-title" style="flex-grow:1;font-size:17px">' . htmlspecialchars($method_detail['name']) . '</h5>
				<button type="button" class="close" data-dismiss="modal" aria-label="Kapat">
				<span aria-hidden="true">&times;</span>
				</button>
				</div>
				<div class="modal-body">
				<div class="row align-items-center" data-check="' . htmlspecialchars($callback_url) . '" data-order="' . $orderId . '" data-success="' . htmlspecialchars(rtrim(strtok($callback_url, '?'), 'addfunds')) . '">
				</div>
				<div class="border-bottom border-lighten mb-3">
				<div class="row mb-3 align-items-center">
				<div class="col-lg">
				<h5 style="font-size:17px"  class="m-0 d-lg-flex align-items-center"><span class="mr-2 d-flex d-lg-inline">Papara Hesap Numarası:</span><b style="color:#0d6efd" class="mr-2 papara-number">' . htmlspecialchars($papara_number) . '</b><a class="d-inline-flex" href="javascript:;" onclick="copyNumber()"><img src="' . public_url('papara/copy.png') . '" height="20"></a></h5>
				<p style="font-size:15px" class="my-4">' . sprintf('Yukarıdaki Papara numarasına açıklamaya <b>%s</b> yazarak <b>%s</b> ödeme yapmanız gereklidir.', $payment_id, $amount_fee . ' ' . $currency) . '</p>
				<p style="font-size:15px" class="my-4">İsterseniz sağ taraftaki karekodu Papara uygulamasına okutup ödeme yapabilirsiniz.</p>
				<p style="font-size:15px" class="m-0"><a href="javascript:;" data-toggle="modal" style="color:#0d6efd;text-decoration:underline" data-target="#paparaModal2">Karekodu Nasıl Okutabilirim?</a></p>
				<div class="mt-4 d-flex align-items-center">
				<img data-checked="' . public_url('papara/check.svg') . '" src="' . public_url('papara/spinner.svg') . '" alt="Ödeme Bekleniyor..." height="50">
				<div class="ml-2 text-danger">
				<h5 class="m-0" data-confirmed="Ödeme Onaylandı!" style="font-size:15px">Ödeme Bekleniyor...</h5>
				</div>
				</div>
				</div>
				<div class="col-lg-auto text-center text-lg-right">
				<img width="250" height="260" src="https://chart.googleapis.com/chart?chs=300x300&cht=qr&chl=' . rawurlencode(sprintf('https://www.papara.com/personal/qr?accountNumber=%s&currency=0&amount=%s&description=%s', $papara_number, $amount_fee, $payment_id)) . '&choe=UTF-8" alt="">
				</div>
				</div>
				</div>
				<p class="m-0">Yaptığınız ödemeler yaklaşık 30 sn içinde sistem tarafından algılanacak ve siparişiniz otomatik olarak onaylanacaktır.</p>
				</div>
				</div>
				</div>
				</div>
				<div class="modal fade" id="paparaModal2" tabindex="-1" role="dialog" aria-labelledby="paparaModal2Label" aria-hidden="true" style="font-family:Montserrat,sans-serif">
				<div class="modal-dialog modal-lg" role="document">
				<div class="modal-content" style="background:#fff!important;color:#000">
				<div class="modal-header" style="display:flex;align-items:center">
				<h5 class="modal-title" style="flex-grow:1;font-size:17px">Papara\'da QR Kod ile Ödeme Yapma</h5>
				<button type="button" class="close" data-dismiss="modal" aria-label="Kapat">
				<span aria-hidden="true">&times;</span>
				</button>
				</div>
				<div class="modal-body" style="font-size:15px">
				<div class="mb-4"><b>1. Adım:</b> Papara uygulamasını açın. Alt taraftaki menüde <b>QR İşlemleri</b> kısmına tıklayın.</div>
				<div class="mb-4"><b>2. Adım:</b> Karşınıza çıkan kamera ile ekranda gözüken QR kodu taratın.</div>
				<div class="mb-lg-4"><b>3. Adım:</b> Ödeme tutarını kontrol edin, eğer doğru ise işlemi onaylayın.</div>
				<div class="row d-none d-lg-flex">
				<div class="col text-left">
				<img src="' . public_url('papara/step-1.png') . '">
				</div>
				<div class="col text-center">
				<img src="' . public_url('papara/step-2.png') . '">
				</div>
				<div class="col text-right">
				<img src="' . public_url('papara/step-3.png') . '">
				</div>
				</div>
				</div>
				</div>
				</div>
				</div>
				<script>
				var check_url = document.querySelector("[data-check]").getAttribute("data-check");
				var order_id = document.querySelector("[data-order]").getAttribute("data-order");

				function copyNumber() {
					var range, selection;
					if (window.getSelection && document.createRange) {
						selection = window.getSelection();
						range = document.createRange();
						range.selectNodeContents(document.querySelector(".papara-number"));
						selection.removeAllRanges();
						selection.addRange(range);
						} else if (document.selection && document.body.createTextRange) {
							range = document.body.createTextRange();
							range.moveToElementText(document.querySelector(".papara-number"));
							range.select();
						}
						document.execCommand("copy");
					}
					var timer = setInterval(function() {
						var http = new XMLHttpRequest();
						var url = check_url;
						var params = "order_id=" + order_id;
						http.open("POST", url, true);

						http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

						http.onreadystatechange = function() {
							if (http.readyState == 4 && http.status == 200) {
								var result = JSON.parse(http.responseText);
								if (result.confirmed) {
									clearInterval(timer);
									var check = document.querySelector("[data-checked]");
									check.src = check.getAttribute("data-checked");
									check.style.height = "45px";
									check.style.margin = "2.5px";
									var confirm = document.querySelector("[data-confirmed]");
									confirm.innerText = confirm.getAttribute("data-confirmed");
									confirm.parentNode.classList.remove("text-danger");
									confirm.parentNode.classList.add("text-success");
									setTimeout(function() {
										location.href = document.querySelector("[data-check]").getAttribute("data-success");
										}, 2000);
									}
								}
							}
							http.send(params);
							}, 20000);
							document.addEventListener("DOMContentLoaded", function() {
								$("#paparaModal").modal("show");
								});
								</script>
								';
			}
		}
	} else {

		$error = false;
		$success = false;
		$payment_url = false;
	}



	if (@$payment_url) {

		echo '<script>setInterval(function(){window.location="' . $payment_url . '"},2000)</script>';
	}



	$title = "{ADD_FUNDS_PAGE_TITLE}";

	$accounts = $db->from('bank_accounts')->all();

	$payments = $db->from('payment_methods')->orderby('method_line', 'ASC')->all();

	$bankpayment = $db->from('payment_methods')->where('method_id', 7)->first();

	$bankpayment = json_decode($bankpayment['method_details'], true);



	$integration = "";

	foreach ($plugins as $plugin) {



		if ($plugin['app_id'] !== 1 && $plugin['app_id'] !== 2 && $plugin['app_id'] !== 3 && $plugin['app_id'] !== 4 && $plugin['app_id'] !== 5) {



			@$data = json_decode($plugin['app_data'], true);



			if (@$data['visibility'] == 0) { // Tüm Sayfalar

				@$integration .= $data['code'];
			} elseif (@$data['visibility'] == 1) { // Giriş Yapanlar

				@$integration .= $data['code'];
			}
		}
	}



	$tempPayments = [];

	foreach ($payments as $payment) :

		if ($payment['method_id'] !== 7) :

			$detail = json_decode($payment['method_details'], true);

			$payment['name'] = $detail['name'];

			$payment['status'] = $detail['status'];



			if ($payment['status'] == 1) :

				$tempPayments[] = $payment;

			endif;

		endif;

	endforeach;

	$payments = $tempPayments;





	$deposits = $db->from('deposits')
		->leftjoin('users', 'users.user_id = deposits.user_id')
		->where('users.user_id', $user["user_id"])
		->orderby('deposits.deposit_id', 'DESC')
		->all();

	$tempDeposits = [];

	foreach ($deposits as $deposit) {

		if ($deposit["deposit_status"] == 2) {

			$deposit["deposit_status"] = "{PAYMENT_WAIT}";
		} elseif ($deposit["deposit_status"] == 1) {

			$deposit["deposit_status"] = "{PAYMENT_SUCCESS}";
		} else {

			$deposit["deposit_status"] = "{PAYMENT_FAILED}";
		}

		$tempDeposits[] = $deposit;
	}

	$deposits = $tempDeposits;

	$balance_history_txt .= '
	<table id="table" class="table order-table table-grey" style="margin-bottom:0;">
	<thead>
	<tr>
	<th>#</th>
	<th>Yöntem</th>
	<th>Tarih</th>
	<th>Tutar</th>
	<th></th>
	</tr>
	</thead>
	<tbody>
	';

	foreach ($deposits as $deposit) : $methods = $db->from('payment_methods')
			->where('method_id', $deposit['deposit_method'])->first();
		if ($methods) {
			$deposit['method_title'] = $methods['method_title'];
		}
		$balance_history_txt .= '
		<tr>
		<td>' . $deposit["deposit_id"] . '</td>
		<td>';
		if ($deposit['deposit_method'] == 158) :
			$balance_history_txt .= 'Manuel Bakiye Ekleme';
		elseif ($deposit['deposit_method'] == 159) :
			$balance_history_txt .= 'Manuel Bakiye Eksiltme';
		else :
			$balance_history_txt .= $deposit["method_title"];
		endif;
		$balance_history_txt .= '
		</td>
		<td>' . date("d.m.y H:i:s", $deposit["deposit_date"]) . '</td>
		<td>' . $deposit["deposit_amount"] . '</td>
		<td>' . $deposit["deposit_status"] . '</td>
		</tr>
		';

	endforeach;
	$balance_history_txt .= '
	</tbody>
	</table>
	';



	$balance_history_txt = replace($balance_history_txt);

	$extra = [
		"{BALANCE_HISTORY}" => $balance_history_txt,
		"{INTEGRATIONS}" => $integration

	];





	$page_content = $db->from('pages')->where('id', 4)->first();
	$seo = json_decode($page_content['page_seo'], true);

	$meta = [
		"title" => $seo['title'],
		"desc" 	=> $seo['desc'],
		"keyw" 	=> $seo['keyw']
	];


	require view("add-funds");
} else {



	header("Location:" . site());
}



$output = ob_get_clean();

$output = str_replace('</body>', $body_text . '</body>', $output);

echo replace($output, $extra);
