<?php

if (isset($_POST['res']) && isset($_POST['hash'])) {


 $username=$payment["shopier_obs"];
$key=$payment["shopier_obssifre"];
$hash=hash_hmac('sha256',$_POST['res'].$username,$key,false);
if (strcmp($hash,$_POST['hash'])!=0) {
    die();
}


$json_result=base64_decode($_POST['res']);
$array_result=json_decode($json_result,true);


$email=$array_result['email'];
$email=htmlentities($email, ENT_QUOTES, "UTF-8");
$orderid=$array_result['orderid'];
$orderid=htmlentities($orderid, ENT_QUOTES, "UTF-8");
$currency=$array_result['currency']; 
$currency=htmlentities($currency, ENT_QUOTES, "UTF-8");
$price=$array_result['price'];
$price=htmlentities($price, ENT_QUOTES, "UTF-8");
$buyername=$array_result['buyername'];
$buyername=htmlentities($buyername, ENT_QUOTES, "UTF-8");
$buyersurname=$array_result['buyersurname'];
$buyersurname=htmlentities($buyersurname, ENT_QUOTES, "UTF-8");
$productcount=$array_result['productcount'];
$productcount=htmlentities($productcount, ENT_QUOTES, "UTF-8");
$productid=$array_result['productid'];
$productid=htmlentities($productid, ENT_QUOTES, "UTF-8");
$customernote=$array_result['customernote']; 
$customernote=htmlentities($customernote, ENT_QUOTES, "UTF-8");
$istest=$array_result['istest'];
$istest=htmlentities($istest, ENT_QUOTES, "UTF-8");
 $buyersurname=str_replace("b", ".", $buyersurname);
$dataal=explode("a", $buyersurname);

    $mik=$dataal[0];
      $mysqliuye2 =  siparis($mik);
	  
if($mysqliuye2["id"]==Null || $mysqliuye2["durum"]!="10"){
echo "success";
	exit;
}

$mail=$mysqliuye2["mail"];

     
      
$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"])));
		sendEmail($mail,$subject,$content);
		
		 $dataa = $db->prepare("UPDATE siparis SET durum=?, stok=? where id=?");
        $dataa->execute([$durum,$stokyaz,$mik]);

                                          echo "success";
                                          exit;





}

if(@$odeme_yontem==Null){
	echo "Eksik data";	exit;
}
 $balance=$amount;
$balance=round($balance,2);
  $ad=$ad;
    $email = $mail;

    $soyad = $sipcek["id"];
    $telefon = $telefon;
    $sehir = "Yok";
    $adres = $adres;
    $ilce = "Yok";
class Shopier
    { 
        private $payment_url = 'https://www.shopier.com/ShowProduct/api_pay4.php';
        private
            $api_key,
            $api_secret,
            $module_version,
            $buyer = [];

        public function __construct($api_key, $api_secret, $module_version = ('1.0.4'))
        {
            $this->api_key = $api_key;
            $this->api_secret = $api_secret;
            $this->module_version = $module_version;
        }

        public function setBuyer(array $fields = [])
        {
            $this->buyerValidateAndLoad($this->buyerFields(), $fields);
        }

        public function setOrderBilling(array $fields = [])
        {
            $this->buyerValidateAndLoad($this->orderBillingFields(), $fields);
        }

        public function setOrderShipping(array $fields = [])
        {
            $this->buyerValidateAndLoad($this->orderShippingFields(), $fields);
        }

        private function buyerValidateAndLoad($validationFields, $fields)
        {
            $diff = array_diff_key($validationFields, $fields);

            if (count($diff) > 0)
                throw new Exception(implode(',', array_keys($diff)) . ' fields are required');

            foreach ($validationFields as $key => $buyerField) {
                $this->buyer[$key] = $fields[$key];
            }
        }

        public function generateFormObject($order_id, $order_total, $callback_url)
        {

            $diff = array_diff_key($this->buyerFields(), $this->buyer);

            if (count($diff) > 0)
                throw new Exception(implode(',', array_keys($diff)) . ' fields are required use "setBuyer()" method ');

            $diff = array_diff_key($this->orderBillingFields(), $this->buyer);

            if (count($diff) > 0)
                throw new Exception(implode(',', array_keys($diff)) . ' fields are required use "setOrderBilling()" method ');

            $diff = array_diff_key($this->orderShippingFields(), $this->buyer);

            if (count($diff) > 0)
                throw new Exception(implode(',', array_keys($diff)) . ' fields are required use "setOrderShipping()" method ');


            $args = array(
                'API_key' => $this->api_key,
                'website_index' => 1,
                'platform_order_id' => $order_id,
                'product_name' => 'Balance',
                'product_type' => 1, //1 : downloadable-virtual 0:real object,2:default
                'buyer_name' => $this->buyer['first_name'],
                'buyer_surname' => $this->buyer['last_name'],
                'buyer_email' => $this->buyer['email'],
                'buyer_account_age' => 0,
                'buyer_id_nr' => $this->buyer['id'],
                'buyer_phone' => $this->buyer['phone'],
                'billing_address' => $this->buyer['billing_address'],
                'billing_city' => $this->buyer['billing_city'],
                'billing_country' => $this->buyer['billing_country'],
                'billing_postcode' => $this->buyer['billing_postcode'],
                'shipping_address' => $this->buyer['shipping_address'],
                'shipping_city' => $this->buyer['shipping_city'],
                'shipping_country' => $this->buyer['shipping_country'],
                'shipping_postcode' => $this->buyer['shipping_postcode'],
                'total_order_value' => $order_total,
                'currency' => $this->getCurrency(),
                'platform' => 0,
                'is_in_frame' => 0,
                'current_language' => $this->lang(),
                'modul_version' => $this->module_version,
                'random_nr' => rand(100000, 999999)
            );


            $data = $args["random_nr"] . $args["platform_order_id"] . $args["total_order_value"] . $args["currency"];
            $signature = hash_hmac('sha256', $data, $this->api_secret, true);
            $signature = base64_encode($signature);
            $args['signature'] = $signature;
            $args['callback'] = $callback_url;

            return [
                'elements' => [
                    [
                        'tag' => 'form',
                        'attributes' => [
                            'id' => 'shopier_form_special',
                            'method' => 'post',
                            'action' => $this->payment_url
                        ],
                        'children' => array_map(function ($key, $value) {
                            return [
                                'tag' => 'input',
                                'attributes' => [
                                    'name' => $key,
                                    'value' => $value,
                                    'type' => 'hidden',
                                ]
                            ];

                        }, array_keys($args), array_values($args))
                    ]
                ]
            ];

        }


        public function generateForm($order_id, $order_total, $callback_url)
        {
            $obj = $this->generateFormObject($order_id, $order_total, $callback_url);

            return $this->recursiveHtmlStringGenerator($obj['elements']);
        }

        public function run($order_id, $order_total, $callback_url)
        {

            $form = $this->generateForm($order_id, $order_total, $callback_url);

            return '<!doctype html>
             <html lang="en">
            <head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title></title>
     </head>
' . $form . '
    <body>
        <script type="text/javascript">
                    document.getElementById("shopier_form_special").submit();
        </script>
     </body>
    </html>
     ';
        }

        // generateFormObject() sınıfının verdiği formattaki arrayden structure çıkartan yapıdırı.
        private function recursiveHtmlStringGenerator(array $elements = [], $string = null)
        {
            foreach ($elements as $element) {
                $attributes = $element['attributes'] ?? [];
                $attributes = array_map(function ($key, $value) {
                    return $key . '="' . $value . '"';
                }, array_keys($attributes), array_values($attributes));
                $attribute_string = implode(' ', $attributes);
                $html_in = $element['source'] ?? null;
                $string .= "<{$element['tag']} {$attribute_string} > " . $html_in;

                if (isset($element['children']) && is_array($element['children']))
                    $string = $this->recursiveHtmlStringGenerator($element['children'], $string);

                $string .= "</{$element['tag']}>";

            }
            return $string;
        }

        //shopierden gelen dataları kontrol eder.
        public function verifyShopierSignature($post_data)
        {

            if (isset($post_data['platform_order_id'])) {
                $order_id = $post_data['platform_order_id'];
                $random_nr = $post_data['random_nr'];
                if ($order_id != '') {
                    $signature = base64_decode($_POST["signature"]);
                    $expected = hash_hmac('sha256', $random_nr . $order_id, $this->api_secret, true);

                    if ($signature == $expected)
                        return true;

                }


            }
            return false;
        }

        private function buyerFields()
        {
            return [
                'id' => true,
                'first_name' => true,
                'last_name' => true,
                'email' => true,
                'phone' => true,
            ];
        }

        private function orderBillingFields()
        {
            return [
                'billing_address' => true,
                'billing_city' => true,
                'billing_country' => true,
                'billing_postcode' => true,
            ];
        }

        private function orderShippingFields()
        {
            return [
                'shipping_address' => true,
                'shipping_city' => true,
                'shipping_country' => true,
                'shipping_postcode' => true,
            ];
        }

        private function getCurrency()
        {
            $currencyList = [
                'TRY' => 0,
                'USD' => 1,
                'EUR' => 2,
            ];
            return $currencyList[strtoupper($this->currency)] ?? 0;
        }

        private function lang()
        {
            $current_language = "tr-TR";
            $current_lan = 0;
            if ($current_language == "tr-TR") {
                $current_lan = 0;
            }

            return $current_lan;
        }

    }

    define('API_KEY', $payment["shopier_api"]);
define('API_SECRET',  $payment["shopier_sifre"]);

$shopier = new Shopier(API_KEY, API_SECRET);

$shopier->setBuyer([
    'id' => rand(0, 100),
    'first_name' => $ad, 'last_name' => $soyad, 'email' => $email, 'phone' => $telefon]);
$shopier->setOrderBilling([
    'billing_address' => $adres,
    'billing_city' => $sehir,
    'billing_country' => 'Turkey',
    'billing_postcode' => $ilce,
]);
$shopier->setOrderShipping([
    'shipping_address' => $adres,
    'shipping_city' => $sehir,
    'shipping_country' => 'Turkey',
    'shipping_postcode' => $ilce,
]);
   
die($shopier->run(rand(0, 100), $balance, $site."?sip=1"));

ob_end_flush();
?>