<?php
error_reporting(0);
$PageSecurity = 15;
$title = _('Stock Main Categorty');
if (isset($_POST['SelectedType']))
{
	$SelectedType = strtoupper($_POST['SelectedType']);
} 
elseif (isset($_GET['SelectedType']))
{
	$SelectedType = strtoupper($_GET['SelectedType']);
}

if (isset($Errors)) 
{
	unset($Errors);
}
$Errors = array();
if (isset($_POST['submit']))
{
	//initialise no input errors assumed initially before we test
	$InputError = 0;
	/* actions to take once the user has clicked the submit button
	ie the page has called itself with some user input */
	//first off validate inputs sensible
	$i=1;
	if ($_POST['stockmaincategoryid']=='' OR $_POST['stockmaincategoryid']==' ' OR $_POST['stockmaincategoryid']==''){
		$InputError = 1;
		prnMsg('<br>' . _('The Stock Main Categorty code cannot be an empty string or spaces'),'error');
		$Errors[$i] = 'Stock Main Categorty';
		$i++;
	}elseif ($_POST['stockmaincategoryid']=='AN'){
		$InputError = 1;
		prnMsg (_('The Stock Main Categorty cannot be AN since this is a system defined abbreviation for any Stock Main Category in general ledger interface lookups'),'error');
		$Errors[$i] = 'Stock Main Categorty';
		$i++;
	}

	if (isset($SelectedType) AND $InputError !=1)
	 {
	 if($_REQUEST['sequence']!="")
		{
		$sqlPoApp=DB_query("SELECT * FROM stockmaincategory where sequence='".$_POST['sequence']."'",$db);
	//	if(DB_num_rows($sqlPoApp)==0){
		$sql = "UPDATE stockmaincategory
			SET stockmaincategoryid =  '" . $_POST['stockmaincategoryid'] . "', stockmaincategoryname = '" . $_POST['stockmaincategoryname'] . "', sequence = '" . $_POST['sequence'] . "'
			WHERE id = '$SelectedType'";

//	$msg = _('The Stock Main Category Successfully Edit') . ' ' . $SelectedType . ' ' .  _('has been updated');
	// Edit By 
	$msg = ('The Stock Main Category Successfully updated') ;
	//}
			//else
			//{
			// $msg = ('Duplicate Sequence No. is Avoided');
			//}
		}
		else
		{
		$sql = "UPDATE stockmaincategory
			SET stockmaincategoryid =  '" . $_POST['stockmaincategoryid'] . "', stockmaincategoryname = '" . $_POST['stockmaincategoryname'] . "', sequence = '" . $_POST['sequence'] . "'
			WHERE id = '$SelectedType'";

//	$msg = _('The Stock Main Category Successfully Edit') . ' ' . $SelectedType . ' ' .  _('has been updated');
	// Edit By 
	$msg = ('The Stock Main Category Successfully Edit') ;
		}
	
	}
	 elseif ( $InputError !=1 ) 
	{

		// First check the type is not being duplicated

	 $checkSql = "SELECT count(*)
			     FROM stockmaincategory
			     WHERE stockmaincategoryid = '" . $_POST['stockmaincategoryid'] . "' and CompanyId='".$_SESSION['ACGCompanyId']."'";
				 

		$checkresult = DB_query($checkSql,$db);
		$checkrow = DB_fetch_row($checkresult);

		if ( $checkrow[0] > 0 ) 
		{
			$InputError = 1;
			prnMsg( _('The Stock Main Category Successfully Edit') . $_POST['stockmaincategoryid'] . _(' already exist.'),'error');
		} else {

			// Add new record on submit
		$sqlPoApp=DB_query("SELECT * FROM stockmaincategory where sequence='".$_POST['sequence']."'",$db);
		if(DB_num_rows($sqlPoApp)==0){
		 $sql = "INSERT INTO stockmaincategory
						(stockmaincategoryid,
			 			 stockmaincategoryname,CompanyId,sequence)
				VALUES ('" . str_replace(' ', '', $_POST['stockmaincategoryid']) . "',
					'" . $_POST['stockmaincategoryname'] . "','".$_SESSION['ACGCompanyId']."','".$_POST['sequence']."')";
					
            
			    $msg = ('Stock Main Category Successfully Added');
			}
			else
			{
			 $msg = ('Duplicate Sequence No. is Avoided');
			}
			//edit By vikas $msg = _('Stock Main Category') . ' ' . $_POST["stockmaincategoryname"] .  ' ' . _('has been created');
		$checkSql = "SELECT count(stockmaincategoryid)
			     FROM stockmaincategory where CompanyId='".$_SESSION['ACGCompanyId']."'";
			   
			$result = DB_query($checkSql, $db);
		    $row = DB_fetch_row($result);
	 	
		}
	}

	if ( $InputError !=1) 
	{
	//run the SQL from either of the above possibilites
		$result = DB_query($sql,$db);


	// Fetch the default price list.
		$sql = "SELECT confvalue
					FROM config
					WHERE confname='DefaultPriceList'";
		$result = DB_query($sql,$db);
		$PriceListRow = DB_fetch_row($result);
		$DefaultPriceList = $PriceListRow[0];

	// Does it exist
		$checkSql = "SELECT count(*)
			     FROM stockmaincategory
			     WHERE stockmaincategoryid = '" . $DefaultPriceList . "'";
		$checkresult = DB_query($checkSql,$db);
		$checkrow = DB_fetch_row($checkresult);

	// If it doesnt then update config with newly created one.
		if ($checkrow[0] == 0)
		 {
			$sql = "UPDATE config
					SET confvalue='".$_POST['stockmaincategoryid']."'
					WHERE confname='DefaultPriceList'";
			$result = DB_query($sql,$db);
			$_SESSION['DefaultPriceList'] = $_POST['stockmaincategoryid'];
		}

		prnMsg($msg,'success');

		unset($SelectedType);
		unset($_POST['stockmaincategoryid']);
		unset($_POST['stockmaincategoryname']);
	}
} 

if(isset($_GET['delete'])) 
{
	  $sql= "SELECT COUNT(*)
	       FROM debtortrans
	       WHERE debtortrans.tpe='$SelectedType'"; 

	$ErrMsg = _('The number of transactions using this Stock Main Category could not be retrieved');
	$result = DB_query($sql,$db,$ErrMsg);
	$myrow = DB_fetch_row($result);
	if ($myrow[0]>0)
	 {
		prnMsg(_('Cannot delete this sale type because customer transactions have been created using this sales type') . '<br>' . _('There are') . ' ' . $myrow[0] . ' ' . _('transactions using this sales type code'),'error');

	} else {

		$sql = "SELECT COUNT(*) FROM debtorsmaster WHERE salestype='$SelectedType'";

		$ErrMsg = _('The number of transactions using this Stock record could not be retrieved because');
		$result = DB_query($sql,$db,$ErrMsg);
		$myrow = DB_fetch_row($result);
		if ($myrow[0]>0) {
			prnMsg (_('Cannot delete this sale type because customers are currently set up to use this sales type') . '<br>' . _('There are') . ' ' . $myrow[0] . ' ' . _('customers with this sales type code'));
		} else {

			$sql="DELETE FROM stockmaincategory WHERE id='$SelectedType'";
			$ErrMsg = _('The Stock Maion Category record could not be deleted because');
			$result = DB_query($sql,$db,$ErrMsg);
			prnMsg('Stock Main Category Successfully Deleted');

			//prnMsg(_('Stock Main ') . ' / ' . _('Category') . ' ' . $SelectedType  . ' ' . _('has been deleted') ,'success');

			$sql ="DELETE FROM stockmaincategory WHERE stockmaincategory.stockmaincategoryid='SelectedType'";
			$ErrMsg =  _('The Sales Type prices could not be deleted because');
			$result = DB_query($sql,$db,$ErrMsg);

//edit by v			prnMsg(' ...  ' . _('and any prices for this sales type / price list were also deleted'),'success');
			unset ($SelectedType);
		}
	} 
echo "<script>location.href='index.php?route=stockmaincategory&modid=".$_REQUEST['modid']."&frmid=".$_REQUEST['frmid']."'</script>";	
}
?>

<link rel="stylesheet" href="css/new_mxerp.css">
<div class="body_contain">
<div class="tab_div">
<h1>Stock Main Category</h1>
<form method="post" action="">
<?php
if(!isset($_GET['delete'])) 
{?>
<table width="100%" border="0" cellpadding="3" cellspacing="0">
<tr class="row1">
<?php

	if ( isset($SelectedType) AND $SelectedType!='')
	{

		$sql = "SELECT id, stockmaincategoryid,
			       stockmaincategoryname,sequence
		        FROM stockmaincategory
		        WHERE id='$SelectedType'";

		$result = DB_query($sql, $db);
		$myrow = DB_fetch_array($result);
		$_POST['stockmaincategoryid'] = $myrow['stockmaincategoryid'];
		$_POST['stockmaincategoryname']  = $myrow['stockmaincategoryname'];
		$_POST['sequence']  = $myrow['sequence'];
?>
		<input type="hidden" name="SelectedType" VALUE="<?php echo $SelectedType;?>">
		<input type="hidden" name="stockmaincategoryid" VALUE="<?php echo $_POST['stockmaincategoryid'];?>">

		<td width="13%" align="right"><strong>Type Code:</strong></td>
        <td width="20%"><input type="Text"  style="width:98%;"  name="stockmaincategoryid" readonly value="<?php echo $_POST['stockmaincategoryid'];?>"></td>
	
		<?php 
	} else{ ?>  	
		<td width="13%" align="right"><strong>Main Category Code:</strong></td>
	    <td width="20%"><input type="Text" <?php echo (in_array('Stock ype',$Errors) ? 'class="inputerror"' : '' );?> style="width:98%;" maxlength="5" id="catcode" onkeypress="return onlyAlphabets(event,this)" name="stockmaincategoryid" id="stockmaincategoryid"></td>
		<?php 
		}
	if (!isset($_POST['stockmaincategoryname'])) 
	{
		$_POST['stockmaincategoryname']='';
		$_POST['sequence']='';
	}?>
	<td width="13%" align="right"><strong>Main Category Description:</strong></td>
	<td width="20%"><input type="Text" style="width:98%;" name="stockmaincategoryname" id="stockmaincategoryname" value="<?php echo $_POST['stockmaincategoryname'];?>" maxlength="30"></td>
	<td width="13%" align="right"><strong>Sequence:</strong></td>
	<td><input type="Text" style="width:98%;" name="sequence" id="sequence" value="<?php echo $_POST['sequence']; ?>" maxlength="30"></td>
</tr>
<tr class="row1">
    <td colspan="6" style="text-align:center;"> <?php if(!isset($_REQUEST['SelectedType'])){ ?>
    <input type="submit" name="submit" class="search" VALUE="Accept" onclick="return frmvalidate();">
    <?php } else { ?>
    <input type="submit" name="submit" class="search" VALUE="Update" onclick="return frmvalidate();"> <?php } ?>
    <input type="submit" name="Cancel" class="search" VALUE="Cancel">
</td>
</tr>
</table>
   <?php 
} 
?>
</form>
<?php 
if (!isset($SelectedType))
{
  $sql = "SELECT * FROM stockmaincategory where CompanyId='".$_SESSION['ACGCompanyId']."'";
	$result = DB_query($sql,$db);
	
	
?>
<table width="100%" border="1" cellpadding="3" cellspacing="0" style="border:#808080 1px solid; border-collapse:collapse;">
<tr>
	<th width="14%">Category Code</th>
	<th>Category Description</th>
	<th width="12%">Sequence No.</th>
	<th width="5%" style="text-align:center;">Edit</th>
	<th width="5%" style="text-align:center;">Delete</th>
</tr><?php 
$k=0; //row colour counter
while ($myrow = DB_fetch_row($result)) 
{
$complaint=$s->GetTotalRecordsTalbes('stockcategory',"stockmaincategory='".$myrow['0']."'");
		if($complaint<=0)
		{
		$flag=0;
		}
		else
		{
		$flag=1;
		}
?>
<tr bgcolor="#FFFFFF">
	<td><?php echo $myrow[1];?></td>
	<td><?php echo $myrow[2];?></td>
	<td><?php echo $myrow[4];?></td>
	<td align="center"><a href="index.php?route=stockmaincategory&modid=<?php echo $_REQUEST['modid'];?>&frmid=<?php echo $_REQUEST['frmid'];?>&SelectedType=<?php echo $myrow[0];?>"><img src="images/icon-edit.png" width="15" height="15" title="Edit Document" /></a></td>
	<td align="center">
	<?php if($flag==0) { ?>
	<a href="index.php?route=stockmaincategory&modid=<?php echo $_REQUEST['modid'];?>&frmid=<?php echo $_REQUEST['frmid'];?>&SelectedType=<?php echo $myrow[0];?>&delete=yes" onclick="return confirm('Are you sure you wish to delete this price list and all the prices it may have set up?')"><img src="images/Icon_Delete.png" width="15" height="15" title="Delete Document" /></a>
	<?php } else { ?><img src="images/Icon_Delete.png" width="15" height="15" title="No permission to Delete Document" style="opacity:0.5;" /><?php } ?>
	</td>
</tr>
<?php 	}
?>	
</table>
<?php 
}
?>
<script type="text/javascript" language="javascript">
function frmvalidate()
{
	var chr=document.getElementById("stockmaincategoryid").value;
	if(chr=='')
	{
		alert("You Must Fill the Main Category Code First!");
		return false;
	}
	else
	{
		if(chr.length<2)
		{
			alert("Main Category Code Not Less than 2 Character");
			return false;
		}
		
	}
	
	var chr1=document.getElementById("stockmaincategoryname").value;
	if(chr1=='')
	{
		alert("You Must Fill the Main Category Description First!");
		return false;
	}
	else
	{
		if(chr1.length<5)
		{
			alert("Main Category Description Not Less than 5 Character");
			return false;
		}
		
	}
	
}

function onlyAlphabets(str)
{
   if (window.event) {
        var charCode = window.event.keyCode;
    }
    else if (e) {
        var charCode = e.which;
    }
    else { return true; }
    if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123))
        {
         $('#catcode').keyup(function() {
    $(this).val($(this).val().toUpperCase());
});        return true;
        }
    else
        return false;

     

}
</script>

</div>
</div>