<?php 
$sqltot = "SELECT id FROM `item_master` order by id desc limit 1";
$resulttot = DB_query($sqltot,$db);
$rowstot = DB_fetch_array($resulttot);
$last=$rowstot['id'];

if($_REQUEST['actionType'] =='addNew')
{
	$sql = "SELECT price_code FROM `pms_price_list` order by id desc limit 1";
	$result = DB_query($sql ,$db);
	$rows = DB_fetch_array($result);
	$price_code = $rows['price_code']; 
	if($price_code != '')
	{
		$code_val1 = substr($price_code, 0,2);
		$code_val2 = substr($price_code, -3);
		$increment = $code_val2 + 1;
		$price_code = $code_val1.str_pad($increment,3,"0",STR_PAD_LEFT);
	}
	else
	{
		$price_code = 'PC001';
	}
	
	$data['price_code'] = $price_code;
	$data['price_list_type'] = $_REQUEST['price_list_type'];
	$data['from_date'] = FormatDateForSQL($_REQUEST['from_date']);
	$data['to_date'] = FormatDateForSQL($_REQUEST['to_date']);
	$data['price_for'] = $_REQUEST['price_for'];
	$data['particular'] = $_REQUEST['particular'];
	$data['create_date'] = FormatDateForSQL($_REQUEST['create_date']);
	$data['CompanyID'] = $_SESSION['ACGCompanyId'];	
	$data['details'] = $_REQUEST['details'];
	$rowinsert = $s->RecordInsert('pms_price_list', $data);
	$priceid = DB_Last_Insert_ID($db,'pms_price_list','id');
	$count = $_REQUEST['activity_id'];
	$itemdata = array();
	for($i = 0; $i<count($count); $i++){
	if($_REQUEST['mrp_rate'][$i]!=''){
		$itemdata[]=array('price_list_id' => $priceid,
						  'activity_id' => $_REQUEST['activity_id'][$i],
						  'mrp_rate'=> $_REQUEST['mrp_rate'][$i]
						  );
	}
	}
	//echo "<pre>";
	//print_r($itemdata);
	//exit;
	if(count($itemdata)>0){
		$value = array();
		foreach( $itemdata as $DATA)
		{
			$value[] = " ('".$priceid."','".$DATA['activity_id']."','".$DATA['mrp_rate']."')";
		}
		$str = implode(",",$value);
		$insert_item_query = "INSERT INTO pms_price_list_items(price_list_id,activity_id,mrp_rate) VALUES $str";
		$result = DB_query($insert_item_query,$db);
	}
	$s->pageLocation("index.php?route=PMS/Maintenance/price_list".$rurl);
}

if($_REQUEST['ID'] !='')
{
	$pricequery = "SELECT * FROM pms_price_list where id='".$_REQUEST['ID']."'";
	$result = DB_query($pricequery,$db);
	$pricerow = DB_fetch_array($result);
	$price_code = $pricerow['price_code'];
}

if($_REQUEST['ID'] !='' and $_REQUEST['actionType'] == "Update"){

	$condition = "id='".$_REQUEST['ID']."'";
	$data['price_code'] = $_REQUEST['price_code'];
	$data['price_list_type'] = $_REQUEST['price_list_type'];
	$data['from_date'] = FormatDateForSQL($_REQUEST['from_date']);
	$data['to_date'] = FormatDateForSQL($_REQUEST['to_date']);
	$data['price_for'] = $_REQUEST['price_for'];
	$data['particular'] = $_REQUEST['particular'];
	$data['details'] = $_REQUEST['details'];
	$rowupdate = $s->RecordEdit('pms_price_list', $data, $condition);
	$count = $_REQUEST['activity_id'];
	
		$delCondition = "price_list_id='".$_REQUEST['ID']."'"; 
		$s->DeleteRecord('pms_price_list_items', $delCondition);
		$priceid = $_REQUEST['ID'];
		for($i = 0; $i<count($count); $i++)
		{
		if($_REQUEST['mrp_rate'][$i]!=''){
			$itemdata[]=array('price_list_id' => $priceid,
							  'activity_id' => $_REQUEST['activity_id'][$i],
							  'mrp_rate' => $_REQUEST['mrp_rate'][$i]
							  );
		}
		}
		if(count($itemdata)>0){
			$value = array();
			foreach( $itemdata as $DATA)
			{
				$value[] = " ('".$priceid."','".$DATA['activity_id']."','".$DATA['mrp_rate']."')";
			}
			$str = implode(",",$value);
			$insert_item_query = "INSERT INTO pms_price_list_items(price_list_id,activity_id,mrp_rate) VALUES $str";
			$result = DB_query($insert_item_query,$db);
		}
	
	
	$s->pageLocation("index.php?route=PMS/Maintenance/price_list".$rurl);

}
?>
<style type="text/css">
.body_lightbox {
width:100%;
background-color:#e7e7e7;
position:absolute;
left:280px;
top:95px;
padding-left:5px;
padding-right:5px;
border:#666666 solid 3px;
}
</style>
<h2 align="center"><strong>Standard Price List</strong></h2>
<form name="form1" action="" method="post" onsubmit="return validateForm();">


<table width="100%" align="center" border="1" cellpadding="3" cellspacing="0" style="border-collapse:collapse;">
	<tr>
	<th width="13%"><strong>Price List No.</strong></th>
	<td width="20%">
		<input name="price_code" id="price_code" type="text" readonly="" class="cap" value="<?php if($_REQUEST['ID'] !=''){echo $pricerow['price_code'];}else{echo 'AUTO GENERATED';}?>" style="width:100%;"></td>
	<th width="13%"><strong>Price List Type</strong></th>
	<td width="20%">
		<input type="text" style="width:100%;" name="price_list_type" id="price_list_type" value="<?php if($_REQUEST['ID'] !=''){echo $pricerow['price_list_type'];}?>">
		<!--<select style="width:100%;" name="price_list_type" id="price_list_type" onchange="checkExisting()">
			<option value="">--Select--</option>	
		<?php 
			$type_sql = "SELECT id, name FROM type_master";
			$tresult = DB_query($type_sql,$db);
			while($typerow = DB_fetch_array($tresult)){
		?>
			<option value="<?php echo $typerow['id'];?>" <?php if($typerow['id']==$pricerow['price_list_type']) echo "selected"?>><?php echo $typerow['name'];?></option>
		<?php } ?>
		</select>-->			
	</td>
	<th width="13%"><strong>Valid From Date</strong></th>
	<td width="20%">
		<input name="from_date" id="from_date" type="text" class="datepicker" value="<?php if($pricerow['from_date'] !='') echo date('d/m/Y',strtotime($pricerow['from_date']));?>" style="width:100%;" onchange="checkExisting()">			</td>
	</tr>
	<tr>
	<th><strong>To</strong></th>
	<td width="20%"><input name="to_date" id="to_date" type="text" class="datepicker" value="<?php if($pricerow['to_date'] !='') echo date('d/m/Y',strtotime($pricerow['to_date']));?>" style="width:100%;" onchange="checkExisting()"></td>
	<th><strong>Description</strong></th>
	<td><input name="details" id="details" type="text" class="cap" value="<?php echo $pricerow['details'];?>" style="width:100%;"></td>
	
	
	<th><strong>PL Date</strong></th>
	<td><input type="text" class="cap" name="create_date" id="create_date" value="<?php if($pricerow['create_date'] !='') echo date('d/m/Y',strtotime($pricerow['create_date'])); else echo date('d/m/Y');?>" readonly="" /></td>
	</tr>
	<tr>
		<th><strong>Price For</strong></th>
		<td>
			<select name="price_for" id="price_for">
				<!--<option value="A">All</option>-->
				<option value="C" <?php if($pricerow['price_for']=='C'){echo "selected";}?>>Contractor</option>
				<option value="P" <?php if($pricerow['price_for']=='P'){echo "selected";}?>>Project</option>
			</select>
		</td>
		<th><strong>Particular</strong></th>
	<td>
		<select style="width:150px;"  name="particular" id="particular" onchange="checkExisting()" >
		<option value="0">Select Contractor</option>
		<?php
		$ClientRes=DB_query("SELECT * FROM suppliers where vendor_type = 'Contractor' and CompanyId='".$_SESSION['ACGCompanyId']."'",$db); 
		while($ClientRow=DB_fetch_array($ClientRes))
		{
 		?>
		<option value="<?php echo $ClientRow['id']?>" <?php echo ($pricerow['particular']==$ClientRow['id']?'selected':'');?>><?php echo $ClientRow['vendor_name']?></option>
		<?php  } ?>
 	</select></td>
		<th><strong>&nbsp;</strong></th>
	<td>&nbsp;</td>
	</tr>
</table> 
	
<p>&nbsp;</p>  

<div id="itemdata">
	<table width="100%" border="1" cellpadding="3" cellspacing="0">
	<tr>
		<th><strong>S.R.</strong></th>
		<th><strong>Activity Group</strong></th>
		<th><strong>Activity Code</strong></th>
		<th><strong>Activity Name</strong></th>
		<th><strong>Unit</strong></th>
		<th><strong>Rate</strong></th>
		
	</tr>
	<?php
	$subcat_sql = "SELECT id,categorydescription from stockcategory where CompanyID='".$_SESSION['ACGCompanyId']."'";
	$result = DB_query($subcat_sql ,$db);
	while($subcatrows = DB_fetch_array($result)){
	$item_sql = "SELECT * FROM sub_activity_defination where inventory_group_id='".$subcatrows['id']."'";
	$item_result = DB_query($item_sql,$db);
	if(DB_num_rows($item_result)>0){
?>
	<tr>
		<td colspan="7"><b><?php echo $subcatrows['categorydescription'];?></b></td>
	</tr>
	
<?php 

$nn=1;
while($itemrow = DB_fetch_array($item_result)){
?>
	<tr bgcolor="#FFFFFF">
		<td><?php echo $nn; ?></td>
		<td><?php if($itemrow['group_name']!='')  echo $s->GetFieldValue('sub_activity_group','id="'.$itemrow['group_name'].'"','group_name'); else echo "&nbsp;";?></td>
		<td><input type="hidden" style="width:100%;" name="activity_id[]" id="activity_id" value="<?php if($itemrow['id']!='') { echo $itemrow['id']; }else{ echo '&nbsp;';}?>"><?php if($itemrow['activity_code']!='')  echo $itemrow['activity_code']; else echo "&nbsp;";?></td>
		<td><?php if($itemrow['activity_name']!='')  echo $itemrow['activity_name']; else echo "&nbsp;";?></td>
		<td><?php if($itemrow['unit']!='')  echo $s->GetFieldValue('unitsofmeasure','unitid="'.$itemrow['unit'].'"','unitname'); else echo "&nbsp;";?></td>
		<?php 
		if($_REQUEST['ID']!=''){		
		$price_sql = "SELECT * FROM pms_price_list_items where price_list_id='".$_REQUEST['ID']."' and activity_id='".$itemrow['id']."'";
		$price_result = DB_query($price_sql,$db);
		$pricerow = DB_fetch_array($price_result);
		}
		?>
		<td><input type="text" name="mrp_rate[]" id="mrp_rate_<?php echo $itemrow['id'];?>" value="<?php if($pricerow['mrp_rate']!=''){echo $pricerow['mrp_rate'];}?>" /> </td>
	</tr>
<?php $nn++;} 
	}}
?>
  </table>
</div>
 
 
  <p style="margin-bottom:15px;"></p>
  <div class="body_lightbox" id="lightbox" style="overflow:auto; width:600px; height:250px; display:none;"></div>
 
<p align="center">
  <input type="submit" name="Save" id="save" value="Save"  />  
  <?php if($_REQUEST['ID'] !=''){?>
  <input type="hidden" name="actionType" id="actionType" value="Update" />
  <?php }else{?>
  <input type="hidden" name="actionType" id="actionType" value="addNew" />
  <?php } ?>
</p>
</form>

<script type="text/javascript">
function validateForm()
{
	if(document.getElementById("from_date").value=='')
	{
		alert("Select Valid From Date");
		document.getElementById("from_date").focus();
		return false;
	}
	
	if(document.getElementById("to_date").value=='')
	{
		alert("Select Valid To Date");
		document.getElementById("to_date").focus();
		return false;
	}
	
	return true;
}


function calculate_rate(id)
{
	var regex = /^\s*?(\d+(\.\d{1,2})?|\.\d{1,2})\s*$/ ;

	var mrp = document.getElementById("mrp_rate_"+id).value;
	var discount = document.getElementById("discount_"+id).value;
 	var netamount = 0;
	if(discount !=''){
	if(regex.test(discount)){
		if(mrp!='')
		{
			if(discount !=''){
				netamount = mrp - (mrp * discount)/100;
			}else{
				netamount = mrp;
			}
		}
		document.getElementById("net_rate_"+id).value = parseFloat(netamount).toFixed(2);
	}else{
		alert("Only digits/decimal values upto 2 places are allowed");
		document.getElementById("discount_"+id).value = '';
		document.getElementById("net_rate_"+id).value = mrp;
		document.getElementById("discount_"+id).focus();
		
	}
  }else
  		document.getElementById("net_rate_"+id).value = mrp;
}

function checkExisting()
{
	var particular=document.getElementById("particular");
	var particular1 = particular.options[particular.selectedIndex].text;
	var particular2 = particular.options[particular.selectedIndex].value;
	var from_date=document.getElementById("from_date").value;
	var to_date=document.getElementById("to_date").value;

	if(particular!='' && from_date!='' && to_date!='')
	{
		var typeId = document.getElementById("price_for");
   		var typeName = typeId.options[typeId.selectedIndex].text;
		var price_for=typeId.options[typeId.selectedIndex].value;

		if(to_date<from_date)
		{alert('End date cannot be less than start date'); return false;}
		
		if (window.XMLHttpRequest)
		{// code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp=new XMLHttpRequest();
		}
		else
		{// code for IE6, IE5
			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
		xmlhttp.onreadystatechange=function()
		{
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{
				var data=xmlhttp.responseText;
				if(data=='no')
				{
					alert('The period entered by you overlaps an existing period of  '+particular1+'  ('+typeName+')  price list. Please enter another period');
					document.getElementById("from_date").value='';
					document.getElementById("to_date").value='';
				}
			}
		}
	xmlhttp.open("GET","pms_checkExistingRecords.php?tp="+price_for+"&f="+from_date+"&t="+to_date+"&cli="+particular2,true);
	xmlhttp.send();
	}
}

function GetItems(str)
{
	var isEdit = '<?php echo $_REQUEST['ID'];?>';
	
	if(isEdit !='')
	{
		var con = confirm("are You sure you want to change Sub Group Type? It will delete your previous records.");
		if(!con){
			var selectedRow = document.getElementById("pre_subgroup").value;
			document.getElementById("subgroup_type").value = selectedRow;
			return;
		}
	}
	var subgroup = document.getElementById("subgroup_type").value;

	if (window.XMLHttpRequest)
	{// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp=new XMLHttpRequest();
	}
	else
	{// code for IE6, IE5
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	xmlhttp.onreadystatechange=function()
	{
		if (xmlhttp.readyState==4 && xmlhttp.status==200)
		{
			document.getElementById("itemdata").innerHTML=xmlhttp.responseText;
		}
	}
xmlhttp.open("GET","get_pricelist_by_subgroup.php?subgroup="+subgroup,true);
xmlhttp.send();
}

function fill_discount(str,last)
{
	for(var i=1;i<=last;i++)
	{
		if(document.getElementById("discount_"+i))
		{
			document.getElementById("discount_"+i).value=str;
			document.getElementById("net_rate_"+i).focus();
		}	
	}
}
</script>
