<?php
$PageSecurity = 15;
$title = _('Units Of Measure');
if ( isset($_GET['SelectedMeasureID']) )
	$SelectedMeasureID = $_GET['SelectedMeasureID'];
elseif (isset($_POST['SelectedMeasureID']))
	$SelectedMeasureID = $_POST['SelectedMeasureID'];

if (isset($_POST['submit'])) 
{
	$InputError = 0;
	if (strpos($_POST['MeasureName'],'&')>0 OR strpos($_POST['MeasureName'],"'")>0) {
		$InputError = 1;
		prnMsg( _('The unit of measure cannot contain the character') . " '&' " . _('or the character') ." '",'error');
	}
	if (trim($_POST['MeasureName']) == '') {
		$InputError = 1;
		prnMsg( _('The unit of measure may not be empty'), 'error');
	}

	if ($_POST['SelectedMeasureID']!='' AND $InputError !=1) {

		/*SelectedMeasureID could also exist if submit had not been clicked this code would not run in this case cos submit is false of course  see the delete code below*/
		// Check the name does not clash
		$sql = "SELECT count(*) FROM unitsofmeasure
				WHERE unitid <> " . $SelectedMeasureID ."
				AND unitname ".LIKE." '" . $_POST['MeasureName'] . "'";
		$result = DB_query($sql,$db);
		$myrow = DB_fetch_row($result);
		if ( $myrow[0] > 0 ) {
			$InputError = 1;
			prnMsg( _('The unit of measure can not be renamed because another with the same name already exist.'),'error');
		} else {
			// Get the old name and check that the record still exist neet to be very carefull here
			// idealy this is one of those sets that should be in a stored procedure simce even the checks are
			// relavant
			$sql = "SELECT unitname FROM unitsofmeasure
				WHERE unitid = " . $SelectedMeasureID;
			$result = DB_query($sql,$db);
			if ( DB_num_rows($result) != 0 ) {
				// This is probably the safest way there is
				$myrow = DB_fetch_row($result);
				$OldMeasureName = $myrow[0];
				$sql = array();
				$sql[] = "UPDATE unitsofmeasure
					SET unitname='" . $_POST['MeasureName'] . "'
					WHERE unitname ".LIKE." '".$OldMeasureName."'";
				$sql[] = "UPDATE stockmaster
					SET units='" . $_POST['MeasureName'] . "'
					WHERE units ".LIKE." '" . $OldMeasureName . "'";
				$sql[] = "UPDATE contracts
					SET units='" . $_POST['MeasureName'] . "'
					WHERE units ".LIKE." '" . $OldMeasureName . "'";
			} else {
				$InputError = 1;
				prnMsg( _('The unit of measure no longer exist.'),'error');
			}
		}
		$msg = _('Unit of measure changed');
	} elseif ($InputError !=1) {
		/*SelectedMeasureID is null cos no item selected on first time round so must be adding a record*/
		$sql = "SELECT count(*) FROM unitsofmeasure
				WHERE unitname " .LIKE. " '".$_POST['MeasureName'] ."'";
		$result = DB_query($sql,$db);
		$myrow = DB_fetch_row($result);
		if ( $myrow[0] > 0 ) {
			$InputError = 1;
			prnMsg( _('The unit of measure can not be created because another with the same name already exists.'),'error');
		} else {
			$sql = "INSERT INTO unitsofmeasure (
						unitname )
				VALUES (
					'" . $_POST['MeasureName'] ."'
					)";
		}
		$msg = _('New unit of measure added');
	}

	if ($InputError!=1){
		//run the SQL from either of the above possibilites
		if (is_array($sql)) {
			$result = DB_Txn_Begin($db);
			$tmpErr = _('Could not update unit of measure');
			$tmpDbg = _('The sql that failed was') . ':';
			foreach ($sql as $stmt ) {
				$result = DB_query($stmt,$db, $tmpErr,$tmpDbg,true);
				if(!$result) {
					$InputError = 1;
					break;
				}
			}
			if ($InputError!=1){
				$result = DB_Txn_Commit($db);
			} else {
				$result = DB_Txn_Rollback($db);
			}
		} else {
			$result = DB_query($sql,$db);
		}
		prnMsg($msg,'success');
	}
	unset ($SelectedMeasureID);
	unset ($_POST['SelectedMeasureID']);
	unset ($_POST['MeasureName']);
	echo "<script>location.href='index.php?route=Setup/maintenance/UnitsOfMeasure&modid=".$_REQUEST['modid']."&frmid=".$_REQUEST['frmid']."'</script>";
} 
if (isset($_GET['delete'])) 
{
	$sql = "SELECT unitname FROM unitsofmeasure
		WHERE unitid = " . $SelectedMeasureID;
	$result = DB_query($sql,$db);
	if ( DB_num_rows($result) == 0 ) {
		// This is probably the safest way there is
		prnMsg( _('Cannot delete this unit of measure because it no longer exist'),'warn');
	} else {
		$myrow = DB_fetch_row($result);
		$OldMeasureName = $myrow[0];
		$sql= "SELECT COUNT(*) FROM stockmaster WHERE units ".LIKE." '" . $OldMeasureName . "'";
		$result = DB_query($sql,$db);
		$myrow = DB_fetch_row($result);
		if ($myrow[0]>0) {
			prnMsg( _('Cannot delete this unit of measure because inventory items have been created using this unit of measure'),'warn');
			echo '<br>' . _('There are') . ' ' . $myrow[0] . ' ' . _('inventory items that refer to this unit of measure') . '</font>';
		} else {
			$sql= "SELECT COUNT(*) FROM contracts WHERE units ".LIKE." '" . $OldMeasureName . "'";
			$result = DB_query($sql,$db);
			$myrow = DB_fetch_row($result);
			if ($myrow[0]>0) {
				prnMsg( _('Cannot delete this unit of measure because contracts have been created using this unit of measure'),'warn');
				echo '<br>' . _('There are') . ' ' . $myrow[0] . ' ' . _('contracts that refer to this unit of measure') . '</font>';
			} else {
				$sql="DELETE FROM unitsofmeasure WHERE unitname ".LIKE."'" . $OldMeasureName . "'";
				$result = DB_query($sql,$db);
				prnMsg( $OldMeasureName . ' ' . _('unit of measure has been deleted') . '!','success');
			}
		}

	} 
	echo "<script>location.href='index.php?route=Setup/maintenance/UnitsOfMeasure&modid=".$_REQUEST['modid']."&frmid=".$_REQUEST['frmid']."'</script>";
	unset ($SelectedMeasureID);
	unset ($_GET['SelectedMeasureID']);
	unset($_GET['delete']);
	unset ($_POST['SelectedMeasureID']);
	unset ($_POST['MeasureID']);
	unset ($_POST['MeasureName']);}
if (!isset($_GET['delete'])) 
{
?>
	<form method="post" action="">
<?php
	if (isset($SelectedMeasureID)) {
		//editing an existing section

		$sql = "SELECT unitid,
				unitname
				FROM unitsofmeasure
				WHERE unitid=" . $SelectedMeasureID;

		$result = DB_query($sql, $db);
		if ( DB_num_rows($result) == 0 ) {
			prnMsg( _('Could not retrieve the requested unit of measure, please try again.'),'warn');
			unset($SelectedMeasureID);
		} else {
			$myrow = DB_fetch_array($result);

			$_POST['MeasureID'] = $myrow['unitid'];
			$_POST['MeasureName']  = $myrow['unitname'];
?>
			<input type=hidden name="SelectedMeasureID" VALUE="<?php echo $_POST['MeasureID'];?>">
			<?php
		}

	}  else {
		$_POST['MeasureName']='';
	}?>
	<table>
	<tr>
		<td><strong>UNIT OF MEASUREMENT</strong></td>
		<td><input type="Text" name="MeasureName" size="30" maxlength="30" value="<?php echo $_POST['MeasureName'];?>"></td>
	  </tr>
	  </table>
	  <br />
		<div class="centre"><input type="Submit" name="submit" value="Save"></div>
</form>
		<?php }
if (!isset($SelectedMeasureID)) 
{
	$sql = "SELECT unitid,
			unitname
			FROM unitsofmeasure
			ORDER BY unitid";

	$ErrMsg = _('Could not get unit of measures because');
	$result = DB_query($sql,$db,$ErrMsg);
?> 
	<table border="0" cellpadding="2" cellspacing="2" class="inborder" style="background:#dce6f2; margin-top:20px;">
		<tr>
		<th><strong>UNIT OF MEASUREMENT </strong></th>
		<th colspan='2'><strong>Action</strong></th>
		</tr><?php

	$k=0; //row colour counter
	while ($myrow = DB_fetch_row($result)) {
?>
	<tr bgcolor="#FFFFFF">
	<td><?php echo $myrow[1];?></td>
	<td><a href="index.php?route=Setup/maintenance/UnitsOfMeasure&amp;modid=<?php echo $_REQUEST['modid'];?>&amp;frmid=<?php echo $_REQUEST['frmid'];?>&amp;SelectedMeasureID=<?php echo $myrow[0];?>">Edit</a></td>
	<td><a href="index.php?route=Setup/maintenanceUnitsOfMeasure&amp;modid=<?php echo $_REQUEST['modid'];?>&amp;frmid=<?php echo $_REQUEST['frmid'];?>&amp;SelectedMeasureID=<?php echo $myrow[0];?>&amp;delete=1" onclick="return confirm('This unit will be deleted. Are you sure?')">Delete</a></td>
</tr>
<?php	} ?>
</table>
	<?php }
include('includes/footer.inc');
?>