<?php

    include'connection.php';
    include'time.php';
    include'../Retailers/functions.php';
    //Perfect Paisa API Balance //
	
    $token2="b968b63cabae4d9aa26b4c252e13be11";
	$url2="https://www.perfectpaisa.in/apiservice.asmx/GetBalance?apiToken=$token2";
	$request_timeout = 60; // 60 seconds timeout
	$ch2 = curl_init();
	curl_setopt($ch2, CURLOPT_URL, $url2);
	curl_setopt($ch2, CURLOPT_TIMEOUT, $request_timeout);
	curl_setopt($ch2, CURLOPT_CONNECTTIMEOUT, $request_timeout);
	curl_setopt($ch2, CURLOPT_RETURNTRANSFER, 1);
    $output2 = curl_exec($ch2);
	$curl_error = curl_errno($ch2);
	$getserver= curl_getinfo($ch2);
	curl_close($ch2);
    $xml2 = simplexml_load_string($output2);
	$PP_API_Bal=floor($xml2);
	
	$upatePP_Api="UPDATE myapi SET LapuBal='$PP_API_Bal' WHERE LapuNumber='PP_Api'";
	mysqli_query($con,$upatePP_Api);
	
    $id=$_GET['reqid'];
    $statu=$_GET['status'];
    $orderid=$_GET['orderid'];
    $txid=$_GET['field1'];
    $balance=$_GET['balance'];
	
	$ptinMsg="PP_Api".$id.$statu.$orderid.$txid;
	$quTest2="INSERT INTO Test(Date,Time,Testdata) VALUES ('$date','$time','$ptinMsg')";
    mysqli_query($con,$quTest2);
       
    $newrechid=$id;
    
	$quGetRechData="SELECT * FROM recharge WHERE Id='$id'";
	$reGetRechData=mysqli_query($con,$quGetRechData);
	$dataGetRech=mysqli_fetch_array($reGetRechData);
	$userid=$dataGetRech['Userid'];
	$mobile=$dataGetRech['Mobile'];
	$amount=$dataGetRech['Amount'];
	$operator=$dataGetRech['Companyname'];
	$CheckStatus=$dataGetRech['Status'];
	$Partnerid=$dataGetRech['Partnerid'];
	
	$UpdateCBS="UPDATE recharge SET CallBack='1' WHERE Id='$id'";
	mysqli_query($con,$UpdateCBS);
	
	
	mysql_query($con,"INSERT INTO cbhis (oid,uid,status_code,msg,url)VALUES('$id','$userid','Test','TestResponse','TestUrl')");
	
	if($statu=="REFUND")
	{
	    $status="FAILED";
	}
	else
	{
	    $status=$statu;
	}
		
	$query2="SELECT * FROM retailer WHERE Userid='$userid'";
	$result2=mysqli_query($con,$query2);
	$databal=mysqli_fetch_array($result2);
	$username=$databal['Name'];
	$parentid=$databal['Parentid'];
	$grandparentid=$databal['Grandparentid'];
	$CallBackUrl=$databal['CallBackUrl'];
	$ApiActive=$databal['ApiActive'];
	    
	   
	
	        $opcodequery="select * from operator where Operator='$operator'";
			$opcoderesult=mysqli_query($con,$opcodequery);
			$opcodedata=mysqli_fetch_array($opcoderesult);
			$opcode=$opcodedata['Value'];
			$columName=$opcodedata['Commision_Column'];
			
			$querygetcom="select * from commision where Userid='$userid'";
			$rsultgetcom=mysqli_query($con,$querygetcom);
			$data=mysqli_fetch_array($rsultgetcom);
			$usercommvalue=$data[$columName];
			
			$commision=$amount*$usercommvalue/100;
			$actual=$amount-$commision;
	
	if($status=="PENDING")
	{
	    $pendingquery="update recharge set Status='$status', Transactionid='$orderid' where Id='$id'";
	    mysqli_query($con,$pendingquery);
	}
	elseif($status=="SUCCESS")
	{	
		$sucessquery="update recharge set LapuNo='PP_Api', ApiBal='$PP_API_Bal',  Status='$status', Transactionid='$orderid', Operatorid='$txid', AdminOpId='S',  API='PP_Api' where Id='$id'";
		mysqli_query($con,$sucessquery);
		
		$quUpdatebal="UPDATE myapi SET LapuBal='$balance', LastUpdate='$date', OrderId='$id' WHERE LapuNumber='PP_Api'";
		mysqli_query($con,$quUpdatebal);
		
		if($ApiActive==1)
	    {
	        $url = "$CallBackUrl?partnertid=$Partnerid&status=$status&orderid=$id&opid=$txid&errmsg=$txid";
	       FILE_PUT_CONTENTS('Test.txt' , $url);
            $curl = curl_init();
            
            curl_setopt_array($curl, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_CONNECTTIMEOUT => 60,
            CURLOPT_TIMEOUT => 60,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "GET",
            CURLOPT_HTTPHEADER => array(
            "cache-control: no-cache"
                    ),
                ));

                $response = curl_exec($curl);
            $hhtpCode =curl_getinfo($curl, CURLINFO_HTTP_CODE);
            $err = curl_error($curl);

            curl_close($curl);



            if ($err) {
            //$do=mysql_query("INSERT INTO kwk_cbhis (oid,uid,status_code,msg,url)VALUES(paste your values)");
            } else {
                //$do=mysql_query("INSERT INTO kwk_cbhis (oid,uid,status_code,msg,url)VALUES(paste your values)");
            }
                $insertCBH="INSERT INTO cbhis (oid,uid,status_code,msg,url)VALUES('$id','$userid','$hhtpCode','$response','$url')";
                mysqli_query($con,$insertCBH);
	    }
	}
	else
	{   
	    $quGetAutoFailedStatus="select * from Auto_Failed where Id='1'";
		$reGetAutoFailedStatus=mysqli_query($con,$quGetAutoFailedStatus);
		$dataGetAutoFailedStatus=mysqli_fetch_array($reGetAutoFailedStatus);
		$AutoFailedStatus=$dataGetAutoFailedStatus['Status'];
		
	    if($status=="FAILED" || $status=="REFUND")
	    {
			if($txid=="Invalid Amount")
			{
				$RefundTxn=$actual;
			    $queryRefund="insert into wallet(Userid,Txn,Remarks,Date,Time,Transactiontype,Paynrechid,Operator,Mobile,Amount)
				values('$userid','$RefundTxn','Recharge_Refund','$date','$time','Recharge_Refund','$newrechid','$operator','$mnum','$amount')";
				if(mysqli_query($con,$queryRefund))
				{
			    	$refundewalletid=mysqli_insert_id($con);
															
            	    $failedquery="update recharge set Creditewalletid='$refundewalletid', Status='FAILED', Transactionid='$orderId', Operatorid='$Printmsg', Responsetxt='$resText', API='PP_Api6' where Id='$newrechid'";
			        mysqli_query($con,$failedquery);
						    									
				    $deletecomm="delete from commwallet where Rechargeid='$newrechid'";
				    mysqli_query($con,$deletecomm);
															
    				$queryNewBal="select * from wallet where Userid='$userid' and Id>=$EwalletId";
                	$resultNewBal=mysqli_query($con,$queryNewBal);
	                $newbal=0;
	                while($dataNewBal=mysqli_fetch_array($resultNewBal))
	                {
	                    $Retbal= $dataNewBal['Balance'];
    	                $newbal=$newbal+$Retbal;
                	}
		    	    $query9="update retailer set Balance='$newbal' where Userid='$userid'";
			    	mysqli_query($con,$query9);
				    
		    	}
		    	 if($ApiActive==1)
        	    {
	               $ch = curl_init();
	                $url="$CallBackUrl?partnertid=$Partnerid&status=$status&orderid=$id&opid=$txid&errmsg=$txid";
            		curl_setopt($ch, CURLOPT_URL, $url);
	               	curl_setopt($ch, CURLOPT_POST, false );
	        	    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
            		curl_setopt($ch, CURLOPT_TIMEOUT, 100);
	               	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
		
	        	    curl_close($ch);
	        	    
	        	    $insertCallBack="insert into CallBackData(RechId,Url)values('$id','$url')";
	        	    mysqli_query($con,$insertCallBack);
	              }
			}
			elseif($AutoFailedStatus=="Deactive" || $txid=="Insufficient Balance.")
			{
				$UpdateRechApibal="update recharge set ReHit='1', AdminOpId='$txid' where Id='$id'";
				mysqli_query($con,$UpdateRechApibal);
				
				$url="$CallBackUrl?partnertid=$Partnerid&status='PENDING'&orderid=$id&opid=$txid&errmsg=$txid";
				$insertCallBack="insert into CallBackData(RechId,Url)values('$id','$url')";
	        	mysqli_query($con,$insertCallBack);
			}
			else
			{
				$RefundTxn=$actual;
			    $queryRefund="insert into wallet(Userid,Openingbalance,Txn,Remarks,Date,Time,Transactiontype,Paynrechid,Operator,Mobile,Amount)
				values('$userid','','$RefundTxn','Recharge_Refund','$date','$time','Recharge_Refund','$newrechid','$operator','$mnum','$amount')";
				if(mysqli_query($con,$queryRefund))
				{
			    	$refundewalletid=mysqli_insert_id($con);
															
            	    $failedquery="update recharge set Creditewalletid='$refundewalletid', Status='FAILED', Transactionid='$orderId', Operatorid='$Printmsg', Responsetxt='$resText', API='PP_Api7' where Id='$newrechid'";
			        mysqli_query($con,$failedquery);
						    									
				    $deletecomm="delete from commwallet where Rechargeid='$newrechid'";
				    mysqli_query($con,$deletecomm);
															
    				$queryNewBal="select * from wallet where Userid='$userid' and Id>=$EwalletId";
                	$resultNewBal=mysqli_query($con,$queryNewBal);
	                $newbal=0;
	                while($dataNewBal=mysqli_fetch_array($resultNewBal))
	                {
	                    $Retbal= $dataNewBal['Balance'];
    	                $newbal=$newbal+$Retbal;
                	}
		    	    $query9="update retailer set Balance='$newbal' where Userid='$userid'";
			    	mysqli_query($con,$query9);
				    
		    	}
			}
	    }
	}
?>