<?php 
$url_cancel= "index.php?route=ToolPlants/fixed_assets/fixed_assets_log_book_entry_index".$rurl;
$url_add= "index.php?route=ToolPlants/fixed_assets/fixed_assets_log_book_entry".$rurl;
if($_REQUEST['Save'] !='')
{
	if($_REQUEST['log_id'] ==''){
	$data['asset_type'] = $_REQUEST['asset_type'];
	$data['asset_code'] = $_REQUEST['asset_code'];
	$data['log_book_month'] = $_REQUEST['month'];
	$data['log_book_year'] = $_REQUEST['year'];
	$data['created'] = date('Y-m-d');
	$data['created_by'] = $_SESSION['UserID'];
	$data['CompanyId'] = $_SESSION['ACGCompanyId'];
		
	$s->RecordInsert('tpl_fixed_asset_logbook',$data);
	$last_id=DB_Last_Insert_Id($db,"tpl_fixed_asset_logbook","id");
	}else{
	$last_id = $_REQUEST['log_id'];
	
	}
	if($last_id !='')
	{
		$count = count($_REQUEST['start_meter_reading']);
		
		for($cnt=0; $cnt<$count; $cnt++){
		 if($_REQUEST['start_meter_reading'][$cnt] !=''){
			$data1['log_id'] = $last_id;
			$data1['asset_code'] = $_REQUEST['asset_code'];
			$data1['log_book_date'] = FormatDateForSQL($_REQUEST['log_book_date'][$cnt]);
			$data1['start_meter_reading'] = $_REQUEST['start_meter_reading'][$cnt];
			$data1['end_meter_reading'] = $_REQUEST['end_meter_reading'][$cnt];
			$data1['total_reading'] = $_REQUEST['total_reading'][$cnt];
			$data1['oil_consumption'] = $_REQUEST['oil_consumption'][$cnt];
			$data1['fuel_unit'] = $_REQUEST['fuel_unit'][$cnt];
			$data1['reading_unit'] = $_REQUEST['reading_unit'][$cnt];
			$data1['fuel_type'] = $_REQUEST['fuel_type'][$cnt];
			$data1['site'] = $_REQUEST['site'][$cnt];
			$data1['remark'] = $_REQUEST['remark'][$cnt];
			
			$s->RecordInsert('tpl_fixed_asset_logbook_details',$data1);
			
		 }
		}
	}
	$_SESSION['success_msg']="Saved Successfully";
	echo "<script>location.href='$url_cancel'</script>";
}


?>

<link rel="stylesheet" href="css/new_mxerp.css">
<div class="body_contain">
 <div class="tab_div">
  <h1>Fixed Asset Log Book Entry</h1>
  <form name="" id="" method="POST">
  <p align="left"><a href="<?php echo $url_add;?>"></a></p>
	<table width="100%" cellspacing="0" cellpadding="3" border="0">
	  <tr class="row1">
	  	<td width="13%" align="right">Group</td>
		<td width="35%">
			<select name="asset_type" id="asset_type" >
				 <option value="0">Select Asset Group</option>
          <?php
		  $asset_type=DB_query("Select * from machine_group_master where CompanyId='".$_SESSION['ACGCompanyId']."'",$db);
			while($asset_type_res=DB_fetch_array($asset_type))
				{
					$se='';
					if($_REQUEST['asset_type']==$asset_type_res['id'])
					$se="selected";
					?>
					<option value=<?php echo $asset_type_res['id'];?> <?php echo $se;?>><?php echo $asset_type_res['machine_gp_location'];?></option>
				<?php }
		  ?>
			</select></td>
		<td width="13%" align="right">Asset Name <font style="color:#FF0000;">*</font></td>
		<td><select name="asset_code" id="asset_code" >
				<option value="0">--Select--</option>
			<?php
				$sqlAssets = "SELECT id, name, code from machine_center WHERE CompanyId='".$_SESSION['ACGCompanyId']."'";
				$res = DB_query($sqlAssets,$db);
				while($assetRow = DB_fetch_array($res)){?>
				<option value="<?php echo $assetRow['id'];?>" <?php echo ($_REQUEST['asset_code']== $assetRow['id'] ) ? "selected" : "";?>><?php echo $assetRow['name']." (".$assetRow['code'].")";?></option>
			<?php } ?>
			</select>
		</td>
	</tr>
	<tr class="row1">
		<td align="right">Month <font style="color:#FF0000;">*</font></td>
		<td><select name="month" id="month" >
				<option value="0">--Select--</option>
			<?php				
				for($i=1; $i<=12; $i++){
					$m='';
					if(isset($_REQUEST['month']))
					{
						if($_REQUEST['month']== $i )
						{
							$m="selected";
						}
					}else{
						if(date("m")== $i )
						{
							$m="selected";
						}
					}	
					?>
				<option value="<?php echo $i;?>" <?php echo $m; ?> ><?php echo date('F', mktime(0, 0, 0, $i));?></option>
			<?php } ?>
			</select></td>
		<td align="right">Year <font style="color:#FF0000;">*</font></td>
		<td><select name="year" id="year" >
				<option value="0">--Select--</option>
			<?php				
				for($j=date('Y'); $j>=2000; $j--){
					$m='';
					if(isset($_REQUEST['year']))
					{
						if($_REQUEST['year']== $j )
						{
							$m="selected";
						}
					}else{
						if(date("Y")== $j )
						{
							$m="selected";
						}
					}	
					?>
				<option value="<?php echo $j;?>" <?php echo $m;?>><?php echo $j;?></option>
			<?php } ?>
			</select>
		</td>
	  </tr>
	  <tr class="row1">
		<td colspan="4" style="text-align:center;"><input type="submit" name="Search" class="search" value="Proceed" onclick="return validate();" /></td>
	  </tr>
</table>
<br>

<?php 
if($_REQUEST['Search'] !=''){
$error_msg = "";
$month = $_REQUEST['month'];
$year = $_REQUEST['year'];
if($year>date('Y'))
{
	$error_msg = "Check Year. It must not be grater than current year";
}elseif($year==date('Y'))
{
	if($month>date('n'))
	{
		$error_msg = "Check Month. It must not be grater than current month.";
 	}
    else{
		//if($month==date('n') and $year==date('Y'))
		//{
			//$endDate = date('j'); 
                     
		//}else{
			$date = $year."-".$month."-1";
			$endDate = date("t", strtotime($date));
		//}
	}
}
	
	$sql1 = "SELECT end_meter_reading, DAY(log_book_date) as lstday, log_id FROM tpl_fixed_asset_logbook_details LD
			 INNER JOIN tpl_fixed_asset_logbook L ON L.id=LD.log_id
			 WHERE LD.asset_code='".$_REQUEST['asset_code']."' and MONTH(LD.log_book_date)='".$month."' and 
			 YEAR(LD.log_book_date)='".$year."' and L.CompanyId='".$_SESSION['ACGCompanyId']."' ORDER BY LD.id desc 
			 LIMIT 1";
	
	$res1 = DB_query($sql1,$db);
	if(DB_num_rows($res1)>0)
	{
		$row1 = DB_fetch_array($res1);
		$start_meter_reading = $row1['end_meter_reading'];
		$lstday = $row1['lstday'];
		
		$endDate1 = date("t", strtotime($date));
		if($lstday == $endDate)
		{
			$error_msg = "Log Book Entry for this Asset is completed till ".$lstday." ".date('F', mktime(0, 0, 0, $month)).", ".$year;
		}else{
			$startDate = $lstday+1;
			$log_id = $row1['log_id'];
		}
	
	}else{
	
		if($_REQUEST['month'] =='1'){
			$month1 = 12;
			$year1 = (int)$_REQUEST['year']-1;
			//$endDate = 31;
		}else{
			$month1 = $month-1;
			$year1 = $year;
		
		}
	
		 $sql2 = "SELECT end_meter_reading, DAY(log_book_date) as lstday, log_id FROM tpl_fixed_asset_logbook_details LD
			 INNER JOIN tpl_fixed_asset_logbook L ON L.id=LD.log_id
			 WHERE LD.asset_code='".$_REQUEST['asset_code']."' and MONTH(LD.log_book_date)='".$month1."' and 
			 YEAR(LD.log_book_date)='".$year1."' and L.CompanyId='".$_SESSION['ACGCompanyId']."' ORDER BY LD.id desc 
			 LIMIT 1";
	
			$res2 = DB_query($sql2,$db);
			if(DB_num_rows($res2)>0)
			{
				$date1 = $year1."-".$month1."-1";
				$endDate1 = date("t", strtotime($date1));
				$row1 = DB_fetch_array($res2);
				$start_meter_reading = $row1['end_meter_reading'];
				
				$lstday = $row1['lstday'];
				
				if($lstday == $endDate1)
				{
					$startDate = 1;
				
				}else{
					$startDate = 1;
					$log_id = $row1['log_id'];
					$error_msg = "Complete Previous Month Entries To Proceed";
				}				
			
			}else{
	
				$sql3 = "SELECT average_production_qty,manchine_opening_date FROM machine_center 
						 WHERE id='".$_REQUEST['asset_code']."'";
				$res3 = DB_query($sql3,$db);
				
				$row3 = DB_fetch_array($res3);
				if($row3['average_production_qty'] == "")
				{
					$error_msg = "Check Opening Meter Reading";
				}else{
					$start_meter_reading = $row3['average_production_qty'];
				}
				
				if($row3['manchine_opening_date'] == "0000-00-00")
				{
					$error_msg = "Check Opening Date";
					
				}else{
				
					$opening_date = date("j/n/Y",strtotime($row3['manchine_opening_date']));
					$parray = explode("/",$opening_date);
					if($year<$parray[2])
					{
						$error_msg = "Year must be greater Than or Equal to Meter Opening Year ".date('F', mktime(0, 0, 0, $parray[1])).", ".$parray[2];
					}elseif($year==$parray[2] and $month<$parray[1]){
					
						$error_msg = "Month must be greater Than or Equal to Meter Opening Month ".date('F', mktime(0, 0, 0, $parray[1])).", ".$parray[2];
					}elseif($month==$parray[1]){
						 $startDate = $parray[0];
                                               //  $num = cal_days_in_month(CAL_GREGORIAN, $parray[1], $parray[0]);
					}else{
						$startDate = 1;
					}
				}
		}
	}

if($error_msg==""){
	$sqlAssets = "SELECT * from machine_center WHERE id='".$_REQUEST['asset_code']."'";
	$res = DB_query($sqlAssets,$db);
	$myrow_res=DB_fetch_array($res);
?>
<table width="100%" border="0" cellspacing="0" cellpadding="3" class="thborder">
	<tr>
		<th width="7%">Date</th>
		<th width="8%">Start Meter Reading <font style="color:#FF0000;">*</font></th>
		<th width="8%">End Meter Reading <font style="color:#FF0000;">*</font></th>
		<th width="8%">Total Reading</th>
		<th width="6%">Reading Unit</th>
		<th width="8%">Fuel Consumption <font style="color:#FF0000;">*</font></th>
		<th width="6%">Fuel Unit</th>
		<th width="6%">Fuel Type</th>
		<th>Working Branch</th>
		<th width="16%">Remark</th>
   </tr>   
<?php			
	for($k=$startDate; $k<=$endDate; $k++){
	$reading_date = $k."/".$month."/".$year;
	$reading_date1 = $year."-".$month."-".$k;
?>
   <tr>
	<td><input type="text" name="log_book_date[]" id="log_book_date_<?php echo $k;?>" value="<?php echo $reading_date;?>" readonly=""  /></td>
	<td><input type="text" name="start_meter_reading[]" id="start_meter_reading_<?php echo $k;?>" value="<?php echo ($k==$startDate)? (int)$start_meter_reading : "";?>" onfocus="setStartReading('<?php echo $k;?>')" <?php echo ($k==$startDate and $start_meter_reading !='')? "readonly" : "readonly";?> /></td>
	<td><input type="text" name="end_meter_reading[]" id="end_meter_reading_<?php echo $k;?>" value="<?php echo $end_meter_reading;?>"  onblur="calTotal('<?php echo $k;?>');"/></td>
	<td><input type="text" name="total_reading[]" id="total_reading_<?php echo $k;?>" value="<?php echo $total_reading;?>" readonly="" /></td>
	<td><input type="text" name="reading_unit[]" id="reading_unit_<?php echo $k;?>" value="<?php echo $s->GetFieldValue('unitsofmeasure',"unitid='".$myrow_res['reading_unit']."'",'unitname');?>" readonly=""  /></td>
	<td><input type="text" name="oil_consumption[]" id="oil_consumption_<?php echo $k;?>" value="<?php echo $oil_consumption;?>"  /></td>
	<td><input type="text" name="fuel_unit[]" id="fuel_unit_<?php echo $k;?>" value="<?php echo $s->GetFieldValue('unitsofmeasure',"unitid='".$myrow_res['fuel_unit']."'",'unitname');?>" readonly="" /></td>
	<td><input type="text" name="fuel_type[]" id="fuel_type_<?php echo $k;?>" value="<?php echo $myrow_res['fule_type'];?>" readonly="" /></td>
	<td><?php
		//echo "Select R.receive_site from tpl_asset_transfer_receive_details AS RD LEFT JOIN tpl_asset_transfer_receive AS R ON RD.receive_id=R.id where asset_id='".$_REQUEST['asset_code']."' and R.receive_date<='".$reading_date1."' order by RD.id DESC limit 0,1";
		$sqlL=DB_query("Select R.receive_site from tpl_asset_transfer_receive_details AS RD LEFT JOIN tpl_asset_transfer_receive AS R ON RD.receive_id=R.id where asset_id='".$_REQUEST['asset_code']."' and R.receive_date<='".$reading_date1."' order by RD.id DESC limit 0,1",$db); 
		 $myrow_loc=DB_fetch_array($sqlL);

		 if($myrow_loc['receive_site']!='')
		 {
		 	$work_loc=$myrow_loc['receive_site'];
		 }else{
		 	$work_loc=$myrow_res['work_location'];
		 }
		?>
	<select name="site[]" id="site_<?php echo $k;?>" >
		<?php
			$sitesql = "SELECT loccode,locationname FROM locations WHERE CompanyId='".$_SESSION['ACGCompanyId']."'";
			$res = DB_query($sitesql,$db);
			while($siteRow = DB_fetch_array($res)){?>
		<option value="<?php echo $siteRow['loccode'];?>" <?php echo ($siteRow['loccode']==$work_loc) ? "selected" : "";?>>
			<?php echo $siteRow['locationname'];?>
		</option>
		<?php }?>
		</select></td>
	<td><input type="text" name="remark[]" id="remark_<?php echo $k;?>" value="" /></td>
  </tr>
  <?php	}?>
  	<input type="hidden" name="log_id" value="<?php echo $log_id;?>" />  
</table>
<p align="center">
		  	<input type="submit" name="Save" value="Save" id="Save" class="search" onclick="return validateReading();" />
			<input type="hidden" name="startDate" id="startDate" value="<?php echo $startDate;?>" />
			<input type="hidden" name="endDate" id="endDate" value="<?php echo $endDate;?>" />			
</p>
		<?php }
		else{  ?>
<p align="center"><font color="#990000"><strong><?php echo $error_msg;?></strong></font></p>
  <?php }
  }
  ?>
  </form>
 </div>
</div>

<?php if(isset($_SESSION['success_msg']))
{ ?>
	<script> alert("<?php echo ($_SESSION['success_msg']);?>");</script>
<?php 
}	unset($_SESSION['success_msg']);
?>

<script type="text/javascript">
function validate(){

	if(document.getElementById("asset_code").value==0)
	{
		alert("Select Asset Name");
		document.getElementById("asset_code").focus();
		return false;
	}
	if(document.getElementById("month").value==0)
	{
		alert("Select Month");
		document.getElementById("month").focus();
		return false;
	}
	if(document.getElementById("year").value==0)
	{
		alert("Select Year");
		document.getElementById("year").focus();
		return false;
	}
}

function validateReading(){

	var start = document.getElementById("startDate").value;
	var end = document.getElementById("endDate").value;
	//alert(start+" = > "+end);
	for(var i=start; i<=end; i++){
		if(document.getElementById("start_meter_reading_"+i).value=='' && document.getElementById("end_meter_reading_"+i).value==''){
		}else{
		if(document.getElementById("start_meter_reading_"+i).value==''){
			alert("Start Meter Reading Can Not Be Empty");
			document.getElementById("start_meter_reading_"+i).focus();
			return false;
		}
		if(document.getElementById("end_meter_reading_"+i).value==''){
			alert("End Meter Reading Can Not Be Empty");
			document.getElementById("end_meter_reading_"+i).focus();
			return false;
		}
		if(document.getElementById("total_reading_"+i).value==''){
			alert("Total Reading Can Not Be Empty");
			document.getElementById("total_reading_"+i).focus();
			return false;
		}
		
		if(document.getElementById("oil_consumption_"+i).value==''){
			alert("Start Meter Reading Can Not Be Empty");
			document.getElementById("oil_consumption_"+i).focus();
			return false;
		}else if(document.getElementById("total_reading_"+i).value >0 && document.getElementById("oil_consumption_"+i).value==0 ){
			alert("Enter Valid Oil Consumption Value");
			document.getElementById("oil_consumption_"+i).focus();
			return false;	
		}
		}
	}
}

function calTotal(id){

	var startReading = parseInt(document.getElementById("start_meter_reading_"+id).value);
	var endReading = parseInt(document.getElementById("end_meter_reading_"+id).value);
	if(isNormalInteger(endReading) && endReading !=''){
	if(startReading>endReading){
		document.getElementById("end_meter_reading_"+id).value='';
		document.getElementById("total_reading_"+id).value = '';
		document.getElementById("end_meter_reading_"+id).focus();
		alert("End Meter Reading Can Not Be Less than Start Meter Reading");
	}else{
		var total = endReading-startReading;
		document.getElementById("total_reading_"+id).value = total;
		if(total == 0){
			document.getElementById("oil_consumption_"+id).value = total;
			document.getElementById("oil_consumption_"+id).readOnly = true;
		}
	}
	}else{
		document.getElementById("end_meter_reading_"+id).value='';
		document.getElementById("total_reading_"+id).value = '';
		document.getElementById("end_meter_reading_"+id).focus();
		alert("Enter only numbers");
	}
}

function setStartReading(id){

	var start = document.getElementById("startDate").value;
	if(id==start){
		return;
	}else{
		var lastid = parseInt(id)-1; 
		document.getElementById("start_meter_reading_"+id).value=document.getElementById("end_meter_reading_"+lastid).value;
	}

}

function isNormalInteger(str) {
    return /^\+?(0|[1-9]\d*)$/.test(str);
}
</script>
