<?php

/* $Revision: 1.20 $ */

$PageSecurity = 9; /*viewing possible with inquiries but not mods */

$UpdateSecurity =10;

include('includes/session.inc');
$title = _('Stock Cost Update');
include('includes/header.inc');
include('includes/SQL_CommonFunctions.inc');

if (isset($_GET['StockID'])){
	$StockID = trim(strtoupper($_GET['StockID']));
} elseif (isset($_POST['StockID'])){
	$StockID =trim(strtoupper($_POST['StockID']));
}

echo "<a href='" . $rootpath . '/SelectProduct.php?' . SID . "'>" . _('Back to Items') . '</a><br>';

if(isset($_POST['submitvalue']))
{
	$overheadid=$_REQUEST['id'];
 	$StockID=$_REQUEST['StockID'];
	$overheadvalue=$_REQUEST['overheadvalue'];
	
	$sql="select * from overheadvalue where stockid='$StockID'";
	$oh_rs = DB_query($sql,$db,$ErrMsg);
	if(!$oh_rs)
	{
		$sql="INSERT into overheadvalue (stockid,overheadid,overheaddesc,overheadamt) values";
		$i=0;
		foreach($overheadid as $v)
		{
			$sql.="('$StockID','$v','','$overheadvalue[$i]'),";
			$i++;
		}
		$sql=substr($sql,0,-1); 
		$result = DB_query($sql,$db,$ErrMsg);
	}
	else
	{
		
		$result = DB_query("delete from overheadvalue where stockid='$StockID'",$db,$ErrMsg);
		
		$sql="INSERT into overheadvalue (stockid,overheadid,overheaddesc,overheadamt) values";
		$i=0;
		foreach($overheadid as $v)
		{
			$sql.="('$StockID','$v','','$overheadvalue[$i]'),";
			$i++;
		}
		$sql=substr($sql,0,-1); 
		$result = DB_query($sql,$db,$ErrMsg);
	}
}
if (isset($_POST['UpdateData'])){


    $sql = "SELECT  materialcost,
                    labourcost,
                    overheadcost,
                    mbflag,
                    sum(quantity) as totalqoh
                FROM stockmaster INNER JOIN locstock
                    ON stockmaster.stockid=locstock.stockid
                WHERE stockmaster.stockid='".$StockID."'
                GROUP BY description,
                    units,
                    lastcost,
                    actualcost,
                    materialcost,
                    labourcost,
                    overheadcost,
                    mbflag";
    $ErrMsg = _('The entered item code does not exist');
    $oldresult = DB_query($sql,$db,$ErrMsg);
    $oldrow = DB_fetch_array($oldresult);
    $_POST['QOH'] = $oldrow['totalqoh'];
    $_POST['OldMaterialCost'] = $oldrow['materialcost'];
    if ($oldrow['mbflag']=='M') {
        $_POST['OldLabourCost'] = $oldrow['labourcost'];
        $_POST['OldOverheadCost'] = $oldrow['overheadcost'];
    } else {
        $_POST['OldLabourCost'] = 0;
        $_POST['OldOverheadCost'] = 0;
        $_POST['LabourCost'] = 0;
        $_POST['OverheadCost'] = 0;
    }
    DB_free_result($oldresult);

 	//$OldCost =$_POST['OldMaterialCost'] + $_POST['OldLabourCost'] + $_POST['OldOverheadCost'];
   	$NewCost =$_POST['MaterialCost'] + $_POST['LabourCost'] + $_POST['OverheadCost'];

	$result = DB_query("SELECT * FROM stockmaster WHERE stockid='$StockID'",$db);
	$myrow = DB_fetch_row($result);
	if (DB_num_rows($result)==0) {
		prnMsg (_('The entered item code does not exist'),'error',_('Non-existent Item'));
	} elseif ($OldCost != $NewCost){

	$Result = DB_Txn_Begin($db);
	ItemCostUpdateGL($db, $StockID, $NewCost, $OldCost, $_POST['QOH']);


		 $SQL = "UPDATE stockmaster SET
					materialcost=" . $_POST['MaterialCost'] . ",
					labourcost=" . $_POST['LabourCost'] . ",
					overheadcost=" . $_POST['OverheadCost'] . ",
					lastcost=" . $NewCost . "
			WHERE stockid='" . $StockID . "'";

		$ErrMsg = _('The cost details for the stock item could not be updated because');
		$DbgMsg = _('The SQL that failed was');
		$Result = DB_query($SQL,$db,$ErrMsg,$DbgMsg,true);

		$Result = DB_Txn_Commit($db);
		UpdateCost($db, $StockID); //Update any affected BOMs

   	}
}

$ErrMsg = _('The cost details for the stock item could not be retrieved because');
$DbgMsg = _('The SQL that failed was');

//23july2010
$sql = "SELECT bom.parent,
			bom.component,
			stockmaster.description,
			stockmaster.decimalplaces,
			stockmaster.materialcost+ stockmaster.labourcost+stockmaster.overheadcost as standardcost,
			bom.quantity,
			bom.quantity * (stockmaster.materialcost+ stockmaster.labourcost+ stockmaster.overheadcost) AS componentcost
		FROM bom INNER JOIN stockmaster ON bom.component = stockmaster.stockid
		WHERE bom.parent = '" . $StockID . "'
		AND bom.effectiveafter < Now()
		AND bom.effectiveto > Now()";

	$ErrMsg = _('The bill of material could not be retrieved because');
	$BOMResult = DB_query ($sql,$db,$ErrMsg);
	$myrowbom=DB_fetch_array($BOMResult);
	$totalcost=$myrowbom['componentcost'];
	
//
$result = DB_query("SELECT description,
								units,
								lastcost,
								actualcost,
								materialcost,
								labourcost,
								overheadcost,
								mbflag,
								stocktype,
								sum(quantity) as totalqoh
							FROM stockmaster INNER JOIN locstock
								ON stockmaster.stockid=locstock.stockid
								INNER JOIN stockcategory
								ON stockmaster.categoryid = stockcategory.categoryid
							WHERE stockmaster.stockid='" . $StockID . "'
							GROUP BY description,
								units,
								lastcost,
								actualcost,
								materialcost,
								labourcost,
								overheadcost,
								mbflag,
								stocktype",
							$db,$ErrMsg,$DbgMsg);


$myrow = DB_fetch_array($result);
echo "<br><div class='centre'><font color=BLUE size=3><b>" . $StockID . " - " . $myrow['description'] . '</b> - ' . _('Total Quantity On Hand') . ': ' . $myrow['totalqoh'] . " " . $myrow['units'] ."</font>";

echo "<form action='" . $_SERVER['PHP_SELF'] . "?". SID ."' method=post>";
echo _('Item Code') . ":<input type=text name='StockID' value='$StockID' 1 maxlength=20>";

echo " <input type=submit name='Show' VALUE='" . _('Show Cost Details') . "'></div><hr>";

if (($myrow['mbflag']=='D' AND $myrow['stocktype'] != 'L')
	OR $myrow['mbflag']=='A'
	OR $myrow['mbflag']=='K'){
    echo '</form>'; // Close the form
   if ($myrow['mbflag']=='D'){
        echo "<br>$StockID " . _('is a service item');
   } else if ($myrow['mbflag']=='A'){
        echo "<br>$StockID " . _('is an assembly part');
   } else if ($myrow['mbflag']=='K'){
        echo "<br>$StockID " . _('is a kit set part');
   }
   prnMsg(_('Cost information cannot be modified for kits assemblies or service items') . '. ' . _('Please select a different part'),'warn');
   include('includes/footer.inc');
   exit;
}

echo '<input type=hidden name=OldMaterialCost VALUE=' . $myrow['materialcost'] .'>';
echo '<input type=hidden name=OldLabourCost VALUE=' . $myrow['labourcost'] .'>';
echo '<input type=hidden name=OldOverheadCost VALUE=' . $myrow['overheadcost'] .">";
echo '<input type=hidden name=QOH VALUE=' . $myrow['totalqoh'] .'>';

echo '<table cellpadding=2 BORDER=2>';
echo '<tr><td>' . _('Last Cost') .':</td><td class=number>' . number_format($myrowbom['componentcost'],2) . '</td></tr>';
if (! in_array($UpdateSecurity,$_SESSION['AllowedPageSecurityTokens']) OR !isset($UpdateSecurity)){
	echo '<tr><td>' . _('Cost') . ':</td><td class=number>' . number_format($myrow['materialcost']+$myrow['labourcost']+$myrow['overheadcost'],2) . '</td></tr></table>';
} else {

	if ($myrow['mbflag']=='M'){
		echo '<input type=hidden name="MaterialCost" VALUE=' . $myrow['materialcost'] . '>';
		echo '<tr><td>' . _('Standard Material Cost Per Unit') .':</td><td class=number>' . number_format($myrow['materialcost'],4) . '</td></tr>';
		echo '<tr><td>' . _('Standard Labour Cost Per Unit') . ':</td><td><input type=TEXT class="number" name=LabourCost VALUE=' . $myrow['labourcost'] . '></td></tr>';
		echo '<tr><td>' . _('Standard Overhead Cost Per Unit') . ':</td><td><input type=TEXT class="number" name=OverheadCost VALUE=' . $myrow['overheadcost'] . '></td></tr>';
	} elseif ($myrow['mbflag']=='B' OR  $myrow['mbflag']=='D') {
		echo '<tr><td>' . _('Standard Cost') .':</td><td><input type=TEXT class="number" name="MaterialCost" VALUE=' . $myrow['materialcost'] . '></td></tr>';
	} else 	{
		echo '<input type=hidden name=LabourCost VALUE=0>';
		echo '<input type=hidden name=OverheadCost VALUE=0>';
	}
    echo "</table><div class='centre'><input type=submit name='UpdateData' VALUE='" . _('Update') . "'><hr>";
}

if ($myrow['mbflag']=='M'){
echo '<table border=0 cellpadding=5 width=35% align=center>
<tr><td width=90px></td>
<td><a href="#" onclick="show()";><b>' . _('Upadte Overhead Cost') .'</b></a></td>
</tr></table>';
	//$SQL1 = "SELECT * FROM overheadcost";
	
	$SQL1 = "SELECT overheadcost.*,overheadvalue.* FROM overheadcost 
		left join overheadvalue on overheadvalue.overheadid=overheadcost.overhead_id 
		where overheadvalue.stockid='$StockID'";

	$ErrMsg =  _('The line items of the order cannot be retrieved because');
	$DbgMsg =  _('The SQL used to retrieve the line items, that failed was');
	$Result1 = db_query($SQL1,$db, $ErrMsg, $DbgMsg);
  if (db_num_rows($Result1)>0) 
	{
		      echo'<form method="post"  name="upadtevalue" action=" '. $_SERVER['PHP_SELF'] . '?' .'" >';
				echo '<input type="Hidden" name="StockID" value="'.$StockID.'">';
			echo'<table cellpadding=2 colspan=9 border=1 id="showtable"  style="display:none">';
			echo'<tr>
			<th>' . _('Code No') . '</th>
			<th>' . _('Description') . '</th>
			<th>' . _('value') . '</th>
			
			</tr>';
			$k=0;
			while ($myrow1=db_fetch_array($Result1)) 
			{
			
			if ($k==1){
			echo '<tr class="EvenTableRows">';
			$k=0;
			} else {
			echo '<tr class="OddTableRows">';
			$k=1;
			}
			
			
			echo 	'<td>' . $myrow1['overhead_code'] . '</td>
			<td>' . $myrow1['overhead_description'] .'</td>';
		
			echo '<td><input type="text" name="overheadvalue[]" value="'.$myrow1['overheadamt'].'" /><input type="hidden" name="id[]" value="'.$myrow1['overhead_id'].'"></td>
			</tr>';
			}
			echo '<tr><td colspan="3"><div align="right"><input tabindex=20 type="Submit" name="submitvalue" value="' . _('Add Value') . '"></div></td></tr>';
			echo '</table>';
			echo'</form>';
			}  

echo '<br>';
}
if ($myrow['mbflag']!='D'){
	echo "<a href='$rootpath/StockStatus.php?" . SID . "&StockID=$StockID'>" . _('Show Stock Status') . '</a>';
	echo "<br><a href='$rootpath/StockMovements.php?" . SID . "&StockID=$StockID'>" . _('Show Stock Movements') . '</a>';
	echo "<br><a href='$rootpath/StockUsage.php?" . SID . "&StockID=$StockID'>" . _('Show Stock Usage')  .'</a>';
	echo "<br><a href='$rootpath/SelectSalesOrder.php?" . SID . "&SelectedStockItem=$StockID'>" . _('Search Outstanding Sales Orders') . '</a>';
	echo "<br><a href='$rootpath/SelectCompletedOrder.php?" . SID . "&SelectedStockItem=$StockID'>" . _('Search Completed Sales Orders') . '</a>';
}
echo '</form></div>';
?>
<script language="javascript">
function show()
{
document.getElementById("showtable").style.display='';
}
</script>
<?php
include('includes/footer.inc');
?>