<?php
    include'connection.php';
    include'time.php';
    include'../Retailers/functions.php';
    
    $id = $_GET['ClientRefNo'];
    $RespStatusCode = $_GET['Status'];
    $orderid = $_GET['TrnID'];
    $txid = $_GET['OprID'];
    
    $quTest2="INSERT INTO Test(Date,Time,Testdata) VALUES ('$date','$time','$id.$RespStatusCode.$orderid.$txid.')";
    mysqli_query($con,$quTest2);
    
    $url="https://www.kwikpayapi.com/Kwpapi/RechargeAPI.aspx?MobileNo=9897095971&APIKey=agfbEchMMunPC8xXeJ3gTbcwq9XtHJoUgKH&REQTYPE=BAL&RESPTYPE=JSON";
    $curl = curl_init();
	curl_setopt_array($curl, array(
	CURLOPT_URL => $url,
	CURLOPT_RETURNTRANSFER => true,
	CURLOPT_ENCODING => "",
	CURLOPT_MAXREDIRS => 10,
	CURLOPT_TIMEOUT => 0,
	CURLOPT_FOLLOWLOCATION => false,
	CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
	CURLOPT_CUSTOMREQUEST => "GET",
	));
	
	$err = curl_error($curl);							

    $result = curl_exec ($curl); 
    $result = (array)json_decode($result);
    curl_close($curl);
       
    $DiziKwikApiBal = $result['BALANCE'];
	
    $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'];
	$OwnApiOpCode=$dataGetRech['OpCode'];
	$DebitAmount=$dataGetRech['Debitamount'];
	$operator=$dataGetRech['Companyname'];
	$CheckStatus=$dataGetRech['Status'];
	$Partnerid=$dataGetRech['Partnerid'];
	
	
	        
	$newrechid=$id;
	$mnum=$mobile;
	$opName=$operator;
	
	$UpdateCBS="UPDATE recharge SET CallBack='1' WHERE Id='$id'";
	mysqli_query($con,$UpdateCBS);
	
	$query2="SELECT * FROM retailer WHERE Userid='$userid'";
	$result2=mysqli_query($con,$query2);
	$databal=mysqli_fetch_array($result2);
	$username=$databal['Name'];
	$CallBackUrl=$databal['CallBackUrl'];
	$ApiActive=$databal['ApiActive'];
		
    if(empty($txid))
    {
        $printMsg="Unknown Error";
    }
    else
    {
        $printMsg=$txid;
    }
    
    $quGetUsrOp="SELECT * FROM CommSlab WHERE Userid='$userid' AND OpName='$opName'";
	$reGetUsrOp=mysqli_query($con,$quGetUsrOp);
	$dataGetUsrOp=mysqli_fetch_array($reGetUsrOp);
	$UsrPersApi1=$dataGetUsrOp['API1'];
	$UsrPersApi2=$dataGetUsrOp['API2'];
			
    
		if($ApiActive==1)
		{
				$ch = curl_init();
				
				curl_setopt($ch, CURLOPT_URL, "$CallBackUrl?partnertid=$Partnerid&status=$status&orderid=$id&opid=$printMsg&errmsg=$txid");
				curl_setopt($ch, CURLOPT_POST, false );
				curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
				curl_setopt($ch, CURLOPT_TIMEOUT, 0);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
			
				curl_close($ch);
		}
				
		if($RespStatusCode==4 || $RespStatusCode==6)
		{
			$pendingquery="update recharge set Status='PENDING', Transactionid='$orderid' where Id='$id'";
			mysqli_query($con,$pendingquery);
		}
		elseif($RespStatusCode==1)
		{
			$GetLapuOldBal="select * from recharge where LapuNo='Dizi_Kwik' and status='SUCCESS' order by Id desc";
			$reGetLapuOldBal=mysqli_query($con,$GetLapuOldBal);
			$dataGetLapuOldBal=mysqli_fetch_array($reGetLapuOldBal);
			$LapuOldBal=$dataGetLapuOldBal['ApiBal'];
			$remaiBal=$LapuOldBal-$amount;
			$LapuDiff=$DiziKwikApiBal-$remaiBal;
			
			$sucessquery="update recharge set Status='SUCCESS', Transactionid='$orderid', Operatorid='$txid', ApiBal='$DiziKwikApiBal', AdminOpId='S', Diff='$LapuDiff' where Id='$id'";
			mysqli_query($con,$sucessquery);
			
			$quUpdatebal="UPDATE myapi SET LapuBal='$DiziKwikApiBal', LastUpdate='$date', OrderId='$id' WHERE LapuNumber='Dizi_Kwik'";
			mysqli_query($con,$quUpdatebal);					  
		}
		elseif($RespStatusCode=2 || $RespStatusCode=3 || $RespStatusCode=5)
		{   
			$quGetAutoFailedStatus="select * from Auto_Failed where Id='1'";
			$reGetAutoFailedStatus=mysqli_query($con,$quGetAutoFailedStatus);
			$dataGetAutoFailedStatus=mysqli_fetch_array($reGetAutoFailedStatus);
			$AutoFailedStatus=$dataGetAutoFailedStatus['Status'];
			
			if($AutoFailedStatus=="Deactive" || $txid=="Insufficient Balance.")
			{
				$UpdateRechApibal="update recharge set ReHit='1', AdminOpId='$txid' where Id='$id'";
				mysqli_query($con,$UpdateRechApibal);
			}
			else
			{
				$opBal=getBal($userid);
				$clBal=$opBal+$DebitAmount;
				
				if(10==strlen($userid))
				{
					$wallet="MLM_Wallet";
					$usrTable="MLM_Users";
				}
				else
				{
					$wallet="wallet";
					$usrTable="retailer";
				}
				$quRefund="INSERT INTO $wallet (Userid,OpBal,Txn,ClBal,TxnType,TxnWith,TxnId,Remarks,Date,Time)
				VALUES ('$userid','$opBal','$DebitAmount','$clBal','Recharge_Refund','SELF','$newrechid','Recharge_Refund','$date','$time')";
				if(mysqli_query($con,$quRefund))
				{
					$refundewalletid=mysqli_insert_id($con);
					
					$query9="UPDATE $usrTable SET Balance='$clBal' WHERE Userid='$userid'";
					mysqli_query($con,$query9);
					
					$quFailed="UPDATE recharge SET Creditewalletid='$refundewalletid', Status='FAILED', Operatorid='$Printmsg' where Id='$newrechid'";
					mysqli_query($con,$quFailed);
																	
					$deleteComm="DELETE FROM commwallet WHERE Rechargeid='$newrechid'";
					mysqli_query($con,$deleteComm);
				
				}
			}
		}
	
?>