<?php
    //include'connection.php';
    //include'functions.php';
    
    $apiOldNo=getApiNo($newrechid);
    $apiNewNo=$apiOldNo+1;
    
    $UpdateRechApi="UPDATE recharge SET API='My_API4', API_NO='$apiNewNo' where Id='$newrechid'";
	mysqli_query($con,$UpdateRechApi);
											    		
	$ch = curl_init();

    if (!$ch)
    {
        die("Couldn't initialize a cURL handle");
    }
    
    if($MyApi2OpCode==97)
    {
	    $MyApi2OpCode=2;
    }
	
	if($apiNewNo==1 && !empty($LapuGroupId))
    {
        $LapuGroupIdCode="&group_id=".$LapuGroupId;
    }
    elseif($apiNewNo==2 && !empty($LapuGroupId2))
    {
        $LapuGroupIdCode="&group_id=".$LapuGroupId2;
    }
    else
    {
        $LapuGroupIdCode="";
    }
	
    
    if($opcode_ROM_STATUS=="NO")
    {
        $API_URL = "https://mrobotics.in/api/recharge_statewise?";
        $apiUrl="api_token=37a1e7bd-3d24-4d73-8c17-ecd76d5a847e&mobile_no=$mnum&amount=$amount&company_id=$MyApi2OpCode&only_roffer=true&order_id=$newrechid&is_stv=$stv_stts&no_roaming=false$LapuGroupIdCode";
    }
    else
    {
        $API_URL = "https://mrobotics.in/api/recharge?";
        $apiUrl="api_token=37a1e7bd-3d24-4d73-8c17-ecd76d5a847e&mobile_no=$mnum&amount=$amount&company_id=$MyApi2OpCode&only_roffer=true&order_id=$newrechid&is_stv=$stv_stts$LapuGroupIdCode";
    }
    
    
    curl_setopt($ch, CURLOPT_URL,$API_URL); // 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);
    //$apiUrl="api_token=37a1e7bd-3d24-4d73-8c17-ecd76d5a847e&mobile_no=$mnum&amount=$amount&company_id=$MyApi2OpCode&only_roffer=true&order_id=$newrechid&is_stv=$stv_stts";
	
    curl_setopt($ch, CURLOPT_POSTFIELDS,$apiUrl);
    $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'];   
	$roffer = $result['roffer'];  
	$romingStatus = $result['is_roaming'];   
	
	
	if($romingStatus=="true")
	{
	    $roamingMsg="Y";
	}
	else
	{
	    $roamingMsg="N";
	}
												
	$updateLapu="UPDATE recharge SET LapuNo='$LapuNo', Roaming='$roamingMsg' where Id='$newrechid'";
	mysqli_query($con,$updateLapu);
    
    if($status1=="SUCCESS" || $status1=="success")
	{
	    if($LapuNo=="8865063210")
	    {
	        if($OwnApiOpCode==35)
	        {
	            $GetLapuOldBal="SELECT * FROM recharge WHERE LapuNo='$LapuNo' AND status='SUCCESS' AND OpCode='35' ORDER BY Id DESC";
	        }
	        else
	        {
	            $GetLapuOldBal="SELECT * FROM recharge WHERE LapuNo='$LapuNo' AND status='SUCCESS' AND OpCode!='35' ORDER BY Id DESC";
	        }
	    }
	    else
	    {
	        $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'];
		$LapuOldBalRow=mysqli_num_rows($reGetLapuOldBal);
													
		if($LapuOldBalRow==0 || $LapuOldBal==0 || empty($LapuOldBal))
		{
		    $LapuOldBal=0;
			$remaiBal=$LapuOldBal-$amount;
			$LapuDiff = $LapuBal-$remaiBal;
		}
		else
		{
		    $remaiBal=$LapuOldBal-$amount;
			$LapuDiff = $LapuBal-$remaiBal;	
		}
		
		$UpadateStatus="UPDATE recharge SET Status='SUCCESS', R_Offer='$roffer', Operatorid='$txnId', LapuOldBal='$LapuOldBal', Diff='$LapuDiff', ApiBal='$LapuBal' WHERE Id='$newrechid'";
		mysqli_query($con,$UpadateStatus);
																
		$quUpdatebal="UPDATE myapi SET LapuBal='$LapuBal', LastUpdate='$date', OrderId='$newrechid' WHERE LapuNumber='$LapuNo'";
		mysqli_query($con,$quUpdatebal);
		
		$myresponse = array("status"=>"SUCCESS", "partnertid"=>"$partnerId", "orderid"=>"$newrechid", "opid"=>"$txnId");
		echo $myresult = json_encode($myresponse);
													                                                    
		/*	$success_msg="Request Submitted Successfully !";
	        echo "<div class='msg-div'>
			    <form method='post'>
			        <h3>".$success_msg."</h3><br>
					<i class='fa fa-check-circle' aria-hidden='true' id='okIcon'></i><br><br>
				    <button type='submit' class='btnPopup'>OK</button><br><br>
                </form>
           </div>";*/
	}
	elseif($status1=="FAILED" || $status1=="failure")
	{
	    $autoFailedStatus=getAFS();
	    
	    if(chk_msg($msg,'Noreco')==6  || chk_msg($msg,'BadMSISDN')==9 || chk_msg($msg,'SubsNot')==7)
        {
            $Printmsg ="Invalid Number Or Operator !";
            $flag=1;
        }
        elseif(chk_msg($msg,'NoPlans')==7  || chk_msg($msg,'TranFail')==8 || chk_msg($msg,'Cardgorup')==9)
		{
			$Printmsg ="Invalid Amount !";
            $flag=1;
		}
		elseif(chk_msg($msg,'PrimePlan')==9)
		{
		    $Printmsg ="You can only select other than prime plan for recharge.	";
            $flag=1;
		}
		elseif(chk_msg($msg,'amountdue')==9)
		{
		    $Printmsg ="Please clear due amount and then proceed with the recharge.";
            $flag=1;
		}
		elseif(chk_msg($msg,'sessExpi')==8)
		{
		    $Printmsg ="Lapu Session Expired !";
            $flag=0;
            $toMail="sameermansuri111@gmail.com";
            $toName="Sameer";
            $subjectMail="Lapu Session Expired !";
            $msgMail="Your Lapu Session Has Been Expired ! Lapu No. Is ".$LapuNo;
           // include'../Admin1/testMail/send_mail.php';
		}
		elseif(chk_msg($msg,'insufbalan')==10 || chk_msg($errorMsg,'lapuONLowLapu')==13)
		{
		    $Printmsg ="FAILED I.B. !";
            $flag=0;
            $toMail="sameermansuri111@gmail.com";
            $toName="Sameer";
            $subjectMail="Insufficiant Balance !";
            $msgMail="You Have Insufficiant Balance In Your Lapu ! Lapu No. Is ".$LapuNo;
            //include'../Admin1/testMail/send_mail.php';
            //$quins="INSERT INTO Test (Date,Time,TestData) VALUES ('$date','$time','$errorMsg')";
	        //mysqli_query($con,$quins);
	
		}
		else
		{
		    $Printmsg = $msg;
            $flag=0;
		}
		
	    $flagFailedForAO=0;
	    if($AO>0 && $RechQualityStatus<$AO)
	    {
	        $flagFailedForAO=1;
	        $Printmsg="FAILED";
	    }
													      
		if($flag==1 || $apiNewNo==2 || $flagFailedForAO==1)
		{
		    include'rechFailed.php';											          
		}
		else
		{
		    $flagFailed=0;
		    if($UsrPersApi2!="OFF" && $UsrPersApi2!="My_API4")
		    {
		            if($UsrPersApi2=="ON" || $UsrPersApi2=="By_Default")
		            {
		                if($UseApi1!="OFF" && $UseApi1!="My_API4")
		                {
		                    $apiFile2="RechFile_".$UseApi1.".php";
		                }
		                elseif($UseApi2!="OFF" && $UseApi2!="My_API4")
		                {
		                    $apiFile2="RechFile_".$UseApi2.".php";
		                }
		                else
		                {
		                    $flagFailed=1;
		                }
		            }
		            else
		            {
		                $apiFile2="RechFile_".$UsrPersApi2.".php";
		            }
				    if($flagFailed==0)
				    {
			    	    include $apiFile2;
				    }
		    }
		    else
		    {
		         $flagFailed=1;
		    }
		    
	        if($flagFailed==1)
	        {
		        if($autoFailedStatus!="Deactive")
		        {   
		            include'rechFailed.php';
		        }
		        else
		        {
		            $UpdateRechApibal="UPDATE recharge SET ReHit='1', AdminOpId='$Printmsg' WHERE Id='$newrechid'";
			        mysqli_query($con,$UpdateRechApibal);
			        
			        $myresponse = array("status"=>"PENDING", "partnertid"=>"$partnerId", "orderid"=>"$newrechid", "opid"=>"$txnId");
					echo $myresult = json_encode($myresponse);
												
			        
			        /*$success_msg="Request Submitted Successfully !";
	                echo "<div class='msg-div'>
				        <form method='post'>
				            <h3>".$success_msg."</h3><br>
    					    <i class='fa fa-check-circle' aria-hidden='true' id='okIcon'></i><br><br>
		    			    <button type='submit' class='btnPopup'>OK</button><br><br>
			    	    </form>
	    		     </div>";*/
		        }
		
		    }
		}
	}

?>