<?php
if(@$odeme_yontem==Null){
	
		$paymenta = $db->prepare("SELECT ad,deger FROM payment");

    $paymenta->execute(array());

    $paymenta = $paymenta->fetchAll(PDO::FETCH_ASSOC);



$a=0;

while(isset($paymenta[$a])){

	$payment[$paymenta[$a]["ad"]]=$paymenta[$a]["deger"];

	$a++;

}

	$querys = $db->query("SELECT * FROM siparis where durum='10' ORDER BY id DESC"); 
                while ($dataax = $querys->fetch(PDO::FETCH_OBJ)) {
					
					$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'https://api.stripe.com/v1/payment_intents/'.$dataax->pkey);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');

curl_setopt($ch, CURLOPT_USERPWD, $payment["stripe_api"] . ':' . '');
// curl_setopt($ch, CURLOPT_USERPWD, 'sk_test_4eC39HqLyjWDarjtT1zdp7dc' . ':' . '');

$result = curl_exec($ch);
if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
}
curl_close($ch);
$js=json_decode($result,true);
    $merchant_oid=htmlentities($dataax->id."a".rand()."z1", ENT_QUOTES, "UTF-8");
$dataal=explode("a", $merchant_oid);
            $mik=$dataal[0];   
			$mysqliuye2 =  siparis($mik);
	  
if($mysqliuye2["id"]==Null || $mysqliuye2["durum"]!="10"){
echo "OK";
continue;
}
$mail=$mysqliuye2["mail"];
       if($js["status"]=="succeeded" || $js["status"]=="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);
		                   
		
		                       
$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);
		
	}
		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"])));
		sendEmail2($mail,$subject,$content);
		
		 $dataa = $db->prepare("UPDATE siparis SET durum=?, stok=? where id=?");
        $dataa->execute([$durum,$stokyaz,$mik]);

                                          echo "OK";
                                      
                                            
      
     
                                           
  	}
	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.";
		sendEmail2($mail,$subject,$content);
		 $dataa = $db->prepare("UPDATE siparis SET durum=? where id=?");
        $dataa->execute(["3",$mik]);
   echo "OK";
                                      
}
} header("Location: ".$site."?sip=1");   exit;
}

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


define('STRIPE_API_KEY', $payment["stripe_api"]); 
define('STRIPE_PUBLISHABLE_KEY', $payment["stripe_publishable"]); 

define('STRIPE_SUCCESS_URL', $site."?callback=Stripe"); //Payment success URL 
define('STRIPE_CANCEL_URL', $site."?sip=0");
?>

<div id="paymentResponse" class="hidden"></div>
	


<!-- Payment button -->
<button class="stripe-button" type="button" id="payButton">
    <div class="spinner hidden" id="spinner"></div>
    <span id="buttonText">Bekleyiniz...</span>
</button>
<script src="https://js.stripe.com/v3/"></script>
<script>

setTimeout(function() {
	$("#payButton").click();
	}, 2000);
// Set Stripe publishable key to initialize Stripe.js
const stripe = Stripe('<?php echo STRIPE_PUBLISHABLE_KEY; ?>');

// Select payment button
const payBtn = document.querySelector("#payButton");

// Payment request handler
payBtn.addEventListener("click", function (evt) {
    setLoading(true);

    createCheckoutSession().then(function (data) {
        if(data.sessionId){
            stripe.redirectToCheckout({
                sessionId: data.sessionId,
            }).then(handleResult);
        }else{
            handleResult(data);
        }
    });
});
    
// Create a Checkout Session with the selected product
const createCheckoutSession = function (stripe) {
    return fetch("<?=$site;?>?modulepay=Stripe&mik=<?=round($amount,2);?>&pay=<?=$sipcek["id"];?>", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify({
            createCheckoutSession: 1,
        }),
    }).then(function (result) {
        return result.json();
    });
};

// Handle any errors returned from Checkout
const handleResult = function (result) {
    if (result.error) {
        showMessage(result.error.message);
    }
    
    setLoading(false);
};

// Show a spinner on payment processing
function setLoading(isLoading) {
    if (isLoading) {
        // Disable the button and show a spinner
        payBtn.disabled = true;
        document.querySelector("#spinner").classList.remove("hidden");
        document.querySelector("#buttonText").classList.add("hidden");
    } else {
        // Enable the button and hide spinner
        payBtn.disabled = false;
        document.querySelector("#spinner").classList.add("hidden");
        document.querySelector("#buttonText").classList.remove("hidden");
    }
}

// Display message
function showMessage(messageText) {
    const messageContainer = document.querySelector("#paymentResponse");
	
    messageContainer.classList.remove("hidden");
    messageContainer.textContent = messageText;
	
    setTimeout(function () {
        messageContainer.classList.add("hidden");
        messageText.textContent = "";
    }, 5000);
}
</script>
<?php
