<?php
    
    function numFormat($number, $decimals=0)
    {
        if (strpos($number,'.')!=null)
        {
            $decimalNumbers = substr($number, strpos($number,'.'));
            $decimalNumbers = substr($decimalNumbers, 1, $decimals);
        }
        else
        {
            $decimalNumbers = 0;
            for ($i = 2; $i <=$decimals ; $i++)
            {
                $decimalNumbers = $decimalNumbers.'0';
            }
        }


        $number = (int) $number;
        $number = strrev($number);  // reverse

        $n = '';
        $stringlength = strlen($number);

        for ($i = 0; $i < $stringlength; $i++)
        {
            // from digit 3, every 2 digit () add comma
            if($i==2 || ($i>2 && $i%2==0) ) $n = $n.$number[$i].','; 
            else $n = $n.$number[$i];
        }

        $number = $n;    
        $number = strrev($number); // reverse

        ($decimals!=0)? $number=$number.'.'.$decimalNumbers : $number ;
        if ($number[0] == ',') $number = substr_replace($number, '', 0, 1);
        if ($number[1] == ',' && $number[0] == '-') $number = substr_replace($number, '', 1, 1);      

        return $number;
    }
    function getTxn($usrId)
    {
        include'connection.php';
        $totalAmt=0;
		$quRech="SELECT Amount FROM recharge WHERE Userid='$usrId' AND Status='SUCCESS'";
		$reRech=mysqli_query($con,$quRech);
		while($dataRech=mysqli_fetch_array($reRech))
        {
            $totalAmt=$totalAmt+$dataRech['Amount'];
        }
        return($totalAmt);
    }
    
    function checkChild($parentId, $childId)
    {
        include'connection.php';
        $flag=0;
        $tmp_ChildId=$childId;
        while($flag==0)
        {
            $qu="SELECT * FROM MLM_Users WHERE Userid='$tmp_ChildId'";
            $re=mysqli_query($con,$qu);
            $count=mysqli_num_rows($re);
            if($count==0)
            {
                $flag=1;
                $result="Invalid Userid !"; 
            }
            else
            {
                $data=mysqli_fetch_array($re);
                if($data['Parent_Id']==$parentId)
                {
                    $flag=1;
                    $result="true";
                }
                elseif(empty($data['Parent_Id']))
                {
                    $flag=1;
                    $result="User Is Not In Your Downline !";
                }
                else
                {
                    $tmp_ChildId=$data['Parent_Id'];
                }
            }
        }
        return($result);
    }
    
    function checkPlace($parentId)
    {
        include'connection.php';
        $quTree="SELECT * FROM MLM_Tree WHERE Userid='$parentId'";
        $reTree=mysqli_query($con,$quTree);
        $dataTree=mysqli_fetch_array($reTree);
        $rightSide=$dataTree['RightSide'];
        $leftSide=$dataTree['LeftSide'];
        
        $countParent=mysqli_num_rows($reTree);
        if($countParent<1)
        {
            return("Parent User Not Found");
        }
        elseif(empty($rightSide))
        {
            return("Right");
        }
        elseif(empty($leftSide))
        {
            return("Left");
        }
        else
        {
            return("PNA");
        }
        
    }
    
    function getBackDate($date,$day)
    {
        $date1=date_create($date);
		date_sub($date1,date_interval_create_from_date_string($day." days"));
		$resultdate=date_format($date1,"Y-m-d");
		return($resultdate);
    }
    
    function getCBT($parentId)
    {
        include'connection.php';
        include'time.php';
        
        $quDis="SELECT * FROM distributer WHERE Userid='$parentId'";
        $reDis=mysqli_query($con,$quDis);
        $dataDis=mysqli_fetch_array($reDis);
        $disTxn=$dataDis['TotalTxn'];
        $disTxnDate=$dataDis['TxnDate'];
        $disPackComm=$dataDis['PackComm'];
        $CBTS=$dataDis['CBTS'];
        
        $backDate=getBackDate($date,1);
        
        if($disTxnDate!=$backDate && $CBTS=="ACTIVE")
        {
            
            $totalTxn=0;
            $quTxn="SELECT * FROM recharge WHERE Status='SUCCESS' AND Rechargedate='$backDate' AND Parentid='$parentId'";
            $reTxn=mysqli_query($con,$quTxn);
            while($dataTxn=mysqli_fetch_array($reTxn))
            {
                $totalTxn=$totalTxn+$dataTxn['Amount'];
            }
        
            if($totalTxn>=100000)
            {
                $packComm=5;
            }
            elseif($totalTxn<100000 && $totalTxn>=50000)
            {
                $packComm=4.5;
            }
            elseif($totalTxn<50000 && $totalTxn>=25000)
            {
                $packComm=4;
            }
            elseif($totalTxn<25000 && $totalTxn>=10000)
            {
                $packComm=3.5;
            }
            elseif($totalTxn<10000 && $totalTxn>=5000)
            {
                $packComm=3.25;
            }
            else
            {
               $packComm=3; 
            }
            
            if($packComm>$disPackComm || $packComm<$disPackComm)
            {
                $updateComm="UPDATE CommSlab SET Comm='$packComm' WHERE Userid='$parentId' AND ServiceId='1' OR Userid='$parentId' AND ServiceId='2'";
                if(mysqli_query($con,$updateComm))
                {
                    $updateDate="UPDATE distributer SET TotalTxn='$totalTxn', TxnDate='$backDate', PackComm='$packComm' WHERE Userid='$parentId'";
                    mysqli_query($con,$updateDate);
                }
            }
            
        }
    }
    
    function getName($usrId)
    {   
	    include'connection.php';
	    $usrDigit=substr($usrId,0,2);
	    
	    if(empty($usrId))
	    {
	        $retName="";
	        return($retName);
	    }
	    elseif($usrDigit==11 || $usrDigit==22)
	    {
	        $retName="ADMIN";
	        return($retName);
	    }
	    else
	    {
	        if(10==strlen($usrId))
	        {
	            $quGetName="SELECT * FROM MLM_Users WHERE Userid='$usrId'";
	        }
	        elseif($usrDigit==50)
	        {
	            $quGetName="SELECT * FROM retailer WHERE Userid='$usrId'";  
	        }
	        elseif($usrDigit==20)
	        {
	            $quGetName="SELECT * FROM distributer WHERE Userid='$usrId'";
	        }
	        elseif($usrDigit==30)
	        {
	            $quGetName="SELECT * FROM masterdis WHERE Userid='$usrId'";
	        }
	        else
	        {
	            $retName="";
                return($retName);
                exit();
	        }
	        
	        if($reGetName=mysqli_query($con,$quGetName))
	        {
                $dataGetName=mysqli_fetch_array($reGetName);
                $retName=$dataGetName['Name'];
                return($retName);
	        }
	        else
	        {
	            $retName="";
                return($retName);
	        }
	    }
    }
    
    function getUser($usrId)
    {   
	    include'connection.php';
	    $usrDigit=substr($usrId,0,2);
	    
	    if(empty($usrDigit))
	    {
	        $retName=" ";
	        return($retName);
	    }
	    elseif($usrDigit==11 || $usrDigit==22)
	    {
	        $retName="ADMIN";
	        return($retName);
	    }
	    else
	    {
	        if(10==strlen($usrId))
	        {
	            $quGetName="SELECT * FROM MLM_Users WHERE Userid='$usrId'";
	        }
	        elseif($usrDigit==50)
	        {
	            $quGetName="SELECT * FROM retailer WHERE Userid='$usrId'";  
	        }
	        elseif($usrDigit==20)
	        {
	            $quGetName="SELECT * FROM distributer WHERE Userid='$usrId'";
	        }
	        elseif($usrDigit==30)
	        {
	            $quGetName="SELECT * FROM masterdis WHERE Userid='$usrId'";
	        }
	        
	        $reGetName=mysqli_query($con,$quGetName);
            $dataGetUsr=mysqli_fetch_array($reGetName);
            return($dataGetUsr);
	    }
    }
    
    function getUBWI($usrId)
    {
        include'connection.php';
	    include'time.php';
	    
        $quGetEwalletId="SELECT * FROM RetBal WHERE Userid='$usrId'";
        $reGetEwalletId=mysqli_query($con,$quGetEwalletId);
        $dataGetEwalletId=mysqli_fetch_array($reGetEwalletId);
        $EwalletId=$dataGetEwalletId['Walletid'];
        $EwalletIdDate=$dataGetEwalletId['Date'];
    
        $quDisOpBal="SELECT * FROM wallet WHERE Userid='$usrId' AND Id>=$EwalletId";
	    $reDisOpBal=mysqli_query($con,$quDisOpBal);
	    $countTxn=mysqli_num_rows($reDisOpBal);
	    if($countTxn>=1000 && $date!=$EwalletIdDate)
	    {
	        $Bal=0;
	        while($dataDisOpBal=mysqli_fetch_array($reDisOpBal))
	        {
	            $OldDisTxn= $dataDisOpBal['Txn'];
	            $Bal=$Bal+$OldDisTxn;
	        }
	        
	        $insertWallet="INSERT INTO wallet (Userid,OpBal,Txn,ClBal,Date,Time,Remarks) VALUES ('$usrId','$Bal','$Bal','$Bal','$date','$time','Update Wallet Id')";
	        if(mysqli_query($con,$insertWallet))
	        {
	            $newWalletId=mysqli_insert_id($con);
	            
	            $update="UPDATE RetBal SET Date='$date', Time='$time', Walletid='$newWalletId', Balance='$Bal' WHERE Userid='$usrId'";
	            mysqli_query($con,$update);
	        }
	    }
    }
    
    function getBal($usrId)
    {
        include'connection.php';
        $quGetEwalletId="SELECT * FROM RetBal WHERE Userid='$usrId'";
        $reGetEwalletId=mysqli_query($con,$quGetEwalletId);
        $dataGetEwalletId=mysqli_fetch_array($reGetEwalletId);
        $EwalletId=$dataGetEwalletId['Walletid'];
    
        if(10==strlen($usrId))
		{
		    $quDisOpBal="SELECT * FROM MLM_Wallet WHERE Userid='$usrId'";
		}
		else
		{
            $quDisOpBal="SELECT * FROM wallet WHERE Userid='$usrId' AND Id>=$EwalletId";
	    }
        
        
	    $reDisOpBal=mysqli_query($con,$quDisOpBal);
	    $Bal=0;
	    while($dataDisOpBal=mysqli_fetch_array($reDisOpBal))
	    {
	       $OldDisTxn= $dataDisOpBal['Txn'];
	       $Bal=$Bal+$OldDisTxn;
	    }
	    return($Bal);
    }
    
    function getOp($opName)
    {
        include'connection.php';
        
        $quGetOp="SELECT * FROM operator WHERE Operator='$opName'";
        $reGetOp=mysqli_query($con,$quGetOp);
        $dataOp=mysqli_fetch_array($reGetOp);
        
        return($dataOp);
    }
    function getOpName($opCode)
    {
        include'connection.php';
        
        $quGetOp="SELECT * FROM operator WHERE OwnApiCode='$opCode'";
        $reGetOp=mysqli_query($con,$quGetOp);
        $dataOp=mysqli_fetch_array($reGetOp);
        
        return($dataOp['Operator']);
    }
    
    function getDupRech($mobileNo,$amount,$opName,$date)
    {
        include'connection.php';
        $quDupRech="SELECT * FROM recharge WHERE Mobile='$mobileNo' AND Amount='$amount' AND Companyname='$opName' AND Rechargedate='$date' AND Status='SUCCESS' OR Mobile='$mobileNo' AND Amount='$amount' AND Companyname='$opName' AND Rechargedate='$date' AND Status='PENDING'";
	    $reDupRech=mysqli_query($con,$quDupRech);
	    $countDupRech=mysqli_num_rows($reDupRech);
	    return($countDupRech);
    }
    
    function getComm($usrId,$opName)
    {
        include'connection.php';
        $quComm="SELECT * FROM CommSlab WHERE Userid='$usrId' AND OpName='$opName'";
	    $reComm=mysqli_query($con,$quComm);
	    $dataComm=mysqli_fetch_array($reComm);
	    $usrComm=$dataComm['Comm'];
	    return($usrComm);
    }
    
    
    function chk_msg($msg_string, $chk_string)
    {
        include'connection.php';
        $msg_upper_string=strtoupper($msg_string);
        $chk_upper_string=strtoupper($chk_string);
        $result=similar_text($msg_upper_string, $chk_upper_string);
        
        return($result);
    }
    
    function getAFS()
    {
        include'connection.php';
        $quGetAutoFailedStatus="SELECT * FROM Auto_Failed WHERE Id='1'";
		$reGetAutoFailedStatus=mysqli_query($con,$quGetAutoFailedStatus);
		$dataGetAutoFailedStatus=mysqli_fetch_array($reGetAutoFailedStatus);
		$AutoFailedStatus=$dataGetAutoFailedStatus['Status'];
		return($AutoFailedStatus);
    }
    
    function getApiNo($newrechid)
    {
        include'connection.php';
        $quGetApiNo="SELECT API_NO FROM recharge WHERE Id='$newrechid'";
        $reGetApiNo=mysqli_query($con,$quGetApiNo);
        $dataApiNo=mysqli_fetch_array($reGetApiNo);
        $apiNo=$dataApiNo['API_NO'];
        
        return($apiNo);
    }
    
    function getRA($amount)
    {
        $realAmount=number_format((float)$amount, 2, '.', '');
        return($realAmount);
    }
    
    function getLON($LapuNo)
    {
        include'connection.php';
        if(!empty($LapuNo))
    	{
		    $quGetLapuOwner="SELECT Seller FROM myapi WHERE LapuNumber='$LapuNo'";
		    if($reGetLapuOwner=mysqli_query($con,$quGetLapuOwner))
		    {
		        $dataGetLapuOwner=mysqli_fetch_array($reGetLapuOwner);
			    $LapuOwner=$dataGetLapuOwner['Seller'];
		    }
		    else
		    {
		        $LapuOwner="";
		    }
			
    	}
    	else
    	{
    	    $LapuOwner="";
    	}
    	
    	return($LapuOwner);
    }
    
    function getLB($operator)
    {
        include'connection.php';
        $TotalLapuBal=0;
        $quMyApi="SELECT * FROM myapi WHERE Operator='$operator'";
	    $reMyApi=mysqli_query($con,$quMyApi);
	    while($dataMyApi=mysqli_fetch_array($reMyApi))
	    {
	        $LapuBal=$dataMyApi['LapuBal'];
		    $TotalLapuBal=$TotalLapuBal+$LapuBal;
	    }
	    return($TotalLapuBal);
    }
    
    function getOzzyBal()
    {
        include'connection.php';
        $apiUsrId=170;
        $apiToken="2bc8fc628274544b5ba8445989e865ec";
        $url="http://ozzyrecharge.com/API/Balance?UserID=$apiUsrId&Token=$apiToken";
        $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);
		$data2=json_decode($output);
		$errorcode = $data2->errorcode;
		$OzzyApiBal = $data2->bal;
		return($OzzyApiBal);
    }
    
    function getAmbikaBal()
    {
        include'connection.php';
        $apiUsrId=24044;
        $apiToken="a5b6785b70c50928ea48f6959b7d9430";
        $url="http://api.ambikamultiservices.com/API/Balance?UserID=$apiUsrId&Token=$apiToken";
        $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);
		$data2=json_decode($output);
		$errorcode = $data2->errorcode;
		$AmbikaApiBal = $data2->bal;
		return($AmbikaApiBal);
    }
    
    function getDiziBal()
    {
        $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);
    
        $ApiBal = $result['BALANCE'];
        return($ApiBal);
    }
    
    function getRechByData($op,$api1,$api2)
    {
        include'connection.php';
        
        date_default_timezone_set("asia/kolkata");
		$dateApiBal=date("Y-m-d");
		$dateAB=date_create($dateApiBal);
		date_sub($dateAB,date_interval_create_from_date_string("1 days"));
		$resultdateAB=date_format($dateAB,"Y-m-d");
		
        $totalTRechAmt=0;
        $totalYRechAmt=0;
        $totalTRO=0;
        if($op=="ALL")
        {
           $quRech="SELECT * FROM recharge WHERE API='$api1' and Status='SUCCESS' and Rechargedate>='$resultdateAB' OR API='$api2' and Status='SUCCESS' and Rechargedate>='$resultdateAB'";
        }
        else
        {
            $quRech="SELECT * FROM recharge WHERE Companyname='$op' AND API='$api1' and Status='SUCCESS' and Rechargedate>='$resultdateAB' OR Companyname='$op' AND API='$api2' and Status='SUCCESS' and Rechargedate>='$resultdateAB'";
        }
		$reRech=mysqli_query($con,$quRech);
		while($dataRech=mysqli_fetch_array($reRech))
		{
		    if($dataRech['Rechargedate']==$date)
		    {   
		        $rechTAmount=$dataRech['Amount'];
		        $totalTRechAmt=$totalTRechAmt+$rechTAmount;
		        
		        $rechTRO=$dataRech['R_Offer'];
		        $totalTRO=$totalTRO+$rechTRO;
		    }
		    else
		    {
		        $rechYAmount=$dataRech['Amount'];
		        $totalYRechAmt=$totalYRechAmt+$rechYAmount;
		    }
		    
		    
		}
		//$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

		$result = array ("RECHT"=>$totalTRechAmt,"RECHY"=>$totalYRechAmt, "ROT"=>$totalTRO);
		return($result);
    }
    
?>