<?php
    include'connection.php';
    
    
    
    date_default_timezone_set("asia/Kolkata");
	$datetime= Date("Y-m-d - h:i:s A");-
	$time= Date("h:i:s A");
	$date= Date("Y-m-d");
    
    $id = $_GET['client_id'];
    $status = $_GET['status'];
    $orderid = $_GET['payid'];
    $txid = $_GET['operator_ref'];
    
    
    
	$quGetRechData="select * from recharge where Id='$id'";
	$reGetRechData=mysqli_query($con,$quGetRechData);
	$dataGetRech=mysqli_fetch_array($reGetRechData);
	$userid=$dataGetRech['Userid'];
	$mobile=$dataGetRech['Mobile'];
	$amount=$dataGetRech['Amount'];
	$operator=$dataGetRech['Companyname'];
	$CheckStatus=$dataGetRech['Status'];
	$Partnerid=$dataGetRech['Partnerid'];
	
    	$query8="select * from wallet where Userid='$userid' order by Id desc";
		$result8=mysqli_query($con,$query8);
		$data8=mysqli_fetch_array($result8);
		$currentbal= $data8['Balance'];
		
		$query2="select * from retailer where Userid='$userid'";
		$result2=mysqli_query($con,$query2);
		$databal=mysqli_fetch_array($result2);
		$username=$databal['Name'];
		$parentid=$databal['Parentid'];
		$grandparentid=$databal['Grandparentid'];
		$CallBackUrl=$databal['CallBackUrl'];
		$ApiActive=$databal['ApiActive'];
	    
	    if($ApiActive==1)
	    {
	        $ch = curl_init();
	        
    		curl_setopt($ch, CURLOPT_URL, "$CallBackUrl?partnertid=$Partnerid&status=$status&orderid=$id&opid=$txid&errmsg=$txid");
	    	curl_setopt($ch, CURLOPT_POST, false );
		    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
    		curl_setopt($ch, CURLOPT_TIMEOUT, 0);
	    	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
		
		    curl_close($ch);
	    }
	
	        $opcodequery="select * from operator where Operator='$operator'";
			$opcoderesult=mysqli_query($con,$opcodequery);
			$opcodedata=mysqli_fetch_array($opcoderesult);
			$opcode=$opcodedata['Value'];
			$columName=$opcodedata['Commision_Column'];
			
			$querygetcom="select * from commision where Userid='$userid'";
			$rsultgetcom=mysqli_query($con,$querygetcom);
			$data=mysqli_fetch_array($rsultgetcom);
			$usercommvalue=$data[$columName];
			
			$commision=$amount*$usercommvalue/100;
			$actual=$amount-$commision;
	
	if($status=="PENDING"){
	$pendingquery="update recharge set Status='$status', Transactionid='$orderid' where Id='$id'";
	mysqli_query($con,$pendingquery);
	echo "Your Recharge Request Pending Now !";
	
	}
	elseif($status=="SUCCESS")
	{
	    $GetLapuOldBal="select * from recharge where LapuNo='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;
    	
		$sucessquery="update recharge set Status='$status', Transactionid='$orderid', Operatorid='$txid', API='Kwik_API', ApiBal='$KwikApiBal', AdminOpId='S' where Id='$id'";
		mysqli_query($con,$sucessquery);
		$aa=json_encode($_GET);
        
        $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='$id'";
			mysqli_query($con,$UpdateRechApibal);
	}
	else
	{   $quGetAutoFailedStatus="select * from Auto_Failed where Id='1'";
		$reGetAutoFailedStatus=mysqli_query($con,$quGetAutoFailedStatus);
		$dataGetAutoFailedStatus=mysqli_fetch_array($reGetAutoFailedStatus);
		$AutoFailedStatus=$dataGetAutoFailedStatus['Status'];
		
	    if($CheckStatus=="FAILED")
	    {
	        
	    }
	    elseif($AutoFailedStatus=="Deactive" || $txid=="Insufficient Balance.")
	    {
	        $UpdateRechApibal="update recharge set ReHit='1', AdminOpId='$txid' where Id='$id'";
	    	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','$id','$operator','$mobile','$amount','$status')";
    		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='$status', Transactionid='$orderid', Operatorid='$txid', Responsetxt='$resText',API='Kwik_API' where Id='$id'";
    			
    			mysqli_query($con,$failedquery);
    			
    			$deletecomm="delete from commwallet where Rechargeid='$id'";
            	mysqli_query($con,$deletecomm);
            	
    			$query9="update retailer set Balance='$refundnewbal' where Userid='$userid'";
    			mysqli_query($con,$query9);
    			
    			echo "Your Recharge Request Has Been Failed Now !";
    		
    		}
	    }
	}
?>