<?php

    include'connection.php';
    
    date_default_timezone_set("asia/Kolkata");
	$datetime= Date("Y-m-d - h:i:s A");
	$time= Date("h:i:s A");
	$date= Date("Y-m-d");
    
    $id=$_GET['urid'];
    $status=$_GET['status'];
    $orderid=$_GET['orderid'];
    $txid=$_GET['txid'];
    
    $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);
	
    	$query8="select * from wallet where Userid='$userid' order by Id desc";
		$result8=mysqli_query($con,$query8);
		$data8=mysqli_fetch_array($result8);
		$currentbal= $data8['Balance'];
		
		$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'];
	    
	    if($ApiActive==1)
	    {
	        $ch = curl_init();
	        
    		curl_setopt($ch, CURLOPT_URL, "$CallBackUrl?partnertid=$Partnerid&status=$status&orderid=$id&opid=$txid&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);
	    }
	
	        $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);
	echo "Your Recharge Request Pending Now !";
	
	}
	elseif($status=="SUCCESS")
	{
	    $GetLapuOldBal="select * from recharge where LapuNo='Rech_Api' and status='SUCCESS' order by Id desc";
    	$reGetLapuOldBal=mysqli_query($con,$GetLapuOldBal);
	    $dataGetLapuOldBal=mysqli_fetch_array($reGetLapuOldBal);
    	$LapuOldBal=$dataGetLapuOldBal['ApiBal'];
    	$remaiBal=$LapuOldBal-$amount;
		$sucessquery="update recharge set Status='$status', Transactionid='$orderid', Operatorid='$txid', AdminOpId='S', API='Rech_API' where Id='$id'";
		if(mysqli_query($con,$sucessquery))
		{
		    	$url="http://api.rechapi.com/bal.php?format=xml&token=4x9tiI9Zz7Sxmi3G8qvhpczsijBLBt";
	        	$request_timeout = 60; // 60 seconds timeout
	        	$ch = curl_init();
        		curl_setopt($ch, CURLOPT_URL, $url);
	        	curl_setopt($ch, CURLOPT_TIMEOUT, $request_timeout);
	        	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $request_timeout);
	        	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		        $output = curl_exec($ch);
	        	$curl_error = curl_errno($ch);
        		$getserver= curl_getinfo($ch);
        		curl_close($ch);
	        	if($getserver["http_code"]==200)
	        	{
		
	        		$xml = simplexml_load_string($output);
			         $rechApiBal=$xml->bal;
			         
    	            $LapuDiff=$rechApiBal-$remaiBal;
			         $UpdateRechApibal="update recharge set ApiBal='$rechApiBal', LapuNo='Rech_Api', Diff='$LapuDiff' where Id='$id'";
			         mysqli_query($con,$UpdateRechApibal);
	        	}
		}
	}
	else
	{   
	    $quGetAutoFailedStatus="select * from Auto_Failed where Id='1'";
		$reGetAutoFailedStatus=mysqli_query($con,$quGetAutoFailedStatus);
		$dataGetAutoFailedStatus=mysqli_fetch_array($reGetAutoFailedStatus);
		$AutoFailedStatus=$dataGetAutoFailedStatus['Status'];
		
	    if($CheckStatus=="FAILED")
	    {
			if($resText=="Invalid Amount")
			{
				$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='My_API2' 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>=234084";
                	$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);
				    
		    	}
			}
			elseif($AutoFailedStatus=="Deactive" || $txid=="Insufficient Balance.")
			{
				$UpdateRechApibal="update recharge set ReHit='1', AdminOpId='$txid' where Id='$id'";
				mysqli_query($con,$UpdateRechApibal);
			}
			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='My_API2' 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>=234084";
                	$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);
				    
		    	}
			}
	    }
	}
?>