<?php
	include'connection.php';
	
	$userid = $_GET['userid'];
	$token = $_GET['token'];
	$partnerid = $_GET['partnerid'];
	$OwnApiOpCode = $_GET['opcode'];
	$mnum = $_GET['mobile'];
	$amount = $_GET['amount'];
		
		$quAdminBal="select * from wallet where Userid='1111' order by Id desc";
		$reAdminBal=mysqli_query($con,$quAdminBal);
		$dataAdminBal=mysqli_fetch_array($reAdminBal);
		$currentAdminbal= $dataAdminBal['Balance'];
		
		$TotalIdeaBal=0;
		$TotalJioBal=0;
		$TotalVodaBal=0;
		$TotalAirtelBal=0;
		
		$quMyAPI="select * from myapi where Operator='Idea'";
		$reMyAPI=mysqli_query($con,$quMyAPI);
		while($dataMyAPI=mysqli_fetch_array($reMyAPI))
		{
		    $LapuIdeaBal=$dataMyAPI['LapuBal'];
		    $TotalIdeaBal=$TotalIdeaBal+$LapuIdeaBal;
		}
		
		$quMyApiJio="select * from myapi where Operator='JIO'";
		$reMyApiJio=mysqli_query($con,$quMyApiJio);
		while($dataMyApiJio=mysqli_fetch_array($reMyApiJio))
		{
		    $LapuJioBal=$dataMyApiJio['LapuBal'];
		    $TotalJioBal=$TotalJioBal+$LapuJioBal;
		}
		
		$quMyApiVoda1="select * from myapi where Operator='Voda'";
		$reMyApiVoda1=mysqli_query($con,$quMyApiVoda1);
		while($dataMyApiVoda1=mysqli_fetch_array($reMyApiVoda1))
		{
		    $LapuVoda1Bal=$dataMyApiVoda1['LapuBal'];
		    $TotalVodaBal=$TotalVodaBal+$LapuVoda1Bal;
		}
		
		$quMyApiAirtel="select * from myapi where Operator='Airtel'";
		$reMyApiAirtel=mysqli_query($con,$quMyApiAirtel);
		while($dataMyApiAirtel=mysqli_fetch_array($reMyApiAirtel))
		{
		    $LapuAirtelBal=$dataMyApiAirtel['LapuBal'];
		    $TotalAirtelBal=$TotalAirtelBal+$LapuAirtelBal;
		}
		
    	$ActualIdeaBal=$TotalIdeaBal*96.34/100;
	    $ActualJioBal=$TotalJioBal*92.96/100;
	    $ActualVodaBal=$TotalVodaBal*96.34/100;
	    $ActualAirtelBal=$TotalAirtelBal*96.63/100;
		
		$quUniqueAPI="select * from myapi where LapuName='Unique_API'";
		$reUniqueAPI=mysqli_query($con,$quUniqueAPI);
		$dataUniqueAPI=mysqli_fetch_array($reUniqueAPI);
		$UniqueAPIBal=$dataUniqueAPI['LapuBal'];
		
		$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;
		}
		
        $curl = curl_init();
    //KWIK_API BALANCE CODE//
         $curl = curl_init();

        curl_setopt_array($curl, array(
          CURLOPT_URL => "https://www.kwikapi.com/api/v2/balance.php?api_key=8tyeubd-prieyeiw-854125-75yhr-8454adz",
          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",
            ));

            $response = curl_exec($curl);
            $err = curl_error($curl);

            curl_close($curl);

            if ($err) {
                  echo "cURL Error #:" . $err;
            }
            else
            {
                $data2=json_decode($response);
											
			    $KwikApiBal = $data2->response->balance;;
            }
            
		$queryMd="select * from masterdis";
		$resultMd=mysqli_query($con,$queryMd);
		$rowMd=mysqli_num_rows($resultMd);
		$sumMdBal=0;
		while($mdData=mysqli_fetch_array($resultMd))
		{
			$totalMdBal=$mdData['Balance'];
			$sumMdBal=$sumMdBal+$totalMdBal;
		}
		
		$querydis="select * from distributer";
		$resultdis=mysqli_query($con,$querydis);
		$rowdis=mysqli_num_rows($resultdis);
		$sumDisBal=0;
		while($disData=mysqli_fetch_array($resultdis))
		{
			$totalDisBal=$disData['Balance'];
	    	$sumDisBal=$sumDisBal+$totalDisBal;
		}
		
		$query1="select * from retailer";
		$result1=mysqli_query($con,$query1);
		$row1=mysqli_num_rows($result1);
		$sumRet=0;
		while($row11=mysqli_fetch_array($result1))
		{
			$retalrBal=$row11['Balance'];
			$sumRet=$sumRet+$retalrBal;
		}
		
		$query4="select * from commwallet where Active='0'";
		$result4=mysqli_query($con,$query4);
		$sum4=0;
		while($row4=mysqli_fetch_array($result4))
		{
			$data4=$row4['Balance'];
			$sum4=$sum4+$data4;
		}
		$totalWalletBal=$currentAdminbal+$sumMdBal+$sumDisBal+$sumRet+$sum4;
	    
	    $TotalApiBal=$ActualIdeaBal+$ActualJioBal+$ActualVodaBal+$ActualAirtelBal+$rechApiBal+$KwikApiBal+$UniqueAPIBal;
    	$Managebal=$totalWalletBal-$TotalApiBal;
        $BenefitBal=1000000-$Managebal;
	
	$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'];
	$ApiToken=$databal['ApiToken'];
	$IpAddr=$databal['IpAddr'];
	
	if($token==$ApiToken)
	{
	    
	}
	else
	{
	    $myresponse = array("status"=>"FAILED", "errmsg"=>"Invalid API Token !");
		echo $myresult = json_encode($myresponse);
		exit();
	}
	$IP =$_SERVER['REMOTE_ADDR'];
	if(!empty($IpAddr))
	{
	    if($IpAddr!==$IP)
	    {
	        $myresponse = array("status"=>"FAILED", "errmsg"=>"Invalid IP Address !");
	    	echo $myresult = json_encode($myresponse);
		    exit();
	    }
	}
	
	$QuGetUser = "select * from retailer where Userid='$userid' and ApiToken='$token'";
	$ReGetUser = mysqli_query($con,$QuGetUser);
	$GetUser = mysqli_num_rows($ReGetUser);
	
	if($GetUser!==1)
	{    
		$myresponse = array("status"=>"FAILED", "errmsg"=>"Invalid Userid Or API Token !");
		echo $myresult = json_encode($myresponse);
	}
	else
	{ //1 
	    
		if($GetUser==1)
		{ //2	
			$query2="select * from distributer where Userid='$parentid'";
			$result2=mysqli_query($con,$query2);
			$datad=mysqli_fetch_array($result2);
			$username=$datad['Name'];
			$grandparentid=$datad['Parentid'];
			$ReferId=$datad['ReferId'];
			
			$quGetAutoFailedStatus="select * from Auto_Failed where Id='1'";
			$reGetAutoFailedStatus=mysqli_query($con,$quGetAutoFailedStatus);
			$dataGetAutoFailedStatus=mysqli_fetch_array($reGetAutoFailedStatus);
			$AutoFailedStatus=$dataGetAutoFailedStatus['Status'];
			
			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");
			
			$date1 = date("Y-m-d h:i:s A");
			$time1 = strtotime($date1);
			$time2 = $time1 - (30 * 60);
			$date2 = date("h:i:s A", $time2);
			
			$postpaidOperator=substr($operator, -8);
				
			$opcodequery="select * from operator where OwnApiCode='$OwnApiOpCode'";
			$opcoderesult=mysqli_query($con,$opcodequery);
			$opcodedata=mysqli_fetch_array($opcoderesult);
			$opcode=$opcodedata['Value'];
			$myApiOpCode=$opcodedata['MyApiValue'];
			$MyApi2OpCode=$opcodedata['My_API2'];
			$KwikApiOpCode=$opcodedata['KwikAPI'];
			$UniqueApiOpCode=$opcodedata['UniqueAPI'];
			$columName=$opcodedata['Commision_Column'];
			$operator = $opcodedata['Operator'];
			$ActiveOp = $opcodedata['Active'];
				
				
			$querygetcom="select * from commision where Userid='$userid'";
			$rsultgetcom=mysqli_query($con,$querygetcom);
			$data=mysqli_fetch_array($rsultgetcom);
			$usercommvalue=$data[$columName];
				
			$parentq="select * from commision where Userid='$parentid'";
			$parentcomm=mysqli_query($con,$parentq);
			$dataparcomm=mysqli_fetch_array($parentcomm);
			$parcommvalue=$dataparcomm[$columName];
			$parbalcomm= $parcommvalue-$usercommvalue;
				
			$gparentq="select * from commision where Userid='$grandparentid'";
			$gparentcomm=mysqli_query($con,$gparentq);
			$gdataparcomm=mysqli_fetch_array($gparentcomm);
			$gparcommvalue=$gdataparcomm[$columName];
			$gparbalcomm= $gparcommvalue-$parcommvalue;
			
			$quGetUsrOp="select * from OperatorActive where Userid='$userid'";
			$reGetUsrOp=mysqli_query($con,$quGetUsrOp);
			$dataGetUsrOp=mysqli_fetch_array($reGetUsrOp);
			$UsrOp=$dataGetUsrOp[$columName];
			
			if($ActiveOp==1)
			{
				 $myresponse = array("status"=>"FAILED","errmsg"=>"Inactive Operator !", "partnertid"=>$partnerId);
				 echo $myresult = json_encode($myresponse);
			}
			elseif($UsrOp=="OFF")
			{
				 $myresponse = array("status"=>"FAILED","errmsg"=>"Operator Down !", "partnertid"=>$partnerId);
				 echo $myresult = json_encode($myresponse);
			}
			elseif($usercommvalue>$parcommvalue || $parcommvalue>$gparcommvalue)
			{
				 $myresponse = array("status"=>"FAILED","errmsg"=>"Invalid Commission Value !", "partnertid"=>$partnerId);
				 echo $myresult = json_encode($myresponse);
			}
			elseif($amount<6)
			{
				 $myresponse = array("status"=>"FAILED","errmsg"=>"Amount Is Less Than 6 !", "partnertid"=>$partnerId);
				 echo $myresult = json_encode($myresponse);
			}
			else
			{ //3
				if(empty($operator))
				{
					 $myresponse = array("status"=>"FAILED","errmsg"=>"Operator Not Found !", "partnertid"=>$partnerId);
					 echo $myresult = json_encode($myresponse);
				}
				elseif(empty($mnum))
				{
					 $myresponse = array("status"=>"FAILED","errmsg"=>"Mobile Number Not Found !", "partnertid"=>$partnerId);
					 echo $myresult = json_encode($myresponse);
				}
				elseif(empty($amount))
				{
					 $myresponse = array("status"=>"FAILED","errmsg"=>"Amount Not Found !", "partnertid"=>$partnerId);
					 echo $myresult = json_encode($myresponse);
				}
				else
				{ //4
				   
						$numLength = strlen($mnum);
						$startNum = substr($mnum,0,1);
						
						if($service=="Mobile" || $service=="Postpaid")
						{
							if($numLength!==10)
							{
								$passNum  = 0;
								$msgPass  = "MOBILE NUMBER MUST BE 10 DIGIT ONLY !";
							}
							else
							{
								$passNum  = 1;
							}
						}
						elseif($operator=="TATA SKY DTH")
						{
							if($numLength==10)
							{
								$passNum  = 1;
							}
							else
							{
								$passNum  = 0;
								$msgPass  = "TATA SKY DTH NUMBER MUST BE 10 DIGIT ONLY !";
							}
						}
						elseif($operator=="DISH TV DTH")
						{
							if($numLength==11 && $startNum==0)
							{
								$passNum  = 1;
							}
							else
							{
								$passNum  = 0;
								$msgPass  = "DISH TV DTH NUMBER MUST BE 11 DIGIT AND START FROM 0 ONLY !";
							}
						}
						elseif($operator=="AIRTEL DTH")
						{
							if($numLength==10 && $startNum==3)
							{
								$passNum  = 1;
							}
							else
							{
								$passNum  = 0;
								$msgPass  = "AIRTEL DTH	NUMBER MUST BE 10 DIGIT AND START FROM 3 ONLY !";
							}
						}
						else
						{
							$passNum  = 1;
						}
						
						
						if($passNum!==1)
						{
							 $myresponse = array("status"=>"FAILED","errmsg"=>$msgPass, "partnertid"=>$partnerId);
					         echo $myresult = json_encode($myresponse);
						}
						else
						{ //5
							if($amount>=$currentbal)
							{
								$myresponse = array("status"=>"FAILED","errmsg"=>"Insufficiant Your Wallet Balance !", "partnertid"=>$partnerId);
								echo $myresult = json_encode($myresponse);
							}
							else
							{ //6
							    
								$quGetSameRech="select * from recharge where Companyname='$operator' and Mobile='$mnum' and Amount='$amount' and Status='PENDING' and Rechargedate='$date'";
								$reGetsameRech=mysqli_query($con,$quGetSameRech);
								$dataGetSameRech=mysqli_num_rows($reGetsameRech);
								
								$quGetSameRech1="select * from recharge where Companyname='$operator' and Mobile='$mnum' and Amount='$amount' and Status='SUCCESS' and Rechargedate='$date'";
								$reGetsameRech1=mysqli_query($con,$quGetSameRech1);
								$dataGetSameRech1=mysqli_num_rows($reGetsameRech1);
								
								$quGetSameRech2="select * from recharge where Companyname='$operator' and Mobile='$mnum' and Amount='$amount' and Status='' and Rechargedate='$date'";
								$reGetsameRech2=mysqli_query($con,$quGetSameRech2);
								$dataGetSameRech2=mysqli_num_rows($reGetsameRech2);
								
								if($dataGetSameRech>=1 || $dataGetSameRech1>=1 || $dataGetSameRech2>=1)
								{
									$myresponse = array("status"=>"FAILED","errmsg"=>"Same Recharge Not Allowed At Same Day !", "partnertid"=>$partnerId);
								    echo $myresult = json_encode($myresponse);
								}
								else
								{ //7
								    
									$commision=$amount*$usercommvalue/100;
									$actual=$amount-$commision;
									
									$insertq="insert into recharge(Partnerid,Userid,Parentid,Grandparentid,ReferalId,Rechargedate,Time,Agentname,Companyname,Mobile,Amount,Debitamount,Status,AdminDiffValue)
									values('$partnerid','$userid','$parentid','$grandparentid','$ReferId','$date','$time','$username','$operator','$mnum','$amount','$actual','PENDING','$BenefitBal')";
									
									if(mysqli_query($con,$insertq))
									{ //8  
										$newrechid=mysqli_insert_id($con);
    	
                                    	$insrtDiff="insert into Diff(Rechid,Date,Time,AdminBal,MdBal,DisBal,RetBal,CommBal,AirtelBal,IdeaBal,VodaBal,JioBal,UniqBal,KwikBal,RechBal,Diff)
    	                                values('$newrechid','$date','$time','$currentAdminbal','$sumMdBal','$sumDisBal','$sumRet','$sum4','$ActualAirtelBal','$ActualIdeaBal','$ActualVodaBal','$ActualJioBal','$UniqueAPIBal','$KwikApiBal','$rechApiBal','$BenefitBal')";
    	                                mysqli_query($con,$insrtDiff);
    	                                
										$result4 = $pdoCon->query("SELECT Balance FROM `wallet` WHERE Userid='$userid' order by Id desc");
                                        $data4 = $result4->fetch();
                                        $oldbalance = $data4['Balance'];
										
										$newbal=$oldbalance-$actual;
											
										$query5="insert into wallet(Userid,Openingbalance,Debit,Remarks,Balance,Date,Time,Transactiontype,Paynrechid,Operator,Mobile,Amount)
										values('$userid','$oldbalance','$actual','Recharge','$newbal','$date','$time','Recharge','$newrechid','$operator','$mnum','$amount')";
											
										if(mysqli_query($con,$query5))
										{ //9
											$ewalletid=mysqli_insert_id($con);
											
											$query7="update recharge set Balance='$newbal',Ewalletid='$ewalletid' where Id='$newrechid'";
											mysqli_query($con,$query7);
											
											$parcommbal=$amount*$parbalcomm/100;
											$gparcommbal=$amount*$gparbalcomm/100;
											
											$insertparcomm="insert into commwallet(Userid,Balance,Date,Time,Rechargeid,Mobile,Amount,Operator,Retailer,Retailername)
											values('$parentid','$parcommbal','$date','$time','$newrechid','$mnum','$amount','$operator','$userid','$username')";
											mysqli_query($con,$insertparcomm);
												
											$insertgparcomm="insert into commwallet(Userid,Balance,Date,Time,Rechargeid,Mobile,Amount,Operator,Retailer,Retailername)
											values('$grandparentid','$gparcommbal','$date','$time','$newrechid','$mnum','$amount','$operator','$userid','$username')";
											mysqli_query($con,$insertgparcomm);
												
												
											$query10="update retailer set Lastrechdate='$date', Balance='$newbal' where Userid='$userid'";
											mysqli_query($con,$query10);
												
											$query8="select * from wallet where Userid='$userid' order by Id desc";
											$result8=mysqli_query($con,$query8);
											$data8=mysqli_fetch_array($result8);
											$currentbal= $data8['Balance'];
												
											$quGetUseApi="select * from operator where Operator='$operator'";
											$reGetUseApi=mysqli_query($con,$quGetUseApi);
											$dataGetUseApi=mysqli_fetch_array($reGetUseApi);
											$UseApi=$dataGetUseApi['UseAPI'];
												
											if($UseApi=="My_API" && $operator=="Airtel" && $amount=="35" || $UseApi=="My_API" && $operator=="Airtel" && $amount=="65")
											{
												$quGetTopupapi="select * from topupapi where Id='1'";
												$reGetTopupApu=mysqli_query($con,$quGetTopupapi);
												$dataGetTopupApi=mysqli_fetch_array($reGetTopupApu);
												$TopupApi=$dataGetTopupApi['TopupApi'];
												$UseApi2=$TopupApi;
											}
											else
											{
												$UseApi2=$UseApi;
											}
												
											if($UseApi2=="My_API")
											{ 
												$UpdateRechApibal="update recharge set API='My_API1' where Id='$newrechid'";
												mysqli_query($con,$UpdateRechApibal);
													
												$token="01dc7e7d-ec4d-42db-99b4-cdf62a80a72a";
												$url="https://www.vastwebindia.com/API/API/Recharge?Mobile=$mnum&OptCode=$myApiOpCode&Amount=$amount&Token=$token&Userid=sameermansuri111@gmail.com&rch_id=$newrechid";
														
												$curl = curl_init();
			
												curl_setopt_array($curl, array(
												CURLOPT_URL => "https://www.vastwebindia.com/API/API/Recharge?Mobile=$mnum&OptCode=$myApiOpCode&Amount=$amount&Token=$token&Userid=sameermansuri111@gmail.com&rch_id=$newrechid",
												CURLOPT_RETURNTRANSFER => true,
												CURLOPT_ENCODING => "",
												CURLOPT_MAXREDIRS => 10,
												CURLOPT_TIMEOUT => 30,
												CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
												CURLOPT_CUSTOMREQUEST => "GET",
												CURLOPT_POSTFIELDS => "",
												CURLOPT_HTTPHEADER => array(
												"Postman-Token: 7d11312d-5948-4352-be19-b636152e59fd",
												"cache-control: no-cache"	),));
			
												$response = curl_exec($curl);
												$err = curl_error($curl);
			
												curl_close($curl);
			
												if ($err)
												{
													echo "cURL Error #:" . $err;
													$UpdateRechApibal="update recharge set ReHit='1', AdminOpId='cURL Error', API='My_API1' where Id='$newrechid'";
													mysqli_query($con,$UpdateRechApibal);
												}
												else
												{
													$response;
																	
													$data2=json_decode($response);
													$queryUpadateOrderId="update recharge set API='My_API1' where Id='$newrechid'";
													mysqli_query($con,$queryUpadateOrderId);
													
													$myresponse = array("status"=>"PENDING", "partnertid"=>$partnerId, "orderid"=>$newrechid);
													echo $myresult = json_encode($myresponse);
												}
													
											}
											elseif($UseApi2=="My_API2")
											{   
												$UpdateRechApibal="update recharge set API='My_API2' where Id='$newrechid'";
												mysqli_query($con,$UpdateRechApibal);
														
												$ch = curl_init();
	
												if(!$ch)
												{
													die("Couldn't initialize a cURL handle");
													$UpdateRechApibal="update recharge set ReHit='1', AdminOpId='cURL Error', API='My_API2' where Id='$newrechid'";
													mysqli_query($con,$UpdateRechApibal);
												}
												curl_setopt($ch, CURLOPT_URL,'https://mrobotics.in/api/recharge?'); // Target URL
												curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
												curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
												curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
												curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
	
												curl_setopt($ch, CURLOPT_POST, 1);
												curl_setopt($ch, CURLOPT_POSTFIELDS,"api_token=37a1e7bd-3d24-4d73-8c17-ecd76d5a847e&mobile_no=$mnum&amount=$amount&company_id=$MyApi2OpCode&order_id=$newrechid&is_stv=false");
	
												$result = curl_exec ($ch); 
	
												$result = (array)json_decode($result);
												
												$status1 = $result['status'];
												$errorMsg = $result['errorMessage'];   
												$msg = $result['response'];   
												$txnId = $result['tnx_id'];   
												$LapuNo = $result['lapu_no'];   
												$LapuBal = $result['balance'];   
												
												$updateLapu="update recharge set LapuNo='$LapuNo', ApiBal='$LapuBal' where Id='$newrechid'";
												mysqli_query($con,$updateLapu);
												
												if($status1=="SUCCESS" || $status1=="success")
												{
													$GetLapuOldBal="select * from recharge where LapuNo='$LapuNo' and status='SUCCESS' order by Id desc";
													$reGetLapuOldBal=mysqli_query($con,$GetLapuOldBal);
													$dataGetLapuOldBal=mysqli_fetch_array($reGetLapuOldBal);
													$LapuOldBal=$dataGetLapuOldBal['ApiBal'];
													$remaiBal=$LapuOldBal-$amount;
													$LapuDiff = $LapuBal-$remaiBal;
													
													$queryUpadateOrderId="update recharge set Transactionid='$orderId', Status='SUCCESS', Operatorid='$txnId', LapuOldBal='$LapuOldBal', Diff='$LapuDiff', API='My_API2', LapuNo='$LapuNo', ApiBal='$LapuBal' where Id='$newrechid'";
													mysqli_query($con,$queryUpadateOrderId);
																
													$quUpdatebal="update myapi set LapuBal='$LapuBal' where LapuNumber='$LapuNo'";
													mysqli_query($con,$quUpdatebal);
													
													$myresponse = array("status"=>"SUCCESS", "partnertid"=>"$partnerId", "orderid"=>"$newrechid", "opid"=>"$txnId");
													echo $myresult = json_encode($myresponse);
													
												}
												elseif($status1=="FAILED" || $status1=="failure")
												{
													if($msg=="No records found" || $msg=="IN Bad MSISDN" || $msg=="Subscriber Not Found")
													{
														$Printmsg ="Invalid Number Or Operator !";
													}
													elseif($msg=="Transaction Failed" || $msg=="Card gorup set ID not found." || $msg=="No Plans Found with this Amount")
													{
														$Printmsg ="Invalid Amount !";
													}
													elseif($msg=="You can only select other than prime plan for recharge." || $msg=="You are not a Prepaid Subscriber")
													{
														$Printmsg=$msg;
													}
													else
													{
														$Printmsg ="Failed";
													}
													
													if($msg=="You are not a Prepaid Subscriber" || $msg=="No records found" || $msg=="You can only select other than prime plan for recharge." || $msg=="No Plans Found with this Amount" || $msg=="IN Bad MSISDN" || $msg=="Transaction Failed" || $msg=="Subscriber Not Found" || $msg=="Card gorup set ID not found.")
													{
														$refundresult = $pdoCon->query("SELECT Balance FROM `wallet` WHERE Userid='$userid' order by Id desc");
                                                        $refunddata = $refundresult->fetch();
                                                        $refundoldbal = $refunddata['Balance'];
														
														$refundnewbal=$refundoldbal+$actual;
																
														$refundaddbalquery="insert into wallet(Userid,Openingbalance,Credit,Remarks,Balance,Date,Time,Transactiontype,Paynrechid,Operator,Mobile,Amount,Status)
														values('$userid','$refundoldbal','$actual','Recharge_Refund','$refundnewbal','$date','$time','Recharge_Refund','$newrechid','$operator','$mnum','$amount','$status')";
														if(mysqli_query($con,$refundaddbalquery))
														{
															$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);
															
															$query9="update retailer set Balance='$refundnewbal' where Userid='$userid'";
															mysqli_query($con,$query9);
															
															$myresponse = array("status"=>"FAILED","errmsg"=>$Printmsg, "partnertid"=>$partnerId, "orderid"=>$newrechid, "opid"=>$Printmsg);
													        echo $myresult = json_encode($myresponse);
														}
																
													}
													elseif($AutoFailedStatus=="Deactive")
													{
														$UpdateRechApibal="update recharge set ReHit='1', AdminOpId='$msg', API='My_API2' where Id='$newrechid'";
														mysqli_query($con,$UpdateRechApibal);
													}
													else
													{
														//$refundquery="select * from wallet where Userid='$userid' order by Id desc";
														//$refundresult=mysqli_query($con,$refundquery);
														//$refunddata=mysqli_fetch_array($refundresult);
														//$refundoldbal=$refunddata['Balance'];
														
														$refundresult = $pdoCon->query("SELECT Balance FROM `wallet` WHERE Userid='$userid' order by Id desc");
                                                        $refunddata = $refundresult->fetch();
                                                        $refundoldbal = $refunddata['Balance'];
                                                        
														$refundnewbal=$refundoldbal+$actual;
																
														$refundaddbalquery="insert into wallet(Userid,Openingbalance,Credit,Remarks,Balance,Date,Time,Transactiontype,Paynrechid,Operator,Mobile,Amount,Status)
														values('$userid','$refundoldbal','$actual','Recharge_Refund','$refundnewbal','$date','$time','Recharge_Refund','$newrechid','$operator','$mnum','$amount','$status')";
														if(mysqli_query($con,$refundaddbalquery))
														{
															$refundewalletid=mysqli_insert_id($con);
															
															$failedquery="update recharge set Creditewalletid='$refundewalletid', Status='FAILED', Transactionid='$orderId', Operatorid='$errorMsg, $msg', Responsetxt='$resText', API='My_API2' where Id='$newrechid'";
															mysqli_query($con,$failedquery);
															
															$deletecomm="delete from commwallet where Rechargeid='$newrechid'";
															mysqli_query($con,$deletecomm);
																
															$query9="update retailer set Balance='$refundnewbal' where Userid='$userid'";
															mysqli_query($con,$query9);
																
															$myresponse = array("status"=>"FAILED","errmsg"=>$errorMsg, "partnertid"=>$partnerId, "orderid"=>$newrechid, "opid"=>$msg);
													        echo $myresult = json_encode($myresponse);
														}
													}
													
												}
											}
											elseif($UseApi2=="Kwik_API")
											{
												$UpdateRechApibal="update recharge set API='Kwik_API' where Id='$newrechid'";
												mysqli_query($con,$UpdateRechApibal);
													
												$apikey="8tyeubd-prieyeiw-854125-75yhr-8454adz";
												if($postpaidOperator=="Postpaid")
												{
													$url="https://www.kwikapi.com/api/v2/bills/recharge.php?api_key=$apikey&number=$mnum&amount=$amount&opid=$KwikApiOpCode&state_code=0&order_id=$newrechid";
															
													$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",
													));
			
													$response = curl_exec($curl);
													$err = curl_error($curl);
			
													curl_close($curl);
			
													if ($err)
													{
														echo "cURL Error #:" . $err;
														$errData=json_decode($err);
														$status1 = $errData->status;
														$resText = $errData->message;
														if($status1=="FAILED")
														{	
															$UpdateRechApibal="update recharge set ReHit='1', AdminOpId='$resText', API='Kwik_API' where Id='$newrechid'";
															mysqli_query($con,$UpdateRechApibal);
															$myresponse = array("status"=>"FAILED","errmsg"=>"$resText", "partnertid"=>$partnerId, "orderid"=>$newrechid, "opid"=>$resText);
													        echo $myresult = json_encode($myresponse);
														}
													}
													else
													{
														$data2=json_decode($response);
													
														$status1 = $data2->status;
														$resText = $data2->message;
														$txnId = $data2->opr_id;
														$kwikApiBal = $data2->balance;
													
														if($status1=="PENDING")
														{
															$queryUpadateOrderId="update recharge set Transactionid='$orderId', Status='$status1', Operatorid='$txnId', API='Kwik_API', ApiBal='$kwikApiBal' where Id='$newrechid'";
															mysqli_query($con,$queryUpadateOrderId);
															$myresponse = array("status"=>"PENDING", "partnertid"=>"$partnerId", "orderid"=>"$newrechid");
													        echo $myresult = json_encode($myresponse);
														}
														elseif($status1=="SUCCESS")
														{
															$queryUpadateOrderId="update recharge set Transactionid='$orderId', Status='$status1', Operatorid='$txnId', API='Kwik_API', ApiBal='$kwikApiBal' where Id='$newrechid'";
															mysqli_query($con,$queryUpadateOrderId);
															$myresponse = array("status"=>"SUCCESS", "partnertid"=>"$partnerId", "orderid"=>"$newrechid", "opid"=>"$txnId");
													        echo $myresult = json_encode($myresponse);
														}
														elseif($postpaidOperator=="Postpaid")
														{
					
														}
														elseif($AutoFailedStatus=="Deactive")
														{
															$UpdateRechApibal="update recharge set ReHit='1', AdminOpId='$resText', API='Kwik_API' where Id='$newrechid'";
															mysqli_query($con,$UpdateRechApibal);
														}
														elseif($status1=="FAILED")
														{
															$refundquery="select * from wallet where Userid='$userid' order by Id desc";
															$refundresult=mysqli_query($con,$refundquery);
															$refunddata=mysqli_fetch_array($refundresult);
															$refundoldbal=$refunddata['Balance'];
															$refundnewbal=$refundoldbal+$actual;
															
															$refundaddbalquery="insert into wallet(Userid,Openingbalance,Credit,Remarks,Balance,Date,Time,Transactiontype,Paynrechid,Operator,Mobile,Amount,Status)
															values('$userid','$refundoldbal','$actual','Recharge_Refund','$refundnewbal','$date','$time','Recharge_Refund','$newrechid','$operator','$mnum','$amount','$status')";
															if(mysqli_query($con,$refundaddbalquery))
															{
																$refundewalletid=mysqli_insert_id($con);
																
																$failedquery="update recharge set Creditewalletid='$refundewalletid', Status='$status1', Transactionid='$orderId', Operatorid='$resText', Responsetxt='$resText', API='Kwik_API' where Id='$newrechid'";
																mysqli_query($con,$failedquery);
																
																$deletecomm="delete from commwallet where Rechargeid='$newrechid'";
																mysqli_query($con,$deletecomm);
															
																$query9="update retailer set Balance='$refundnewbal' where Userid='$userid'";
																mysqli_query($con,$query9);
															
																$myresponse = array("status"=>"FAILED","errmsg"=>$resText, "partnertid"=>$partnerId, "orderid"=>$newrechid, "opid"=>$txnId);
													            echo $myresult = json_encode($myresponse);
															}
														}
													}
												}
												else
												{
													$url="https://www.kwikapi.com/api/v2/recharge.php?api_key=$apikey&number=$mnum&amount=$amount&opid=$KwikApiOpCode&state_code=0&order_id=$newrechid";
														
													$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",
													));
			
													$response = curl_exec($curl);
													$err = curl_error($curl);
			
													curl_close($curl);
			
													if ($err)
													{
														echo "cURL Error #:" . $err;
													}
													else
													{
														$data2=json_decode($response);
													
														$status1 = $data2->status;
														$resText = $data2->message;
														$txnId = $data2->opr_id;
														$kwikApiBal = $data2->balance;
													
														if($status1=="PENDING")
														{
															$queryUpadateOrderId="update recharge set Transactionid='$orderId', Status='$status1', Operatorid='$txnId', API='Kwik_API' where Id='$newrechid'";
															mysqli_query($con,$queryUpadateOrderId);
															
															$myresponse = array("status"=>"PENDING", "partnertid"=>"$partnerId", "orderid"=>"$newrechid");
													        echo $myresult = json_encode($myresponse);
														}
														elseif($status1=="SUCCESS")
														{
															$GetLapuOldBal="select * from recharge where LapuNo='Kwik_Api' and status='SUCCESS' order by Id desc";
															$reGetLapuOldBal=mysqli_query($con,$GetLapuOldBal);
															$dataGetLapuOldBal=mysqli_fetch_array($reGetLapuOldBal);
															$LapuOldBal=$dataGetLapuOldBal['ApiBal'];
															$remaiBal=$LapuOldBal-$amount;
														
															$queryUpadateOrderId="update recharge set Transactionid='$orderId', Status='$status1', Operatorid='$txnId', API='Kwik_API' where Id='$newrechid'";
															mysqli_query($con,$queryUpadateOrderId);
															
															$curl = curl_init();
	
															curl_setopt_array($curl, array(
															CURLOPT_URL => "https://www.kwikapi.com/api/v2/balance.php?api_key=8tyeubd-prieyeiw-854125-75yhr-8454adz",
															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",
																		));
	
															$response = curl_exec($curl);
															$err = curl_error($curl);
	
															curl_close($curl);
	
															if($err)
															{
																echo "cURL Error #:" . $err;
															}
															else
															{
																$data2=json_decode($response);
											
																$KwikApiBal = $data2->response->balance;;
															}
															
															$LapuDiff=$KwikApiBal-$remaiBal;
															$UpdateRechApibal="update recharge set ApiBal='$KwikApiBal', LapuNo='Kwik_Api', Diff='$LapuDiff' where Id='$newrechid'";
															mysqli_query($con,$UpdateRechApibal);
															
															$myresponse = array("status"=>"SUCCESS", "partnertid"=>"$partnerId", "orderid"=>"$newrechid", "opid"=>"$txnId");
													        echo $myresult = json_encode($myresponse);
															
														}
														elseif($postpaidOperator=="Postpaid")
														{
					
														}
														elseif($AutoFailedStatus=="Deactive")
														{
															$UpdateRechApibal="update recharge set ReHit='1', AdminOpId='$resText', API='Kwik_API' where Id='$newrechid'";
															mysqli_query($con,$UpdateRechApibal);
														}
														else
														{
															$refundquery="select * from wallet where Userid='$userid' order by Id desc";
															$refundresult=mysqli_query($con,$refundquery);
															$refunddata=mysqli_fetch_array($refundresult);
															$refundoldbal=$refunddata['Balance'];
															$refundnewbal=$refundoldbal+$actual;
															
															$refundaddbalquery="insert into wallet(Userid,Openingbalance,Credit,Remarks,Balance,Date,Time,Transactiontype,Paynrechid,Operator,Mobile,Amount,Status)
															values('$userid','$refundoldbal','$actual','Recharge_Refund','$refundnewbal','$date','$time','Recharge_Refund','$newrechid','$operator','$mnum','$amount','$status')";
															if(mysqli_query($con,$refundaddbalquery))
															{
																$refundewalletid=mysqli_insert_id($con);
																
																$failedquery="update recharge set Creditewalletid='$refundewalletid', Status='$status1', Transactionid='$orderId', Operatorid='$resText', Responsetxt='$resText', API='Kwik_API' where Id='$newrechid'";
																mysqli_query($con,$failedquery);
																
																$deletecomm="delete from commwallet where Rechargeid='$newrechid'";
																mysqli_query($con,$deletecomm);
															
																$query9="update retailer set Balance='$refundnewbal' where Userid='$userid'";
																mysqli_query($con,$query9);
															
																$myresponse = array("status"=>"FAILED","errmsg"=>$resText, "partnertid"=>$partnerId, "orderid"=>$newrechid, "opid"=>$txnId);
													            echo $myresult = json_encode($myresponse);
															}
														}
													}
												}
											}
											elseif($UseApi2=="Unique_API")
											{
													
												$UpdateRechApibal="update recharge set API='Unique_API' where Id='$newrechid'";
												mysqli_query($con,$UpdateRechApibal);
													
												$apiUserId="9897095971";
												$apiPwd="123456";
												
												$curl = curl_init();
		
												curl_setopt_array($curl, array(
												CURLOPT_URL => "http://uniqueebazaar.store/index.php/RechargeWebService/apitransaction?userid=9897095971&password=123456&mobile=$mnum&opt=$UniqueApiOpCode&amount=$amount&agentid=$newrechid&fmt=json",
												CURLOPT_RETURNTRANSFER => true,
												CURLOPT_ENCODING => "",
												CURLOPT_MAXREDIRS => 10,
												CURLOPT_TIMEOUT => 30,
												CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
												CURLOPT_CUSTOMREQUEST => "POST",
												CURLOPT_POSTFIELDS => "",
												CURLOPT_HTTPHEADER => array(
												"Postman-Token: 12172b3e-8111-46ff-a491-71ca0f581b7e",
												"cache-control: no-cache"
													),
													));
		
												$response = curl_exec($curl);
												$err = curl_error($curl);
		
												curl_close($curl);
												
												if ($err)
												{
													echo "cURL Error #:" . $err;
												}
												else
												{
													$data2=json_decode($response);
												
													$TxnId = $data2->userDATA->RBID;
													$status1 = $data2->userDATA->Status;
													$resText = $data2->userDATA->MSG;
													$opId = $data2->userDATA->OPID;
													$UniqApiBal = $data2->userDATA->BAL;
												
													if($status1=="Error")
													{
														if($AutoFailedStatus=="Deactive")
														{ 
															$UpdateRechApibal="update recharge set ReHit='1', API='Unique_API1', AdminOpId='$resText' where Id='$newrechid'";
															mysqli_query($con,$UpdateRechApibal);
														}
														else
														{
															$refundquery="select * from wallet where Userid='$userid' order by Id desc";
															$refundresult=mysqli_query($con,$refundquery);
															$refunddata=mysqli_fetch_array($refundresult);
															$refundoldbal=$refunddata['Balance'];
															$refundnewbal=$refundoldbal+$actual;
															
															$refundaddbalquery="insert into wallet(Userid,Openingbalance,Credit,Remarks,Balance,Date,Time,Transactiontype,Paynrechid,Operator,Mobile,Amount,Status)
															values('$userid','$refundoldbal','$actual','Recharge_Refund','$refundnewbal','$date','$time','Recharge_Refund','$newrechid','$operator','$mnum','$amount','FAILED')";
															if(mysqli_query($con,$refundaddbalquery))
															{
																$getrefundewalletid="select * from wallet where Userid='$userid' order by Id desc";
																$resultrefundewalletid=mysqli_query($con,$getrefundewalletid);
																$datarefundewalletid=mysqli_fetch_array($resultrefundewalletid);
																$refundewalletid=$datarefundewalletid['Id'];
																
																$failedquery="update recharge set Creditewalletid='$refundewalletid', Status='FAILED', Transactionid='$orderId', Operatorid='$txnId', Responsetxt='$resText', API='Unique_API' where Id='$newrechid'";
																mysqli_query($con,$failedquery);
																
																$deletecomm="delete from commwallet where Rechargeid='$newrechid'";
																mysqli_query($con,$deletecomm);
																
																$query9="update retailer set Balance='$refundnewbal' where Userid='$userid'";
																mysqli_query($con,$query9);
																
																$myresponse = array("status"=>"FAILED","errmsg"=>$resText, "partnertid"=>$partnerId, "orderid"=>$newrechid, "opid"=>$opId);
													            echo $myresult = json_encode($myresponse);
															}
															
														}
															
													}
													elseif($status1=="SUCCESS" || $status1=="Success")
													{
														$GetLapuOldBal="select * from recharge where LapuNo='Unique_Api' and status='SUCCESS' order by Id desc";
														$reGetLapuOldBal=mysqli_query($con,$GetLapuOldBal);
														$dataGetLapuOldBal=mysqli_fetch_array($reGetLapuOldBal);
														$LapuOldBal=$dataGetLapuOldBal['ApiBal'];
														$remaiBal=$LapuOldBal-$amount;
														if(empty($UniqApiBal) || $UniqApiBal==0)
														{
															$UniqApiBal2=$LapuOldBal-$amount;
														}
														else
														{
															$UniqApiBal2=$UniqApiBal;
														}
														
														$LapuDiff=$UniqApiBal2-$remaiBal;
														
														$quUpdatebal="update myapi set LapuBal='$UniqApiBal2' where LapuName='Unique_API'";
														mysqli_query($con,$quUpdatebal);
			
														$updateLapuNo="update recharge set LapuNo='Unique_Api', LapuOldBal='$LapuOldBal', Diff='$LapuDiff' where Id='$newrechid'";
														mysqli_query($con,$updateLapuNo);
														
														$queryUpadateOrderId="update recharge set API='Unique_API2', Operatorid='$opId', ApiBal='$UniqApiBal2', AdminOpId='S', Status='$status1' where Id='$newrechid'";
														mysqli_query($con,$queryUpadateOrderId);
														
														$myresponse = array("status"=>"SUCCESS", "partnertid"=>"$partnerId", "orderid"=>"$newrechid", "opid"=>"$opId");
													    echo $myresult = json_encode($myresponse);
													}
													elseif($status1=="FAILED" || $status1=="Failed")
													{
															if($AutoFailedStatus=="Deactive")
															{
																$UpdateRechApibal="update recharge set ReHit='1', API='Unique_API3', AdminOpId='$status1' where Id='$newrechid'";
																mysqli_query($con,$UpdateRechApibal);
															}
															else
															{
																$refundquery="select * from wallet where Userid='$userid' order by Id desc";
																$refundresult=mysqli_query($con,$refundquery);
																$refunddata=mysqli_fetch_array($refundresult);
																$refundoldbal=$refunddata['Balance'];
																$refundnewbal=$refundoldbal+$actual;
															
																$refundaddbalquery="insert into wallet(Userid,Openingbalance,Credit,Remarks,Balance,Date,Time,Transactiontype,Paynrechid,Operator,Mobile,Amount,Status)
																values('$userid','$refundoldbal','$actual','Recharge_Refund','$refundnewbal','$date','$time','Recharge_Refund','$newrechid','$operator','$mnum','$amount','FAILED')";
																if(mysqli_query($con,$refundaddbalquery))
																{
																	$refundewalletid=mysqli_insert_id($con);
																
																	$failedquery="update recharge set Creditewalletid='$refundewalletid', Status='FAILED', Transactionid='$orderId', Operatorid='$resText', Responsetxt='$resText', API='Unique_API2$status1' where Id='$newrechid'";
																	mysqli_query($con,$failedquery);
																	
																	$deletecomm="delete from commwallet where Rechargeid='$newrechid'";
																	mysqli_query($con,$deletecomm);
																
																	$query9="update retailer set Balance='$refundnewbal' where Userid='$userid'";
																	mysqli_query($con,$query9);
																
																	$myresponse = array("status"=>"FAILED","errmsg"=>$resText, "partnertid"=>$partnerId, "orderid"=>$newrechid, "opid"=>$txnId);
													                echo $myresult = json_encode($myresponse);
																}
															}
														}
													}
												}
											elseif($UseApi2=="Rech_API")
											{
												$UpdateRechApibal="update recharge set API='Rech_API' where Id='$newrechid'";
												mysqli_query($con,$UpdateRechApibal);
												
												$token="4x9tiI9Zz7Sxmi3G8qvhpczsijBLBt";
												$url="http://api.rechapi.com/recharge.php?format=xml&token=$token&mobile=$mnum&amount=$amount&opid=$opcode&urid=$newrechid";
												$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);
													$orderId=$xml->orderId;
													$status1=$xml->status;
													$mobile=$xml->mobile;
													$amount=$xml->amount;
													$operatorId=$xml->operatorId;
													$error_code=$xml->error_code;
													$service=$xml->service;
													$resText=$xml->resText;
													
													if($status1=="SUCCESS")
													{
														$queryUpadateOrderId="update recharge set Transactionid='$orderId', API='Rech_API' where Id='$newrechid'";
														mysqli_query($con,$queryUpadateOrderId);
														
														$myresponse = array("status"=>"SUCCESS", "partnertid"=>$partnerId, "orderid"=>$newrechid, "opid"=>$operatorId);
													    echo $myresult = json_encode($myresponse);
													}
													elseif($status1=="FAILED")
													{
														if($AutoFailedStatus=="Deactive")
														{
															$UpdateRechApibal="update recharge set ReHit='1', AdminOpId='$resText', API='Rech_API' where Id='$newrechid'";
															mysqli_query($con,$UpdateRechApibal);
															
															$myresponse = array("status"=>"PENDING", "partnertid"=>$partnerId, "orderid"=>$newrechid);
													        echo $myresult = json_encode($myresponse);
														}
														else
														{
															$refundquery="select * from wallet where Userid='$userid' order by Id desc";
															$refundresult=mysqli_query($con,$refundquery);
															$refunddata=mysqli_fetch_array($refundresult);
															$refundoldbal=$refunddata['Balance'];
															$refundnewbal=$refundoldbal+$actual;
															
															$refundaddbalquery="insert into wallet(Userid,Openingbalance,Credit,Remarks,Balance,Date,Time,Transactiontype,Paynrechid,Operator,Mobile,Amount,Status)
															values('$userid','$refundoldbal','$actual','Recharge_Refund','$refundnewbal','$date','$time','Recharge_Refund','$newrechid','$operator','$mnum','$amount','$status')";
															if(mysqli_query($con,$refundaddbalquery))
															{
																$refundewalletid=mysqli_insert_id($con);
																$failedquery="update recharge set Creditewalletid='$refundewalletid', Status='$status1', Transactionid='$orderId', Operatorid='$resText', Responsetxt='$resText', API='Rech_API' where Id='$newrechid'";
																mysqli_query($con,$failedquery);
																
																$deletecomm="delete from commwallet where Rechargeid='$newrechid'";
																mysqli_query($con,$deletecomm);
																
																$query9="update retailer set Balance='$refundnewbal' where Userid='$userid'";
																mysqli_query($con,$query9);
																
																$myresponse = array("status"=>"FAILED","errmsg"=>$resText, "partnertid"=>$partnerId, "orderid"=>$newrechid, "opid"=>$txnId);
													            echo $myresult = json_encode($myresponse);
															}
														}
													}
													else
													{
														$queryUpadateOrderId="update recharge set Transactionid='$orderId', API='Rech_API' where Id='$newrechid'";
														mysqli_query($con,$queryUpadateOrderId);
														
														$myresponse = array("status"=>"PENDING", "partnertid"=>$partnerId, "orderid"=>$newrechid, "opid"=>$txnId);
													    echo $myresult = json_encode($myresponse);
													}													
													
												}
												elseif($curl_error=="28")
												{
													$pendingquery="update recharge set Status='$status1', Transactionid='$orderId', Operatorid='$resText', Responsetxt='$resText' where Id='$newrechid'";
													mysqli_query($con,$pendingquery);
														
													$myresponse = array("status"=>"PENDING","errmsg"=>"Error");
												    echo $myresult = json_encode($myresponse);
												}
												
											}
											
										}//9
										
									}//8
									
								}//7
								
							} //6
							
						} //5
				}//4
				
			} //3
			
		} //2 
	} //1
	ob_end_flush();
?>	