<?php

if (isset($_POST['token']) && isset($_GET['sip'])) {


    $iyzico_api   = $payment["iyzico_api"];
    $iyzico_guvenlik  = $payment["iyzico_secret"];
    
include(__ROOT__."/system/payment/IyzipayBootstrap.php");


IyzipayBootstrap::init();


if(@$_POST["token"]==Null || @$_GET["sip"]==Null){
echo 'Data error';
	exit;
}
$token=htmlspecialchars($_POST["token"], ENT_QUOTES, "UTF-8");
$sip=htmlspecialchars($_GET["sip"], ENT_QUOTES, "UTF-8");

$request = new \Iyzipay\Request\RetrieveCheckoutFormRequest();
$request->setLocale(\Iyzipay\Model\Locale::TR);
$request->setConversationId("$sip");
$request->setToken("$token");
$checkoutForm = \Iyzipay\Model\CheckoutForm::retrieve($request, Config::options());

//print_r($checkoutForm->getStatus());
 $odeme_durum=$checkoutForm->getPaymentStatus();

//gonderılen orderid
$orderid=$checkoutForm->getbasketId();

# print result
 $say=0;


$merchant_oid=$sip;

            $mik=$merchant_oid;
			
      $mysqliuye2 =  siparis($mik);
	  
if($mysqliuye2["id"]==Null || $mysqliuye2["durum"]!="10"){
echo "OK";
	exit;
}
$mail=$mysqliuye2["mail"];
	if( $odeme_durum =="SUCCESS" ) {
		



     
      
$prod=json_decode($mysqliuye2["urun"],true);
  
	include(__ROOT__."/system/class/turkpin.php");
foreach($prod as $deg => $val){
$siparisstok="";
			$urun=urun($val["product"]);
		  $adet=$val["adet"];
	
			if($urun["urun_stok"]!=Null){
				$nswt=$urun["urun_stok"]-$adet;
		 $dataa = $db->prepare("UPDATE urun SET urun_stok=? where id=?");
        $dataa->execute([$nswt,$val["product"]]);
			}

	$getir="0";
			
$opsiyonkey=moduller("opsiyonkey");
$turkpin=moduller("turkpin");
if($turkpin["durum"]=="1" && $urun["oyunKod"]!=Null){
		   $siparisstok=turkpin($val["product"],$adet);
		   if($siparisstok==Null || $durum=="0"){
			   $durum="0";
		   }
		   else{
			   $durum="2";
		   }
}
else{
if($opsiyonkey["durum"]=="1"){
	foreach($val["opsiyon"] as $degx => $valx){
		$opt=opsiyon($valx);
		if($opt["stok"]!=Null){
				    $stok = explode("\n", $opt["stok"]);
			$stoksay=count($stok);  
			if($stok["0"]==""){
	  	$stoksay="0";
	  }
	  if($stoksay==0){
			$durum="0";
	  }
	  else{
		  
		  $siparisstok=$stok[0];
		  $lisay=2;
		  $say=1;
		  while($adet>=$lisay && $stok[$say]!=Null){
			  $siparisstok=$siparisstok.", ".$stok[$say];
			  $say++;
			  $lisay++;
		  }
			$yenistok=$stok[$say];
			$yenisay=$say+1;
			while(@$stok[$yenisay]!=Null){
			$yenistok=$yenistok."\n".$stok[$yenisay];
			$yenisay++;
		}
		 if($durum!="0"){
		$durum="2";
		 }
		 $dataa = $db->prepare("UPDATE urun_opsiyon SET stok=? where id=?");
        $dataa->execute([$yenistok,$valx]);
		
			}
			$getir="1";
		}
		
	}
}
			if($getir=="0"){
		    $stok = explode("\n", $urun["stok"]);
			$stoksay=count($stok);  
			if($stok["0"]==""){
	  	$stoksay="0";
	  }
	  if($stoksay==0){
			$durum="0";
	  }
	  else{
		  
		  $siparisstok=$stok[0];
		  $lisay=2;
		  $say=1;
		  while($adet>=$lisay && $stok[$say]!=Null){
			  $siparisstok=$siparisstok.", ".$stok[$say];
			  $say++;
			  $lisay++;
		  }
			$yenistok=$stok[$say];
			$yenisay=$say+1;
			while(@$stok[$yenisay]!=Null){
			$yenistok=$yenistok."\n".$stok[$yenisay];
			$yenisay++;
		}
		 if($durum!="0"){
		$durum="2";
		 }
		
		 $dataa = $db->prepare("UPDATE urun SET stok=? where id=?");
        $dataa->execute([$yenistok,$val["product"]]);
		
			}
			}}
	  $stokyaz[$deg]=$siparisstok;
}
						$siparisstok=implode(", ",$stokyaz);
	$stokyaz=json_encode($stokyaz, JSON_UNESCAPED_UNICODE);
		                   
	  
		
		
		
		if($durum=="2"){
		$subject="Sipariş Başarıyla Tamamlandı";
					$mailmsgs = $db->prepare("SELECT ad,mesaj FROM mail where ad='siparis_tamamlandi'");
		}
		else{
		$subject="Sipariş Başarıyla Alındı";
					$mailmsgs = $db->prepare("SELECT ad,mesaj FROM mail where ad='siparis_odendi'");
		}
    $mailmsgs->execute(array());
    $mailmsgs = $mailmsgs->fetchAll(PDO::FETCH_ASSOC);

$mailmsgs["mesaj"]=$mailmsgs["0"]["mesaj"];

		$content=str_replace("{siparis_stok}",$siparisstok,str_replace("{siparis_no}",$mysqliuye2["sip_no"],str_replace("{isim_soyisim}",$mysqliuye2["ad"],$mailmsgs["mesaj"])));
	
		 sendEmail($mail,$subject,$content);
	
		 $dataa = $db->prepare("UPDATE siparis SET durum=?, stok=? where id=?");
        $dataa->execute([$durum,$stokyaz,$mik]);
                                            
$telegram=eklenti("telegram");
    if($telegram["durum"]==1){
		  $json=json_decode($telegram["deger"],true); 
		 $telegram_key=$json["Bot Key"];
  $telegramchatid=$json["Chat ID"];

		                    
					$js=json_decode($mysqliuye2["urun"],true);
					if($js[0]==Null){
						$urun=urun($mysqliuye2["urun"]);
						$urunad=$urun["ad"];
					}
					else{
						$urunad=array();
						foreach($js as $deg=>$val){
						$urun=urun($val["product"]);
						$urunad[]=$val["adet"]." adet ".$urun["ad"];
						}
						$urunad=implode(", ",$urunad);
					}
    $msg=$mysqliuye2["tarih"]." tarihinde ".$mysqliuye2["mail"]." mail adresli üye ".html_entity_decode($urunad, ENT_QUOTES, "UTF-8")." ürünü sipariş verdi.";
 
   $url='https://api.telegram.org/bot'.$telegram_key.'/sendMessage';
   $data=array('chat_id'=>$telegramchatid,'text'=>$msg);
        $options=array('http'=>array('method'=>'POST','header'=>"Content-Type:application/x-www-form-urlencoded\r\n",'content'=>http_build_query($data),),);
        $context=stream_context_create($options);
        $result=file_get_contents($url,false,$context);
		
	}
	
header("Location: ".$site."?sip=1");
	exit;

	} else { 


		$subject="Sipariş Başarısız Oldu";
		$content="Merhaba ".$mysqliuye2["ad"].",<br>
		Siparişiniz başarısız olmuştur. Ürünü satın alabilmek için lütfen tekrar sipariş veriniz.";
		sendEmail($mail,$subject,$content);
		 $dataa = $db->prepare("UPDATE siparis SET durum=? where id=?");
        $dataa->execute(["3",$mik]);
header("Location: ".$site."?sip=0");
	exit;
                                            
	}



                                          echo "success";
                                          exit;
                                            




}

if(@$odeme_yontem==Null){
	echo "Eksik data";	exit;
}
 $balance=$amount;

    $balance=round($amount,2);
  $ad=$ad;
    $email = $mail;

    $payid = $sipcek["id"];
    $telefon = $telefon;
    $sehir = html_entity_decode("Yok");
    $adres = $adres;
    $ilce = html_entity_decode("Yok");

$kart_ad=htmlentities($_POST["kart_ad"], ENT_QUOTES, "UTF-8");
$kart_no=htmlentities($_POST["kart_no"], ENT_QUOTES, "UTF-8");
$kart_ay=htmlentities($_POST["kart_ay"], ENT_QUOTES, "UTF-8");
$kart_yil=htmlentities($_POST["kart_yil"], ENT_QUOTES, "UTF-8");
$kart_cvc=htmlentities($_POST["kart_cvc"], ENT_QUOTES, "UTF-8");
    $iyzico_api   = $payment["iyzico_api"];
    $iyzico_guvenlik  = $payment["iyzico_secret"];
include(__ROOT__."/system/payment/IyzipayBootstrap.php");


IyzipayBootstrap::init();

class Config
{
    public static function options()
    {
        global $iyzico_api;
        global $iyzico_guvenlik;
        $options = new \Iyzipay\Options();
        $options->setApiKey($iyzico_api);
        $options->setSecretKey($iyzico_guvenlik);
        $options->setBaseUrl('https://sandbox-api.iyzipay.com');
//https://api.iyzipay.com
        return $options;
    }
}

# make request
$request = new \Iyzipay\Request\CreateCheckoutFormInitializeRequest();
$request->setLocale(\Iyzipay\Model\Locale::TR);
$request->setConversationId($sipcek["id"]);
$request->setPrice($balance);
$request->setPaidPrice($balance);
$request->setCurrency(\Iyzipay\Model\Currency::TL);
//$request->setInstallment(1);
$request->setBasketId(time());
//$request->setPaymentChannel(\Iyzipay\Model\PaymentChannel::WEB);
$request->setPaymentGroup(\Iyzipay\Model\PaymentGroup::PRODUCT);
$request->setCallbackUrl($site."?callback=Iyzico&sip=".$sipcek["id"]);
/*
$paymentCard = new \Iyzipay\Model\PaymentCard();
$paymentCard->setCardHolderName($kart_ad);
$paymentCard->setCardNumber($kart_no);
$paymentCard->setExpireMonth($kart_ay);
$paymentCard->setExpireYear($kart_yil);
$paymentCard->setCvc($kart_cvc);
$paymentCard->setRegisterCard(0);
$request->setPaymentCard($paymentCard);
*/
$buyer = new \Iyzipay\Model\Buyer();
$buyer->setId($payid);
$buyer->setName($ad);
$buyer->setSurname("Yok");
$buyer->setGsmNumber($telefon);
$buyer->setEmail($email);
$buyer->setIdentityNumber("11111111111");
$buyer->setLastLoginDate(date("Y-m-d H:i:s"));
$buyer->setRegistrationDate("2021-04-21 15:12:09");
$buyer->setRegistrationAddress($adres);
$buyer->setIp($_SERVER["REMOTE_ADDR"]);
$buyer->setCity("Istanbul");
$buyer->setCountry("Turkey");
$buyer->setZipCode("34732");
$request->setBuyer($buyer);

$shippingAddress = new \Iyzipay\Model\Address();
$shippingAddress->setContactName($ad);
$shippingAddress->setCity("Bursa");
$shippingAddress->setCountry("Turkey");
$shippingAddress->setAddress($adres);
$shippingAddress->setZipCode("34742");
$request->setShippingAddress($shippingAddress);

$billingAddress = new \Iyzipay\Model\Address();
$billingAddress->setContactName($ad);
$billingAddress->setCity("Bursa");
$billingAddress->setCountry("Turkey");
$billingAddress->setAddress($adres);
$billingAddress->setZipCode("34742");
$request->setBillingAddress($billingAddress);

$basketItems = array();
$firstBasketItem = new \Iyzipay\Model\BasketItem();
$firstBasketItem->setId(time());
$firstBasketItem->setName("Payment");
$firstBasketItem->setCategory1("Yok");
$firstBasketItem->setCategory2("Yok");
$firstBasketItem->setItemType(\Iyzipay\Model\BasketItemType::VIRTUAL);
$firstBasketItem->setPrice($balance);
$basketItems[0] = $firstBasketItem;


$request->setBasketItems($basketItems);

# make request
$payment = \Iyzipay\Model\CheckoutFormInitialize::create($request, Config::options());

# print response
print_r($payment->getErrorMessage());
print_r($payment->getCheckoutFormContent());
ob_end_flush();
?><div id="iyzipay-checkout-form" class="responsive"></div>