<?php
/* $Id: index.php 6941 2014-10-26 23:18:08Z daintree $*/
error_reporting(E_ALL & ~E_NOTICE);
$PageSecurity=0;

include('includes/session.inc');
$Title=_('ERP Home');
include('includes/newheader.php');

?>

		
  					
	<script src="angular/angular.min.js"></script>  
        
 
     
     
		

   
  
 									
									<?php
//this is where you paste. Below paste it:

echo '<p class="page_title_text"><img src="'.$RootPath.'/css/'.$Theme.'/images/magnifier.png" title="' . _('Search') . '" alt="" />
     ' . ' ' . $Title . '</p>';

if (isset($_GET['NewShipment']) AND $_GET['NewShipment']=='Yes'){
	unset($_SESSION['Shipment']->LineItems);
	unset($_SESSION['Shipment']);
}

if (!isset($_GET['SelectedShipment'])){

	echo '<br />';
	prnMsg( _('This page is expected to be called with the shipment number to show the costing for'), 'error');
	include ('includes/footer.inc');
	exit;
}

$ShipmentHeaderSQL = "SELECT shipments.supplierid,
							suppliers.suppname,
							shipments.eta,
							suppliers.currcode,
							shipments.vessel,
							shipments.voyageref,
							shipments.closed
						FROM shipments INNER JOIN suppliers
							ON shipments.supplierid = suppliers.supplierid
						WHERE shipments.shiptref = '" . $_GET['SelectedShipment'] . "'";

$ErrMsg = _('Shipment').' '. $_GET['SelectedShipment'] . ' ' . _('cannot be retrieved because a database error occurred');
$GetShiptHdrResult = DB_query($ShipmentHeaderSQL, $ErrMsg);
if (DB_num_rows($GetShiptHdrResult)==0) {
	echo '<br />';
	prnMsg( _('Shipment') . ' ' . $_GET['SelectedShipment'] . ' ' . _('could not be located in the database') , 'error');
	include ('includes/footer.inc');
	exit;
}

$HeaderData = DB_fetch_array($GetShiptHdrResult);
echo '<br />
	<table class="selection">
	<tr>
		<th colspan="4"><h3>' . _('Shipment Details') . '</h3></th>
	</tr>
	<tr>
		<td><b>' .  _('Shipment') .': </b></td>
		<td><b>' . $_GET['SelectedShipment'] . '</b></td>
		<td><b>' .  _('From').' ' . $HeaderData['suppname'] . '</b></td>
	</tr>
	<tr>
		<td>' . _('Vessel'). ': </td>
		<td>' . $HeaderData['vessel'] . '</td>
		<td>' .  _('Voyage Ref'). ': </td>
		<td>' . $HeaderData['voyageref'] . '</td>
	</tr>
	<tr>
		<td>' . _('Expected Arrival Date (ETA)') . ': </td>
		<td>' . ConvertSQLDate($HeaderData['eta']) . '</td>
	</tr>
	</table>';

/*Get the total non-stock item shipment charges */

$sql = "SELECT SUM(value)
		FROM shipmentcharges
		WHERE stockid=''
		AND shiptref ='" . $_GET['SelectedShipment']. "'";

$ErrMsg = _('Shipment') . ' ' . $_GET['SelectedShipment'] . ' ' . _('general costs cannot be retrieved from the database');
$GetShiptCostsResult = DB_query($sql, $ErrMsg);
if (DB_num_rows($GetShiptCostsResult)==0) {
	echo '<br />';
	prnMsg (_('No General Cost Records exist for Shipment') . ' ' . $_GET['SelectedShipment'] . ' ' . _('in the database'), 'error');
	include ('includes/footer.inc');
	exit;
}

$myrow = DB_fetch_row($GetShiptCostsResult);

$TotalCostsToApportion = $myrow[0];

/*Now Get the total of stock items invoiced against the shipment */

$sql = "SELECT SUM(value)
		FROM shipmentcharges
		WHERE stockid<>''
		AND shiptref ='" . $_GET['SelectedShipment'] . "'";

$ErrMsg = _('Shipment') . ' ' . $_GET['SelectedShipment'] . ' ' . _('Item costs cannot be retrieved from the database');
$GetShiptCostsResult = DB_query($sql);
if (DB_error_no() !=0 OR DB_num_rows($GetShiptCostsResult)==0) {
	echo '<br />';
	prnMsg ( _('No Item Cost Records exist for Shipment') . ' ' . $_GET['SelectedShipment'] . ' ' . _('in the database'), 'error');
	include ('includes/footer.inc');
	exit;
}

$myrow = DB_fetch_row($GetShiptCostsResult);

$TotalInvoiceValueOfShipment = $myrow[0];

/*Now get the lines on the shipment */

$LineItemsSQL = "SELECT purchorderdetails.itemcode,
						purchorderdetails.itemdescription,
						SUM(purchorderdetails.qtyinvoiced) as totqtyinvoiced,
						SUM(purchorderdetails.quantityrecd) as totqtyrecd
						FROM purchorderdetails
					WHERE purchorderdetails.shiptref='" . $_GET['SelectedShipment'] . "'
					GROUP BY purchorderdetails.itemcode,
						  purchorderdetails.itemdescription";

$ErrMsg = _('The lines on the shipment could not be retrieved from the database');
$LineItemsResult = DB_query($LineItemsSQL, $ErrMsg);

if (DB_num_rows($LineItemsResult) > 0) {

	if (isset($_POST['Close'])){
		while ($myrow=DB_fetch_array($LineItemsResult)){
		  if ($myrow['totqtyinvoiced'] < $myrow['totqtyrecd']){
			 prnMsg(_('Cannot close a shipment where the quantity received is more than the quantity invoiced. Check the item') . ' ' . $myrow['itemcode'] . ' - ' . $myrow['itemdescription'],'warn');
			 unset($_POST['Close']);
		  }
		}
		DB_data_seek($LineItemsResult,0);
 	}


	if (isset($_POST['Close'])){
	/*Set up a transaction to buffer all updates or none */
		$result = DB_Txn_Begin();
		$PeriodNo = GetPeriod(Date($_SESSION['DefaultDateFormat']), $db);
	}

	echo '<br /><table cellpadding="2" class="selection">';
	echo '<tr>
			<th colspan="9"><h3>' . _('Items on shipment'). '</h3></th></tr>';

	$TableHeader = '<tr>
						<th>' .  _('Item'). '</th>
						<th>' .  _('Quantity'). '<br />' .  _('Invoiced'). '</th>
						<th>' .  _('Quantity'). '<br />' .  _('Received'). '</th>
						<th>' .  _('Invoiced'). '<br />' .  _('Charges'). '</th>
						<th>' .  _('Shipment'). '<br />' .  _('Charges'). '</th>
						<th>' .  _('Shipment'). '<br />' .  _('Cost'). '</th>
						<th>' .  _('Standard'). '<br />' .  _('Cost'). '</th>
						<th>' .  _('Variance'). '</th>
						<th>%</th>
					</tr>';
	echo  $TableHeader;

	/*show the line items on the shipment with the value invoiced and shipt cost */

	$k=0; //row colour counter
		$TotalShiptVariance = 0;
	$RowCounter =0;

	while ($myrow=DB_fetch_array($LineItemsResult)) {

		if ($k==1){
			echo '<tr class="EvenTableRows">';
			$k=0;
		} else {
			echo '<tr class="OddTableRows">';
			$k=1;
		}

				$sql = "SELECT SUM(shipmentcharges.value) AS invoicedcharges
						 FROM shipmentcharges
						 WHERE shipmentcharges.stockid ='" . $myrow['itemcode'] . "'
						 AND shipmentcharges.shiptref='" . $_GET['SelectedShipment'] . "'";
				$ItemChargesResult = DB_query($sql);
				$ItemChargesRow = DB_fetch_row($ItemChargesResult);
				$ItemCharges = $ItemChargesRow[0];

		if ($TotalInvoiceValueOfShipment>0){
			$PortionOfCharges = $TotalCostsToApportion *($ItemCharges/$TotalInvoiceValueOfShipment);
		} else {
			$PortionOfCharges = 0;
		}

		if ($myrow['totqtyinvoiced']>0){
			$ItemShipmentCost = ($ItemCharges+$PortionOfCharges)/$myrow['totqtyrecd'];
		} else {
			$ItemShipmentCost =0;
		}
		$sql = "SELECT SUM(grns.stdcostunit*grns.qtyrecd) AS costrecd
				   FROM grns INNER JOIN purchorderdetails
				   ON grns.podetailitem=purchorderdetails.podetailitem
			 		WHERE purchorderdetails.shiptref='" . $_GET['SelectedShipment'] . "'
			 		AND purchorderdetails.itemcode = '" . $myrow['itemcode'] . "'";

		$StdCostResult = DB_query($sql);
		$StdCostRow = DB_fetch_row($StdCostResult);
		$CostRecd = $StdCostRow[0];
		if ($myrow['totqtyrecd']==0) {
			$StdCostUnit = 0;
		} else {
			$StdCostUnit = $StdCostRow[0]/$myrow['totqtyrecd'];
		}

		if ($ItemShipmentCost !=0){
			$Variance = $StdCostUnit - $ItemShipmentCost;
		} else {
			$Variance =0;
		}

		$TotalShiptVariance += ($Variance *$myrow['totqtyinvoiced']);

		if ($StdCostUnit>0 ){
			$VariancePercentage = locale_number_format(($Variance*100)/$StdCostUnit,1);
		} else {
			$VariancePercentage =100;
		}


		if ( isset($_POST['Close']) AND $Variance !=0){


			if ($_SESSION['CompanyRecord']['gllink_stock']==1){
				  $StockGLCodes = GetStockGLCode($myrow['itemcode'],$db);
			}

			/*GL journals depend on the costing method used currently:
				 Standard cost - the price variance between the exisitng system cost and the shipment cost is taken as a variance
				 to the price varaince account
				 Weighted Average Cost - the price variance is taken to the stock account and the cost updated to ensure the GL
				 stock account ties up to the stock valuation
			*/

			if ($_SESSION['WeightedAverageCosting'] == 1){   /* Do the WAvg journal and cost update */
				   	/*
					First off figure out the new weighted average cost Need the following data:

					How many in stock now
				The quantity being costed here - $myrow['qtyinvoiced']
				The cost of these items - $ItemShipmentCost
				*/

				$sql ="SELECT SUM(quantity) FROM locstock WHERE stockid='" . $myrow['itemcode'] . "'";
				$ErrMsg =  _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The quantity on hand could not be retrieved from the database');
				$DbgMsg = _('The following SQL to retrieve the total stock quantity was used');
				$Result = DB_query($sql, $ErrMsg, $DbgMsg);
				$QtyRow = DB_fetch_row($Result);
				$TotalQuantityOnHand = $QtyRow[0];


				/*The cost adjustment is the price variance / the total quantity in stock
				But that's only provided that the total quantity in stock is > the quantity charged on this invoice
								*/

				$WriteOffToVariances =0;

				if ($myrow['totqtyinvoiced'] > $TotalQuantityOnHand){

							 /*So we need to write off some of the variance to variances and
							 only the balance of the quantity in stock to go to stock value */

					 $WriteOffToVariances =  ($myrow['totqtyinvoiced'] - $TotalQuantityOnHand) * ($ItemShipmentCost - $StdCostUnit);
				 }


				if ($_SESSION['CompanyRecord']['gllink_stock']==1){

				   /* If the quantity on hand is less the amount charged on this invoice then some must have been sold
					and the price variance on these must be written off to price variances*/


					if ($myrow['totqtyinvoiced'] > $TotalQuantityOnHand){

						$sql = "INSERT INTO gltrans (type,
											typeno,
											trandate,
											periodno,
											account,
											narrative,
											amount)
				  					VALUES (31,
				   					'" . $_GET['SelectedShipment'] . "',
									'" . Date('Y-m-d') . "',
									'" . $PeriodNo . "',
							 		'" . $StockGLCodes['purchpricevaract'] . "',
								 	'" . $myrow['itemcode'] . ' ' . _('shipment cost') . ' ' .  locale_number_format($ItemShipmentCost,$_SESSION['CompanyRecord']['deicmalplaces']) . _('shipment quantity > stock held - variance write off') . "',
									 " . $WriteOffToVariances . ")";

						$ErrMsg =  _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The GL entry for the shipment variance posting for'). ' ' . $myrow['itemcode'] . ' '. _('could not be inserted into the database because');
			   			$result = DB_query($sql, $ErrMsg,'',TRUE);

					}
				/*Now post any remaining price variance to stock rather than price variances */
					$sql = "INSERT INTO gltrans (type,
											typeno,
											trandate,
											periodno,
											account,
											narrative,
											amount)
											VALUES (31,
							   					'" . $_GET['SelectedShipment'] . "',
												'" . Date('Y-m-d') . "',
												'" . $PeriodNo . "',
										 		'" . $StockGLCodes['stockact'] . "',
											 	'" . $myrow['itemcode'] . ' ' . _('shipment avg cost adjt') . "',
												'" . ($myrow['totqtyinvoiced'] *($ItemShipmentCost - $StdCostUnit)- $WriteOffToVariances) . "')";

					$ErrMsg =  _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The GL entry for the shipment average cost adjustment for'). ' ' . $myrow['itemcode'] . ' '. _('could not be inserted into the database because');
					$result = DB_query($sql, $ErrMsg,'',TRUE);

				} /* end of average cost GL stuff */


				/*Now to update the stock cost with the new weighted average */

				/*Need to consider what to do if the cost has been changed manually between receiving
				the stock and entering the invoice - this code assumes there has been no cost updates
				made manually and all the price variance is posted to stock.

				A nicety or important?? */

				$ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The cost could not be updated because');
				$DbgMsg = _('The following SQL to update the cost was used');

				if ($TotalQuantityOnHand>0) {

					$CostIncrement = ($myrow['totqtyinvoiced'] *($ItemShipmentCost - $StdCostUnit) - $WriteOffToVariances) / $TotalQuantityOnHand;

					$sql = "UPDATE stockmaster
								SET lastcost=materialcost+overheadcost+labourcost,
									materialcost=materialcost+" . $CostIncrement . ",
									lastcostupdate='" . Date('Y-m-d') . "'
							WHERE stockid='" . $myrow['itemcode'] . "'";

					$Result = DB_query($sql, $ErrMsg, $DbgMsg,'',TRUE);

				} else {
					$sql = "UPDATE stockmaster
								SET lastcost=materialcost+overheadcost+labourcost,
									materialcost='" . $ItemShipmentCost . "',
									lastcostupdate='" . Date('Y-m-d') . "'
								WHERE stockid='" . $myrow['itemcode'] . "'";

					$Result = DB_query($sql, $ErrMsg, $DbgMsg,'',TRUE);

				}
				/* End of Weighted Average Costing Code */


			} else { /*We must be using standard costing do the journals for standard costing then */

				 if ($_SESSION['CompanyRecord']['gllink_stock']==1){
					$sql = "INSERT INTO gltrans (type,
												typeno,
												trandate,
												periodno,
												account,
												narrative,
												amount)
									VALUES (31,
										'" . $_GET['SelectedShipment'] . "',
										'" . Date('Y-m-d') . "',
										'" . $PeriodNo . "',
										'" . $StockGLCodes['purchpricevaract'] . "',
										'" . $myrow['itemcode'] . ' ' . _('shipment cost') . ' ' .  locale_number_format($ItemShipmentCost,$_SESSION['CompanyRecord']['decimalplaces']) . ' x ' . _('Qty recd') .' ' . $myrow['totqtyrecd'] . "',
										" . -$Variance * $myrow['totqtyrecd'] . ")";

					$ErrMsg =  _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The Positive GL entry for the shipment variance posting for'). ' ' . $myrow['itemcode'] . ' '. _('could not be inserted into the database because');
		   			$result = DB_query($sql, $ErrMsg,'',TRUE);
				 }
			} /* end of the costing specific updates */


			if ($_SESSION['CompanyRecord']['gllink_stock']==1){
						/*we always need to reverse entries relating to the GRN suspense during delivery and entry of shipment charges */
				  $sql = "INSERT INTO gltrans (type,
										typeno,
										trandate,
										periodno,
										account,
										narrative,
										amount)
							VALUES (31,
								'" . $_GET['SelectedShipment'] . "',
								'" . Date('Y-m-d') . "',
								'" . $PeriodNo . "',
								'" . $_SESSION['CompanyRecord']['grnact'] . "',
								'" . $myrow['itemcode'] . ' ' ._('shipment cost') . ' ' .  locale_number_format($ItemShipmentCost,$_SESSION['CompanyRecord']['decimalplaces']) . ' x ' . _('Qty invoiced') . ' ' . $myrow['totqtyinvoiced'] . "',
								" . ($Variance * $myrow['totqtyinvoiced']) . ")";

				  $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The credit GL entry for the shipment variance posting for') . ' ' . $myrow['itemcode'] . ' ' . _('could not be inserted because');

				  $result = DB_query($sql, $ErrMsg,'',TRUE);
						 }

				if ( isset($_POST['UpdateCost']) AND $_POST['UpdateCost'] == 'Yes' ){ /*Only ever a standard costing option
												  Weighted average costing implies cost updates taking place automatically */

					$QOHResult = DB_query("SELECT SUM(quantity)
											FROM locstock
											WHERE stockid ='" . $myrow['itemcode'] . "'");
					$QOHRow = DB_fetch_row($QOHResult);
					$QOH=$QOHRow[0];

					if ($_SESSION['CompanyRecord']['gllink_stock']==1){
						$CostUpdateNo = GetNextTransNo(35, $db);
						$PeriodNo = GetPeriod(Date('d/m/Y'), $db);

						$ValueOfChange = $QOH * ($ItemShipmentCost - $StdCostUnit);

						$SQL = "INSERT INTO gltrans (type,
												typeno,
												trandate,
												periodno,
												account,
												narrative,
												amount)
										VALUES (35,
											'" . $CostUpdateNo . "',
											'" . Date('Y-m-d') . "',
											'" . $PeriodNo . "',
											'" . $StockGLCodes['adjglact'] . "',
											'" . _('Shipment of') . ' ' . $myrow['itemcode'] . " " . _('cost was') . ' ' . $StdCostUnit . ' ' . _('changed to') . ' ' . locale_number_format($ItemShipmentCost,$_SESSION['CompanyRecord']['decimalplaces']) . ' x ' . _('QOH of') . ' ' . $QOH . "',
											" . -$ValueOfChange . ")";

						   $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The GL credit for the shipment stock cost adjustment posting could not be inserted because'). ' ' . DB_error_msg();

						   $Result = DB_query($SQL, $ErrMsg,'',TRUE);

						   $SQL = "INSERT INTO gltrans (type,
										typeno,
										trandate,
										periodno,
										account,
										narrative,
										amount)
								VALUES (35,
									'" . $CostUpdateNo . "',
									'" . Date('Y-m-d') . "',
									'" . $PeriodNo . "',
									'" . $StockGLCodes['stockact'] . "',
									'" . _('Shipment of') . ' ' . $myrow['itemcode'] .  ' ' . _('cost was') . ' ' . $StdCostUnit . ' ' . _('changed to') . ' ' . locale_number_format($ItemShipmentCost,$_SESSION['CompanyRecord']['decimalplaces']) . ' x ' . _('QOH of') . ' ' . $QOH . "',
									" . $ValueOfChange . ")";

						   $ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The GL debit for stock cost adjustment posting could not be inserted because') .' '. DB_error_msg();

						   $Result = DB_query($SQL, $ErrMsg,'',TRUE);

					} /*end of GL entries for a standard cost update */

					/* Only the material cost is important for imported items */
					$sql = "UPDATE stockmaster SET materialcost=" . $ItemShipmentCost . ",
												labourcost=0,
												overheadcost=0,
												lastcost='" . $StdCostUnit . "',
												lastcostupdate='" . Date('Y-m-d') . "'
										WHERE stockid='" . $myrow['itemcode'] . "'";

					$ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The shipment cost details for the stock item could not be updated because'). ': ' . DB_error_msg();

					$result = DB_query($sql, $ErrMsg,'',TRUE);

				} // end of update cost code
		} // end of Close shipment item updates


/*  Item / Qty Inv/  FX price/ Local Val/ Portion of chgs/ Shipt Cost/ Std Cost/ Variance/ Var % */

	echo '<td>' . $myrow['itemcode'] . ' - ' . $myrow['itemdescription'] . '</td>
			<td class="number">' . locale_number_format($myrow['totqtyinvoiced'],'Variable') . '</td>
			<td class="number">' . locale_number_format($myrow['totqtyrecd'],'Variable') . '</td>
			<td class="number">' . locale_number_format($ItemCharges,$_SESSION['CompanyRecord']['decimalplaces']) . '</td>
			<td class="number">' . locale_number_format($PortionOfCharges,$_SESSION['CompanyRecord']['decimalplaces']) . '</td>
			<td class="number">' . locale_number_format($ItemShipmentCost,$_SESSION['CompanyRecord']['decimalplaces']) . '</td>
			<td class="number">' . locale_number_format($StdCostUnit,$_SESSION['CompanyRecord']['decimalplaces']) . '</td>
			<td class="number">' . locale_number_format($Variance,$_SESSION['CompanyRecord']['decimalplaces']) . '</td>
			<td class="number">' . $VariancePercentage . '%</td></tr>';
	}
}
echo '<tr>
		<td colspan="3" class="number"><b>' .  _('Total Shipment Charges'). '</b></td>
		<td class="number">' . locale_number_format($TotalInvoiceValueOfShipment,$_SESSION['CompanyRecord']['decimalplaces']) . '</td>
		<td class="number">' . locale_number_format($TotalCostsToApportion,$_SESSION['CompanyRecord']['decimalplaces'])  . '</td>
	</tr>';

echo '<tr>
		<td colspan="6" class="number">' . _('Total Value of all variances on this shipment') . '</td>
		<td class="number">' . locale_number_format($TotalShiptVariance,$_SESSION['CompanyRecord']['decimalplaces']) . '</td>
	</tr>';

echo '</table>';


echo '<br />
	<table width="95%">
	<tr>
		<td valign="top">'; // put this shipment charges side by side in a table (major table 2 cols)

$sql = "SELECT suppliers.suppname,
			supptrans.suppreference,
			systypes.typename,
			supptrans.trandate,
			supptrans.rate,
			suppliers.currcode,
			shipmentcharges.stockid,
			shipmentcharges.value,
			supptrans.transno,
			supptrans.supplierno
		FROM supptrans INNER JOIN shipmentcharges
			ON shipmentcharges.transtype=supptrans.type
			AND shipmentcharges.transno=supptrans.transno
		INNER JOIN suppliers
			ON suppliers.supplierid=supptrans.supplierno
		INNER JOIN systypes ON systypes.typeid=supptrans.type
		WHERE shipmentcharges.stockid<>''
		AND shipmentcharges.shiptref='" . $_GET['SelectedShipment'] . "'
		ORDER BY supptrans.supplierno,
			supptrans.transno,
			shipmentcharges.stockid";

$ChargesResult = DB_query($sql);

echo '<table cellpadding="2" class="selection">';
echo '<tr>
		<th colspan="6"><h3>' . _('Shipment Charges Against Products'). '</h3></th>
	</tr>';

$TableHeader = '<tr>
					<th>' .  _('Supplier'). '</th>
					<th>' .  _('Type'). '</th>
					<th>' .  _('Ref'). '</th>
					<th>' .  _('Date'). '</th>
					<th>' .  _('Item'). '</th>
					<th>' .  _('Local Amount'). '<br />' .  _('Charged'). '</th>
				</tr>';

echo  $TableHeader;

/*show the line items on the shipment with the value invoiced and shipt cost */

$k=0; //row colour counter
$RowCounter =0;
$TotalItemShipmentChgs =0;

while ($myrow=DB_fetch_array($ChargesResult)) {


	if ($k==1){
		echo '<tr class="EvenTableRows">';
		$k=0;
	} else {
		echo '<tr class="OddTableRows">';
		$k=1;
	}

	echo '<td>' . $myrow['suppname'] . '</td>
		<td>' .$myrow['typename'] . '</td>
		<td>' . $myrow['suppreference'] . '</td>
		<td>' . ConvertSQLDate($myrow['trandate']) . '</td>
		<td>' . $myrow['stockid'] . '</td>
		<td class="number">' . locale_number_format($myrow['value'],$_SESSION['CompanyRecord']['decimalplaces']) . '</td>
		</tr>';

	$TotalItemShipmentChgs += $myrow['value'];
}

echo '<tr>
		<td colspan="5" class="number"><b>' .  _('Total Charges Against Shipment Items'). ':</b></td>
		<td class="number">' . locale_number_format($TotalItemShipmentChgs,$_SESSION['CompanyRecord']['decimalplaces']) . '</td>
	</tr>';

echo '</table>';

echo '</td><td valign="top">'; //major table

/* Now the shipment freight/duty etc general charges */

$sql = "SELECT suppliers.suppname,
		supptrans.suppreference,
		systypes.typename,
		supptrans.trandate,
		supptrans.rate,
		suppliers.currcode,
		shipmentcharges.stockid,
		shipmentcharges.value
	FROM supptrans INNER JOIN shipmentcharges
		ON shipmentcharges.transtype=supptrans.type
		AND shipmentcharges.transno=supptrans.transno
	INNER JOIN suppliers
		ON suppliers.supplierid=supptrans.supplierno
	INNER JOIN systypes
		ON systypes.typeid=supptrans.type
	WHERE shipmentcharges.stockid=''
	AND shipmentcharges.shiptref='" . $_GET['SelectedShipment'] . "'
	ORDER BY supptrans.supplierno,
		supptrans.transno";

$ChargesResult = DB_query($sql);

echo '<table cellpadding="2" class="selection">';
echo '<tr>
		<th colspan="6"><h3>' . _('General Shipment Charges') . '</h3></th>
	</tr>';

$TableHeader = '<tr>
					<th>' .  _('Supplier'). '</th>
					<th>' .  _('Type'). '</th>
					<th>' .  _('Ref'). '</th>
					<th>' .  _('Date'). '</th>
					<th>' .  _('Local Amount'). '<br />' .  _('Charged'). '</th>
				</tr>';

echo  $TableHeader;

/*show the line items on the shipment with the value invoiced and shipt cost */

$k=0; //row colour counter
$RowCounter =0;
$TotalGeneralShipmentChgs =0;

while ($myrow=DB_fetch_array($ChargesResult)) {

	if ($k==1){
		echo '<tr class="EvenTableRows">';
		$k=0;
	} else {
		echo '<tr class="OddTableRows">';
		$k=1;
	}

	echo '<td>' . $myrow['suppname'] . '</td>
		<td>' .$myrow['typename'] . '</td>
		<td>' . $myrow['suppreference'] . '</td>
		<td>' . ConvertSQLDate($myrow['trandate']) . '</td>
		<td class="number">' . locale_number_format($myrow['value'],$_SESSION['CompanyRecord']['decimalplaces']) . '</td></tr>';

	$TotalGeneralShipmentChgs += $myrow['value'];

}

echo '<tr>
	<td class="number" colspan="4"><b>' .  _('Total General Shipment Charges'). ':</b></td>
	<td class="number">' . locale_number_format($TotalGeneralShipmentChgs,$_SESSION['CompanyRecord']['decimalplaces']) . '</td></tr>';

echo '</table>';

echo '</td>
	</tr>
	</table>'; //major table close

if ( isset($_GET['Close'])) { /* Only an opportunity to confirm user wishes to close */

// if the page was called with Close=Yes then show options to confirm OK to c
	echo '<div class="centre">
			<form method="post" action="' . htmlspecialchars($_SERVER['PHP_SELF'],ENT_QUOTES,'UTF-8') .'?SelectedShipment=' . $_GET['SelectedShipment'] . '">';
	echo '<input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />';

		if ($_SESSION['WeightedAverageCosting']==0){
		/* We are standard costing - so show the option to update costs - under W. Avg cost updates are implicit */
			echo _('Update Standard Costs') .':<select name="UpdateCost">
					<option selected="selected" value="Yes">' .  _('Yes') . '</option>
					<option value="No">' .  _('No') . '</option>
					</select>';
		}
	echo '<br />
		<br />
		<input type="submit" name="Close" value="'. _('Confirm OK to Close'). '" />
		</form>
		</div>';
}

if ( isset($_POST['Close']) ){ /* OK do the shipment close journals */

/*Inside a transaction need to:
 1 . compare shipment costs against standard x qty received and take the variances off to the GL GRN supsense account and variances - this is done in the display loop

 2. If UpdateCost=='Yes' then do the cost updates and GL entries.

 3. Update the shipment to completed

 1 and 2 done in the display loop above only 3 left*/

/*also need to make sure the purchase order lines that were on this shipment are completed so no more can be received in against the order line */

		$result = DB_query("UPDATE purchorderdetails
								   SET quantityord=quantityrecd,
									   completed=1
							WHERE shiptref = '" . $_GET['SelectedShipment'] ."'",
							_('Could not complete the purchase order lines on this shipment'),
							'',
							TRUE);

	$result = DB_query("UPDATE shipments SET closed=1 WHERE shiptref='" .$_GET['SelectedShipment']. "'",_('Could not update the shipment to closed'),'',TRUE);
	$result = DB_Txn_Commit();

	echo '<br /><br />';
	prnMsg( _('Shipment'). ' ' . $_GET['SelectedShipment'] . ' ' . _('has been closed') );
	if ($_SESSION['CompanyRecord']['gllink_stock']==1) {
		echo '<br />';
		prnMsg ( _('All variances were posted to the general ledger') );
	}
	If (isset($_POST['UpdateCost']) AND $_POST['UpdateCost']=='Yes'){
		echo '<br />';
		prnMsg ( _('All shipment items have had their standard costs updated') );
	}
}





			  
 	echo '</div >';
	?>
						

		
					</div>
				</div>
			</div>
					
					

						<!--end:: Widgets/Stats-->

						<!--Begin::Section-->
						

		<!-- end::Quick Sidebar -->

		<!-- begin::Scroll Top -->
		<div id="m_scroll_top" class="m-scroll-top">
			<i class="la la-arrow-up"></i>
		</div>

		<!-- end::Scroll Top -->

		<!-- begin::Quick Nav -->
		

		<!-- begin::Quick Nav -->
<script src="includes/vendors/owl.carousel/dist/owl.carousel.js" type="text/javascript"></script>

		<!--end::Page Scripts -->
	</body>

	<!-- end::Body -->
</html>
 
      
<?php



/*The module link codes are hard coded in a switch statement below to determine the options to show for each tab */
include('includes/MainMenuLinksArray.php');

if (isset($SupplierLogin) AND $SupplierLogin==1){
	echo '<table class="table_index">
			<tr>
			<td class="menu_group_item">
				<p>&bull; <a href="' . $RootPath . '/SupplierTenders.php?TenderType=1">' . _('View or Amend outstanding offers') . '</a></p>
			</td>
			</tr>
			<tr>
			<td class="menu_group_item">
				<p>&bull; <a href="' . $RootPath . '/SupplierTenders.php?TenderType=2">' . _('Create a new offer') . '</a></p>
			</td>
			</tr>
			<tr>
			<td class="menu_group_item">
				<p>&bull; <a href="' . $RootPath . '/SupplierTenders.php?TenderType=3">' . _('View any open tenders without an offer') . '</a></p>
			</td>
			</tr>
		</table>';
	include('includes/footer.inc');
	exit;
} elseif (isset($CustomerLogin) AND $CustomerLogin==1){
	echo '<table class="table_index">
			<tr>
			<td class="menu_group_item">
				<p>&bull; <a href="' . $RootPath . '/CustomerInquiry.php?CustomerID=' . $_SESSION['CustomerID'] . '">' . _('Account Status') . '</a></p>
			</td>
			</tr>
			<tr>
			<td class="menu_group_item">
				<p>&bull; <a href="' . $RootPath . '/SelectOrderItems.php?NewOrder=Yes">' . _('Place An Order') . '</a></p>
			</td>
			</tr>
			<tr>
			<td class="menu_group_item">
				<p>&bull; <a href="' . $RootPath . '/SelectCompletedOrder.php?SelectedCustomer=' . $_SESSION['CustomerID'] . '">' . _('Order Status') . '</a></p>
			</td>
			</tr>
		</table>';

	include('includes/footer.inc');
	exit;
}

if (isset($_GET['Application'])){ /*This is sent by this page (to itself) when the user clicks on a tab */
	$_SESSION['Module'] = $_GET['Application'];
}








//include('includes/footer.inc');

function GetRptLinks($GroupID) {
/*
This function retrieves the reports given a certain group id as defined in /reports/admin/defaults.php
in the acssociative array $ReportGroups[]. It will fetch the reports belonging solely to the group
specified to create a list of links for insertion into a table to choose a report. Two table sections will
be generated, one for standard reports and the other for custom reports.
*/
	global $db, $RootPath, $ReportList;
	require_once('reportwriter/languages/en_US/reports.php');
	require_once('reportwriter/admin/defaults.php');
	$GroupID=$ReportList[$GroupID];
	$Title= array(_('Custom Reports'), _('Standard Reports and Forms'));

	$sql= "SELECT id,
				reporttype,
				defaultreport,
				groupname,
				reportname
			FROM reports
			ORDER BY groupname,
					reportname";
	$Result=DB_query($sql,'','',false,true);
	$ReportList = '';
	while ($Temp = DB_fetch_array($Result)) $ReportList[] = $Temp;

	$RptLinks = '';
	for ($Def=1; $Def>=0; $Def--) {
        $RptLinks .= '<li class="menu_group_headers">';
        $RptLinks .= '<b>' .  $Title[$Def] . '</b>';
        $RptLinks .= '</li>';
		$NoEntries = true;
		if ($ReportList) { // then there are reports to show, show by grouping
			foreach ($ReportList as $Report) {
				if ($Report['groupname']==$GroupID AND $Report['defaultreport']==$Def) {
                    $RptLinks .= '<li class="menu_group_item">';
					$RptLinks .= '<p>&bull; <a href="' . $RootPath . '/reportwriter/ReportMaker.php?action=go&amp;reportid=' . $Report['id'] . '">' . _($Report['reportname']) . '</a></p>';
					$RptLinks .= '</li>';
					$NoEntries = false;
				}
			}
			// now fetch the form groups that are a part of this group (List after reports)
			$NoForms = true;
			foreach ($ReportList as $Report) {
				$Group=explode(':',$Report['groupname']); // break into main group and form group array
				if ($NoForms AND $Group[0]==$GroupID AND $Report['reporttype']=='frm' AND $Report['defaultreport']==$Def) {
                    $RptLinks .= '<li class="menu_group_item">';
					$RptLinks .= '<img src="' . $RootPath . '/css/' . $_SESSION['Theme'] . '/images/folders.gif" width="16" height="13" alt="" />&nbsp;';
					$RptLinks .= '<p>&bull; <a href="' . $RootPath . '/reportwriter/FormMaker.php?id=' . $Report['groupname'] . '"></p>';
					$RptLinks .= $FormGroups[$Report['groupname']] . '</a>';
					$RptLinks .= '</li>';
					$NoForms = false;
					$NoEntries = false;
				}
			}
		}
		if ($NoEntries) $RptLinks .= '<li class="menu_group_item">' . _('There are no reports to show!') . '</li>';
	}
	return $RptLinks;
}
	
?>
<!-- Modal HTML embedded directly into document -->
<div id="ex1" class="modal">
  <p>Thanks for clicking. That felt good.</p>
  <a href="#" rel="modal:close">Close</a>
</div>


<!-- Modal -->
 <div class="modal fade" id="getCodeModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
   <div class="modal-dialog modal-lg">
      <div class="modal-content">
       <div class="modal-header">
         <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
         <h4 class="modal-title" id="myModalLabel"> API CODE </h4>
       </div>
       <div class="modal-body" id="getCode" style="overflow-x: scroll;">
       
          
          
       </div>
    </div>
   </div>
 </div>
<script>
jQuery(document).ready(function($){

   // event must be delegated from .xcrud
	
	//check employee for a clash on existing patrol location
$(".xcrud").on("change","#internal",function(){ // !important, delegation from static container
     var internal = $("#internal").val();
	 
	
        if(internal != 0)
       {
		
		 $('#sectors').attr("disabled", true);
		
            $('#patrollocation').attr("disabled",true);
		  $('#account').attr("disabled", true);
		   
		//   $("#account").hide();
       }
	else{
		 $('#sectors').attr("disabled", false);
		
            $('#patrollocation').attr("disabled",false);
		  $('#account').attr("disabled", false)
		//$("#account").show();
	}
     
	  
   });
	
	//check employee for a clash on same employee working at different location but at same time-frame
	//monday shift one and two	
	$(".xcrud").on("change","#monout",function(){ // !important, delegation from static container
     var start_time = $("#monin").val();
	 var end_time = $("#monout").val();
	 var rosterid = $("#rosterid").val();
		 var employeeid = $("#employeeid").val();
		
	
	
		
	
		
	   $.ajax({
      url:'hrms/CheckEmployee-timeclash.php',
      method:"POST",
      data:{start_time:start_time,end_time:end_time,rosterid:rosterid,employeeid:employeeid},
		 
		
      success:function(data)
     {
		 	
	   var data = JSON.parse(data);
	    console.log(data);
        if(data != 0)
       {
		  
		   
       alert('CLASH!This employee is already rostered in another location/post at these selected times. Please choose another employee before proceeding. Full Details where they are rostered at :ROSTERID:'+ data);
		    
       }
      }
     })  
	  
   });

	//monday calculations
 
	



	
	
	//tuesdayshift one and two	
	$(".xcrud").on("change","#tuesout",function(){ // !important, delegation from static container
     var start_time = $("#tuesin").val();
	 var end_time = $("#tuesout").val();
	 var rosterid = $("#rosterid").val();
		 var employeeid = $("#employeeid").val();
		
	   $.ajax({
      url:'hrms/CheckEmployee-timeclashtues.php',
      method:"POST",
      data:{start_time:start_time,end_time:end_time,rosterid:rosterid,employeeid:employeeid},
		 
		
      success:function(data)
     {
		 	
	   var data = JSON.parse(data);
	    console.log(data);
        if(data != 0)
       {
		  
		   
       alert('CLASH!This employee is already rostered in another location/post at these selected times. Please choose another employee before proceeding. Full Details where they are rostered at :ROSTERID:'+ data);
		    
       }
      }
     })  
	  
   });
	
	//wed shift one and two	
	$(".xcrud").on("change","#wedout",function(){ // !important, delegation from static container
     var start_time = $("#wedin").val();
	 var end_time = $("#wedout").val();
	 var rosterid = $("#rosterid").val();
		 var employeeid = $("#employeeid").val();
		if ( end_time <= start_time){
		   
		   alert('Time logged out has to be greater than Time logged in ');
	   }
		
	   $.ajax({
      url:'hrms/CheckEmployee-timeclashwed.php',
      method:"POST",
      data:{start_time:start_time,end_time:end_time,rosterid:rosterid,employeeid:employeeid},
		 
		
      success:function(data)
     {
		 	
	   var data = JSON.parse(data);
	    console.log(data);
        if(data != 0)
       {
		  
		   
       alert('CLASH!This employee is already rostered in another location/post at these selected times. Please choose another employee before proceeding. Full Details where they are rostered at :ROSTERID:'+ data);
		    
       }
      }
     })  
	  
   });
	
	
	//thursday shift one and two	
	$(".xcrud").on("change","#thursout",function(){ // !important, delegation from static container
     var start_time = $("#thursin").val();
	 var end_time = $("#thursout").val();
	 var rosterid = $("#rosterid").val();
		 var employeeid = $("#employeeid").val();
		if ( end_time <= start_time){
		   
		   alert('Time logged out has to be greater than Time logged in ');
	   }
		
	   $.ajax({
      url:'hrms/CheckEmployee-timeclashthurs.php',
      method:"POST",
      data:{start_time:start_time,end_time:end_time,rosterid:rosterid,employeeid:employeeid},
		 
		
      success:function(data)
     {
		 	
	   var data = JSON.parse(data);
	    console.log(data);
        if(data != 0)
       {
		  
		   
       alert('CLASH!This employee is already rostered in another location/post at these selected times. Please choose another employee before proceeding. Full Details where they are rostered at :ROSTERID:'+ data);
		    
       }
      }
     })  
	  
   });
	
	//friday shift one and two	
	$(".xcrud").on("change","#friout",function(){ // !important, delegation from static container
     var start_time = $("#friin").val();
	 var end_time = $("#friout").val();
	 var rosterid = $("#rosterid").val();
		 var employeeid = $("#employeeid").val();
		if ( end_time <= start_time){
		   
		   alert('Time logged out has to be greater than Time logged in ');
	   }
		
	   $.ajax({
      url:'hrms/CheckEmployee-timeclashfri.php',
      method:"POST",
      data:{start_time:start_time,end_time:end_time,rosterid:rosterid,employeeid:employeeid},
		 
		
      success:function(data)
     {
		 	
	   var data = JSON.parse(data);
	    console.log(data);
        if(data != 0)
       {
		  
		   
       alert('CLASH!This employee is already rostered in another location/post at these selected times. Please choose another employee before proceeding. Full Details where they are rostered at :ROSTERID:'+ data);
		    
       }
      }
     })  
	  
   });
	
	//saturday shift one and two	
	$(".xcrud").on("change","#satout",function(){ // !important, delegation from static container
     var start_time = $("#satin").val();
	 var end_time = $("#satout").val();
	 var rosterid = $("#rosterid").val();
		 var employeeid = $("#employeeid").val();
		if ( end_time <= start_time){
		   
		   alert('Time logged out has to be greater than Time logged in ');
	   }
		
	   $.ajax({
      url:'hrms/CheckEmployee-timeclashsat.php',
      method:"POST",
      data:{start_time:start_time,end_time:end_time,rosterid:rosterid,employeeid:employeeid},
		 
		
      success:function(data)
     {
		 	
	   var data = JSON.parse(data);
	    console.log(data);
        if(data != 0)
       {
		  
		   
       alert('CLASH!This employee is already rostered in another location/post at these selected times. Please choose another employee before proceeding. Full Details where they are rostered at :ROSTERID:'+ data);
		    
       }
      }
     })  
	  
   });
	
	//sundayshift one and two	
	$(".xcrud").on("change","#sunout",function(){ // !important, delegation from static container
     var start_time = $("#sunin").val();
	 var end_time = $("#sunout").val();
	 var rosterid = $("#rosterid").val();
		 var employeeid = $("#employeeid").val();
		if ( end_time <= start_time){
		   
		   alert('Time logged out has to be greater than Time logged in ');
	   }
		
	   $.ajax({
      url:'hrms/CheckEmployee-timeclashsun.php',
      method:"POST",
      data:{start_time:start_time,end_time:end_time,rosterid:rosterid,employeeid:employeeid},
		 
		
      success:function(data)
     {
		 	
	   var data = JSON.parse(data);
	    console.log(data);
        if(data != 0)
       {
		  
		   
       alert('CLASH!This employee is already rostered in another location/post at these selected times. Please choose another employee before proceeding. Full Details where they are rostered at :ROSTERID:'+ data);
		    
       }
      }
     })  
	  
   });
	
	

	
	
	
   }); 
	
	

	
	
		
		

	
	
</script>


<script type="text/javascript">
jQuery(document).on("ready xcrudafterrequest",function(){
    
});
</script>