<?php
	include'connection.php';
	
	include'time.php';
	include'../Retailers/functions.php';
	include'../Admin1/insertDiff.php';
	
	ini_set('memory_limit', '-1');
	
    $time_start = microtime(true);
    
	$userid = $_GET['userid'];
	$token = $_GET['token'];
	$partnerId = $_GET['partnerid'];
	$OwnApiOpCode = $_GET['opcode'];
	$mnum = $_GET['mobile'];
	$amount = $_GET['amount'];
    
    $Pdate = date("Y-m-d H:i:s");
    $Ptime = strtotime($Pdate);
    $Ptime = $Ptime - (1 * 60);
    $PdatePtime = date("Y-m-d H:i:s", $Ptime);
    
    $quRechBlockByAmt="SELECT * FROM RBBA WHERE OwnOpCode='$OwnApiOpCode' AND Amount='$amount'";
	$reRechBlockByAmt=mysqli_query($con,$quRechBlockByAmt);
	$RechBlockByAmt=mysqli_num_rows($reRechBlockByAmt);
	
	if($RechBlockByAmt>0)
    {
        $myresponse = array("status"=>"FAILED", "errmsg"=>"Amount Blocked For Invalid Amount !");
		echo $myresult = json_encode($myresponse);
		exit();
    }		
    
	$quPendingRech="SELECT * FROM recharge WHERE OpCode='$OwnApiOpCode' AND Userid='$userid' AND Status='PENDING' AND Rechargedate='$date' AND PTime<='$PdatePtime'";
    $rePendingRech=mysqli_query($con,$quPendingRech);
    $countPendingRech=mysqli_num_rows($rePendingRech);
    
    if($countPendingRech>5)
    {
        $myresponse = array("status"=>"FAILED", "errmsg"=>"Operator Block For Pending Txn Above 5 !");
		echo $myresult = json_encode($myresponse);
		exit();
    }
    
	$query2="SELECT * FROM retailer WHERE Userid='$userid'";
	$result2=mysqli_query($con,$query2);
	$databal=mysqli_fetch_array($result2);
	$GetUser = mysqli_num_rows($result2);
	$usrName=$databal['Name'];
	$ApiToken=$databal['ApiToken'];
	$IpAddr=$databal['IpAddr'];
	$JioLM=$databal['JioLM'];
	
	if($GetUser!=1)
	{
	    $myresponse = array("status"=>"FAILED", "errmsg"=>"Invalid Userid !");
		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();
	    }
	}
	if($token!==$ApiToken)
	{    
	    $myresponse = array("status"=>"FAILED", "errmsg"=>"Invalid API Token !");
		echo $myresult = json_encode($myresponse);
	}
	else
	{ //1 
	    
		if($GetUser==1)
		{ //2
			
			$quGetAutoFailedStatus="select * from Auto_Failed where Id='1'";
			$reGetAutoFailedStatus=mysqli_query($con,$quGetAutoFailedStatus);
			$dataGetAutoFailedStatus=mysqli_fetch_array($reGetAutoFailedStatus);
			$AutoFailedStatus=$dataGetAutoFailedStatus['Status'];
				
			$opcodequery="SELECT * FROM operator WHERE OwnApiCode='$OwnApiOpCode'";
			$opcoderesult=mysqli_query($con,$opcodequery);
			$opcodedata=mysqli_fetch_array($opcoderesult);
			$opcode=$opcodedata['Value'];
			$opcode_ROM_STATUS=$opcodedata['ROM'];
			$MyApi2OpCode=$opcodedata['My_API2'];
			$myApiOpCode=$MyApi2OpCode;
			$KwikApiOpCode=$opcodedata['KwikAPI'];
			$UniqueApiOpCode=$opcodedata['UniqueAPI'];
			$DiziPayOpCode=$opcodedata['DiziPayApi'];
			$Dizi_KwikOpCode=$opcodedata['Dizi_Kwik'];
			$PP_ApiOpCode=$opcodedata['PP_Api'];
			$OzzyOpCode=$opcodedata['Ozzy_Api'];
			$RechbesellOpCode=$opcodedata['RechBS_Api'];
			$AmbikaOpCode=$opcodedata['AmbikaApi'];
			$columName=$opcodedata['Commision_Column'];
			$operator = $opcodedata['Operator'];
			$ActiveOp = $opcodedata['Active'];
			$Ozzy_Comm = $opcodedata['Ozzy_Comm'];
	
	        $UseApi1=$opcodedata['UseAPI'];
	        $UseApi2=$opcodedata['UseAPI2'];
	
	        $Parentid=$databal['Parentid'];
            $Grandparentid=$databal['Grandparentid'];
            
            $opName=$operator;
            
            $OwnApiCode=$opcodedata['OwnApiCode'];
            
            //This Code For DiziKwik's & M Robotic's BSNL Special Only
            $OwnApiCode=$OwnApiOpCode;
            
            if($OwnApiCode==3 || $OwnApiCode==4)
            {
                if(0==substr($amount, -1))
	            {
	                $stv_stts="false";
	            }
	            else
	            {
	                $stv_stts="true";
	            }
            }
            else
            {
                $stv_stts="false";
            }
            
	        if($OwnApiCode==4)
	        {
	            $stv=1;
	        }
	        else
	        {
	            $stv=0;
	        }
	
            
	        $UserComm=getComm($userid,$opName);
	        $ParentComm=getComm($Parentid,$opName);
	        $GrandparentComm=getComm($Grandparentid,$opName);
				
			if(!empty($JioLM) && $OwnApiOpCode==10 && $amount<249)
			{   
			    $usercommvalue=$JioLM;
			}
			else
			{
			    $usercommvalue=$usercommvalue1;
			}
			
			$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'];
			$AO=$dataGetUsrOp['AO'];
			$TxnLimit=$dataGetUsrOp['TxnLimit'];
			$LapuGroupId=$dataGetUsrOp['LapuGroupId'];
			$LapuGroupId2=$dataGetUsrOp['LapuGroupId2'];
			
			
			
			if($ActiveOp==1)
			{
				 $myresponse = array("status"=>"FAILED","errmsg"=>"Inactive Operator !", "partnertid"=>$partnerId);
				 echo $myresult = json_encode($myresponse);
				 exit();
			}
			elseif($UsrPersApi1=="OFF" && $UsrPersApi2="OFF")
			{
				 $myresponse = array("status"=>"FAILED","errmsg"=>"Operator Down !", "partnertid"=>$partnerId);
				 echo $myresult = json_encode($myresponse);
				 exit();
			}
			elseif($UserComm>$ParentComm || $ParentComm>$GrandparentComm)
			{
				 $myresponse = array("status"=>"FAILED","errmsg"=>"Invalid Commission Value !", "partnertid"=>$partnerId);
				 echo $myresult = json_encode($myresponse);
				 exit();
			}
			elseif($amount<10)
			{
				 $myresponse = array("status"=>"FAILED","errmsg"=>"Amount Is Less Than 10 !", "partnertid"=>$partnerId);
				 echo $myresult = json_encode($myresponse);
				 exit();
			}
			elseif($OwnApiOpCode==31 && $amount<=180 || $OwnApiOpCode==32 && $amount<=180)
			{
				 $myresponse = array("status"=>"FAILED","errmsg"=>"Transaction Amount Should be between 180 - 10000", "partnertid"=>$partnerId);
				 echo $myresult = json_encode($myresponse);
				 exit();
			}
			else
			{ //3
				if(empty($operator))
				{
					 $myresponse = array("status"=>"FAILED","errmsg"=>"Operator Not Found !", "partnertid"=>$partnerId);
					 echo $myresult = json_encode($myresponse);
				     exit();
				}
				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
		                    $OpBal=getBal($userid);
	                        
							if($amount>=$OpBal)
							{
								$myresponse = array("status"=>"FAILED","errmsg"=>"Insufficiant Your Wallet Balance !", "partnertid"=>$partnerId);
								echo $myresult = json_encode($myresponse);
							}
							else
							{ //6
		                        
		                        $quRechQuality="SELECT * FROM recharge WHERE Userid='$userid' AND Companyname='$operator' ORDER BY Id DESC";
							    $reRechQuality=mysqli_query($con,$quRechQuality);
							    $dataRechQuality=mysqli_fetch_array($reRechQuality);
							    $RechQualityStatus=$dataRechQuality['RoffPerce'];
								    
		                        $quTotRech="SELECT * FROM recharge WHERE Userid='$userid' AND Companyname='$operator' AND Status='SUCCESS' And Rechargedate='$date'";
							    $reTotRech=mysqli_query($con,$quTotRech);
							    $countTotRech=mysqli_num_rows($reTotRech);
							    
							    if($AO>0 && !empty($AO))
							    {
							        $AOflag=1;
							    }
								else
								{
								    $AOflag=0;
								}
								
								
								if(0<getDupRech($mnum,$amount,$opName,$date))
								{
									$myresponse = array("status"=>"FAILED","errmsg"=>"Same Recharge Not Allowed At Same Day !", "partnertid"=>$partnerId);
								    echo $myresult = json_encode($myresponse);
								}
								elseif($OwnApiOpCode==1 && $countTotRech>10 && $RechQualityStatus<$AO && $amount<200 && $AOflag==1 || $OwnApiOpCode==33 && $countTotRech>10 && $RechQualityStatus<$AO && $amount<200 && $AOflag==1)
								{
									$myresponse = array("status"=>"FAILED","errmsg"=>"FAILED !", "partnertid"=>$partnerId);
								    echo $myresult = json_encode($myresponse);
								}
								elseif($OwnApiOpCode==10  && $RechQualityStatus<$AO && $amount<=300 && $AOflag==1)
								{
									$myresponse = array("status"=>"FAILED","errmsg"=>"FAILED !", "partnertid"=>$partnerId);
								    echo $myresult = json_encode($myresponse);
								}
								else
								{ //7
								    $UserCommAmt=$amount*$UserComm/100;
	                                $DebitAmount=$amount-$UserCommAmt;
	
	                                $actualParentComm=$ParentComm-$UserComm;
	                                $ParentCommAmt=$amount*$actualParentComm/100;

	                                $actualGrandParentComm=$GrandparentComm-$ParentComm;
	                                $GrandParentCommAmt=$amount*$actualGrandParentComm/100;
	                                
	                                $usrNewBal=$OpBal-$DebitAmount;
	                                
	                                //for R_Offer Percentage//
	                                if($OwnApiOpCode==10)
	                                {
	                                    $totalTxn=1;
	                                    $txnAbove239=0;
	                                    $txnPerc=0;
	                                    
	                                    $quOpTxn="SELECT * FROM recharge WHERE OpCode='$OwnApiOpCode' AND STATUS='SUCCESS' AND Rechargedate='$date' AND Userid='$userid'";
	                                    $reOpTxn=mysqli_query($con,$quOpTxn);
	                                    while($dataOpTxn=mysqli_fetch_array($reOpTxn))
	                                    {
	                                        if($dataOpTxn['Amount']>299)
	                                        {
	                                            $txnAbove239=$txnAbove239+$dataOpTxn['Amount'];
	                                        }
	                                        $totalTxn=$totalTxn+$dataOpTxn['Amount'];
	                                    }
	                                    
	                                    $txnResho = $txnAbove239/$totalTxn;
	                                    $txnPerc = $txnResho*10;
	                                    
	                                   // $txnPerc=6;
	                                }
	                                else
	                                {
	                                    $txnAmount=1;
	                                    $txnRoffer=0;
	                                    $txnPerc=0;
	                                    $quOpTxn="SELECT * FROM recharge WHERE OpCode='$OwnApiOpCode' AND STATUS='SUCCESS' AND Rechargedate='$date' AND Userid='$userid' AND API='My_API' OR OpCode='$OwnApiOpCode' AND STATUS='SUCCESS' AND Rechargedate='$date' AND Userid='$userid' AND API='My_API2' OR OpCode='$OwnApiOpCode' AND STATUS='SUCCESS' AND Rechargedate='$date' AND Userid='$userid' AND API='My_API3' OR OpCode='$OwnApiOpCode' AND STATUS='SUCCESS' AND Rechargedate='$date' AND Userid='$userid' AND API='My_API4'";
	                                    $reOpTxn=mysqli_query($con,$quOpTxn);
	                                    while($dataOpTxn=mysqli_fetch_array($reOpTxn))
	                                    {
	                                        $txnAmount=$txnAmount+$dataOpTxn['Amount'];
	                                        $txnRoffer=$txnRoffer+$dataOpTxn['R_Offer'];
	                                    }
	                                    $txnPerc=$txnRoffer/$txnAmount*100;
	                                }
	                                
	                                $txnPercentage=getRA($txnPerc);
	                                
									$insertRech="INSERT INTO recharge(Partnerid,Userid,RetComm,RetCommAmt,Parentid,DisComm,Grandparentid,MdComm,Rechargedate,Time,PTime,Agentname,Balance,OpCode,Companyname,Mobile,Amount,RoffPerce,Debitamount,IP)
		                            VALUES ('$partnerId','$userid','$UserComm','$UserCommAmt','$Parentid','$ParentComm','$Grandparentid','$GrandparentComm','$date','$time','$PTime','$usrName','$usrNewBal','$OwnApiOpCode','$opName','$mnum','$amount','$txnPercentage','$DebitAmount','$IP')";
		                            if(mysqli_query($con,$insertRech))
									{ //8  
										$newrechid=mysqli_insert_id($con);
		    	                        
										$insertWallet="INSERT INTO wallet (Userid,OpBal,Txn,ClBal,TxnType,TxnWith,TxnId,Remarks,Date,Time,APBU,IP)
			                            VALUES ('$userid','$OpBal','-$DebitAmount','$usrNewBal','RECHARGE','SELF','$newrechid','DEBIT FOR RECHARGE','$date','$time','$userid','$IP')";
			                            if(mysqli_query($con,$insertWallet))
										{ //9
											$ewalletid=mysqli_insert_id($con);
											
											$updateRech="UPDATE recharge SET Ewalletid='$ewalletid' where Id='$newrechid'";
				                            mysqli_query($con,$updateRech);
				                            
				                            $UpdateBal="UPDATE retailer SET Balance='$usrNewBal', Lastrechdate='$date' where Userid='$userid'";
				                            mysqli_query($con,$UpdateBal);
				
				                            $quParComm="INSERT INTO commwallet(Userid,Balance,Date,Time,Rechargeid)
				                            VALUES ('$Parentid','$ParentCommAmt','$date','$time','$newrechid')";
				                            mysqli_query($con,$quParComm);
												
				                            $quGparComm="INSERT INTO commwallet(Userid,Balance,Date,Time,Rechargeid)
				                            values('$Grandparentid','$GrandParentCommAmt','$date','$time','$newrechid')";
				                            mysqli_query($con,$quGparComm);
												
											if($UsrPersApi1!="OFF")
											{
												if($UsrPersApi1=="By_Default" || $UsrPersApi1=="ON")
											    {
											        if($UseApi1!="OFF")
											        {
											            $UseApiName=$UseApi1;
											        }
											        else
											        {
												        $UseApiName=$UseApi2;
											        }
											    }
											    else
											    {
											        $UseApiName=$UsrPersApi1;
											    }
											}
											else
											{
											    if($UsrPersApi2=="By_Default" || $UsrPersApi2=="ON")
											    {
											        if($UseApi1!="OFF")
											        {
											            $UseApiName=$UseApi1;
											        }
											        else
											        {
												        $UseApiName=$UseApi2;
											        }
											    }
											    else
											    {
											        $UseApiName=$UsrPersApi2;
											    }
											}
											$apiFile="RechFile_".$UseApiName.".php";						
				
				                           include $apiFile;
										}
									}
								}
							}				
				}		}		
			}
		} //2 
	} //1
	
	$time_end = microtime(true);
    $execution_time = floor(($time_end - $time_start));
    $UpdateExcTime="UPDATE recharge SET RespoTime='$execution_time' WHERE Id='$newrechid'";
	mysqli_query($con,$UpdateExcTime);
	
	ob_end_flush();
?>	