<?php
include("include/config.inc.php");
if(!isset($_SESSION['s_activId']))
{
  $_SESSION['s_urlRedirectDir'] = $_SERVER['REQUEST_URI'];
  header("Location:checkLogin.php");
}
else
{
	$partyId = isset($_REQUEST['partyId']) ? $_REQUEST['partyId'] : 0;
	$cDate   = date('Y-m-d');

    if(isset($_REQUEST['partyId']))
	{
	   
	  $selectJavakAmount = "SELECT SUM(kg) AS jKg,SUM(totalAmt) AS jtotalAmt
	                   FROM client
					  WHERE cliTransType = 'J'
				AND partyId = ".$partyId;
	  $selectJavakAmountRes = mysql_query($selectJavakAmount);
	  if($jrow = mysql_fetch_assoc($selectJavakAmountRes))
	  {
	    $jKg          = $jrow['jKg'];
	    $jtotalAmt    = $jrow['jtotalAmt'];  
	  }
	  
	  
	   $selectOpen = "SELECT SUM(openingFine) AS openingFine,SUM(openingAmt) AS openingAmt
	                   FROM client
					  WHERE partyId = ".$partyId;
	  $sselectOpenRes = mysql_query($selectOpen);
	  if($oprow = mysql_fetch_assoc($sselectOpenRes))
	  {
	   echo $openingFine   = $oprow['openingFine'];
	    $openingAmt        = $oprow['openingAmt'];  
	  }
	  
	  $selectAavkAmount = "SELECT SUM(kg) AS aKg,SUM(totalAmt) AS atotalAmt
	                   FROM client
					  WHERE cliTransType = 'A'
				AND partyId = ".$partyId;
	  $selectAavkAmountRes = mysql_query($selectAavkAmount);
	  if($arow = mysql_fetch_assoc($selectAavkAmountRes))
	  {
  	    $aKg          = $arow['aKg'];
	    $atotalAmt    = $arow['atotalAmt'];  
	  }
	if($aKg > 0)
	{
	
	 $finalKg     = $aKg - $jKg + $openingFine;
	  
	}
	else
	{
	  $finalKg     = $jKg - $aKg + $openingFine	;
	}
	
	$finalAmount = $atotalAmt - $jtotalAmt + $openingAmt;
	
	$insertData = "INSERT INTO client(partyId,cDate,openingFine,openingAmt) 
	               VALUES(".$partyId.",'".$cDate."',".$finalKg.",".$finalAmount.")";
	$res = mysql_query($insertData);
	if($res)
	{
	   $selectMAx = "SELECT MAX(clientId) AS clientId
	                     FROM client
	                WHERE partyId = ".$partyId;
	  $selectMAxRes = mysql_query($selectMAx);
	  if($row = mysql_fetch_array($selectMAxRes))
	  {
	    $clientId = $row['clientId'];
	  }
	  
       $delete = "delete FROM client
	                WHERE partyId = ".$partyId."
					AND clientId < ".$clientId;
	   $res52 = mysql_query($delete);
	   if(!$res52)
	   {
	     echo "Delete fail";
	   }
	   else
	   {
	     header("Location:clientList.php");
	   }
	}
  }	
}
?>