<?php
    ob_start();
	session_start();
	if($_SESSION['did'])
	{
		$userid=$_SESSION['did'];
		$fdate=$_SESSION['fd'];
	    $ldate=$_SESSION['ld'];
		$sum=$_SESSION['sm'];
		if($sum<100)
		{
		    echo "<h2 align='center' style='color:red;'>Commission Will Be Redeemed Rs.100 or Above only !</h2>";
		    exit();
		}
	}
	else
	{
		header('location:../login.php');
	}
?>
<?php
	include'connection.php';
	include'../Retailers/functions.php';
	
	date_default_timezone_set("asia/kolkata");
	$date=date("Y-m-d");
	$time=date("h:i:s A");
	
	$quGetEwalletId="select * from RetBal where Userid='$userid'";
    $reGetEwalletId=mysqli_query($con,$quGetEwalletId);
    $dataGetEwalletId=mysqli_fetch_array($reGetEwalletId);
    $EwalletId=$dataGetEwalletId['Walletid'];
    
        $quOldBal="select * from wallet where Userid='$userid' and Id>=$EwalletId";
	    $reOldBal=mysqli_query($con,$quOldBal);
	    $oldBal=0;
	    while($dataOldBal=mysqli_fetch_array($reOldBal))
	    {
	        $usrBal= $dataOldBal['Txn'];
	        $oldBal=$oldBal+$usrBal;
	    }
	    $newBal=$oldBal+$sum;
	    
	$updateq="update commwallet set Active='1' where Userid=$userid and Date>='$fdate' and Date<='$ldate'";
	if(mysqli_query($con,$updateq))
	{   
	    $insertq="insert into wallet(Userid,OpBal,Txn,ClBal,Remarks,Date,Time,TxnType)
	    values('$userid','$oldBal','$sum','$newBal','Add Commision For $fdate to $ldate','$date','$time','Commission_Redeemed')";
	    if(mysqli_query($con,$insertq))
	    {
	        $updatebal="update distributer set Balance='$newBal' where Userid='$userid'";
		    if(mysqli_query($con,$updatebal))
		    {
		        $respMsg="SUCCESS";
		    }
		    else
		    {
		        $respMsg="FAILED";
		    }
	    }
	    else
	    {
	        $respMsg="FAILED";
	    }
	}
	else
	{
	    $respMsg="FAILED";
	}
	header('location:redeem_commission.php?respMsg='.$respMsg);
	
    ob_end_flush();
?>