<?php
include("include/config.inc.php");
if(!isset($_SESSION['s_activId']))
{
  $_SESSION['s_urlRedirectDir'] = $_SERVER['REQUEST_URI'];
  header("Location:checkLogin.php");
}
else
{
	$pendingArray = array();
	 
	$selectParty = "SELECT * FROM party 
	                   WHERE partyType = 'C'
					  ORDER BY partyName";
	$selectPartyRes = mysql_query($selectParty);
	while($row = mysql_fetch_array($selectPartyRes))
	{
	  $pendingArray[$row['partyId']]['partyId']   	= $row['partyId'];
	  $pendingArray[$row['partyId']]['is_open']   	= $row['is_open'];
	  $pendingArray[$row['partyId']]['partyName'] 	= $row['partyName'];
	  $pendingArray[$row['partyId']]['kg'] 		  	= 0;
	  $pendingArray[$row['partyId']]['totalAmt']  	= 0;
	  $pendingArray[$row['partyId']]['openingAmt']  = 0;
	  $pendingArray[$row['partyId']]['openingFine']	= 0;
	  
	   $slectIssue = "SELECT SUM(kg) AS ckg , SUM(totalAmt) AS ctotalAmt 
	                   FROM client
	                WHERE  cliTransType = 'J'
					AND partyId = ".$row['partyId']."
					GROUP BY clientId";
	  $slectIssueRes = mysql_query($slectIssue);
	  while($irow = mysql_fetch_array($slectIssueRes))
	  {
	    $pendingArray[$row['partyId']]['kg']             -= $irow['ckg'];
	    $pendingArray[$row['partyId']]['totalAmt']       -= $irow['ctotalAmt'];
	  }

	  $slectIssue = "SELECT SUM(kg) AS jkg , SUM(totalAmt) AS jtotalAmt 
	                     FROM client
					WHERE  cliTransType = 'A'
					AND partyId = ".$row['partyId']."
					GROUP BY clientId";
	  $slectIssueResi = mysql_query($slectIssue);
	  while($irow = mysql_fetch_array($slectIssueResi))
	  {
	    $pendingArray[$row['partyId']]['kg']           += $irow['jkg'];
		$pendingArray[$row['partyId']]['totalAmt']     += $irow['jtotalAmt'];
	  }
	  
	  $kg        += $pendingArray[$row['partyId']]['kg'];
	  $totalAmt  += $pendingArray[$row['partyId']]['totalAmt'];
	}
	
	if($_REQUEST['submit'])
	{
	     
		for($i=0; $i< count($_POST['partyId']); $i++)
		{
		  $finalAmt   = isset($_POST['finalAmt'][$i]) ? $_POST['finalAmt'][$i] : 0;
		  $kgrs       = isset($_POST['kgrs'][$i]) ? $_POST['kgrs'][$i] : 0;
		  $partyId    = isset($_POST['partyId'][$i]) ? $_POST['partyId'][$i] : 0; 
		  
		  $insertProcess = "UPDATE party
								 SET kgrs    ='".$kgrs."',
								 finalAmt    = '".$finalAmt."'
							WHERE partyId = ".$partyId;
		  $insertProcessRes = mysql_query($insertProcess);
		   
		  if(!$insertProcessRes)
		  {
			echo "Party Update Fail";
		  }
		  else
		  {
			header("Location:summaryNew.php");
		  }
		}
		 
	}
}
include("./bottom.php");
$smarty->assign("totalAmt",$totalAmt);
$smarty->assign("kg",$kg);
$smarty->assign("pendingArray",$pendingArray);
$smarty->display("summary.tpl");
?>