<?php
include_once("config.php");
// Get header content
$template="../templates/admin/header.tpl";
$content=$supp_obj->return_file_content($template);
$content=$supp_obj->screen_plugin_content("knowledgebase",$content);
$content=$manager->filter_restricted_admin($supp_obj,$content);
//Code for displaying the title in every page
$config=$supp_obj->prefix_table("configuration");
$sql="select * from $config ";
$array=$supp_obj->get_a_line($sql);
$a_config=$array;

if($array['cron_option']=="0")	// hv to execute mailpilot.php
{	
	if(time()-$array['last_checked']>=($array['cron_time']*60))	// last time the page was loaded is well above the limits
	{
		include_once("../cron/mail.php");
	}
}

$array['cPagetitle']=$generic_msg['cProdname']." - ".$titles_array[$page_name];
//print_R($array);
//Code end
if((isset($post_vars['fdept_id']) and $post_vars['fdept_id']!="") or (isset($get_vars['fdept_id']) and $get_vars['fdept_id']!=""))			// set department id
{
	if($post_vars['fdept_id']=="all")
	{	
		$post_vars['fdept_id']='';
	}

	$cdept_id=$get_vars['fdept_id'];
	if($post_vars['fdept_id']!="")
	{
		$cdept_id=$post_vars['fdept_id'];
	}
	
	$_SESSION['fdept_id']=$cdept_id;
}

// Department id passed by stats module.
if(isset($get_vars['sub_dept']))
{
	$_SESSION['sub_dept']=$get_vars['sub_dept'];
}

if(isset($get_vars['custom_field']))
{
	$_SESSION['custom_field']=$get_vars['custom_field'];
}

if($get_vars['enableall']=="yes")
{
	$_SESSION['searchtext']="";
	$_SESSION['Ffrom_date']="";
	$_SESSION['Fto_date']="";
	$_SESSION['fstatus']="";
	$_SESSION['priority_type']="";
	$_SESSION['sub_dept']="";
	$_SESSION['typeofsearch']="";
	$_SESSION['custom_field']="";
	$_SESSION['filter_column']=''; // Used in ageing report. Used to filter against ticket_created time
	
}

function is_admin($supp_obj,$staff_id,$content)
{
	$staff=$supp_obj->prefix_table("staff");
	$sql="select is_admin,allow_canned,allow_staff from $staff where staff_id='$staff_id' ";
	$a_sql=$supp_obj->get_a_line($sql);
	if($a_sql['is_admin']=="1" or ($a_sql['allow_canned']=="y" or $a_sql['allow_staff']=="y"))	// Staff is an administrator
	{
		$content=preg_replace("/\<\{admin_(.*?)\}\>/is","",$content);
		if($a_sql['is_admin']!="1")
		{
			$content=preg_replace("/<{adminonly_start}>(.*?)<{adminonly_end}>/is","",$content);	
		}
		else
		{
			$content=preg_replace("/\<\{adminonly_(.*?)\}\>/is","",$content);
		}
		if(($a_sql['allow_canned']=="y" and $a_sql['allow_staff']=="y") or ($a_sql['is_admin']=="1"))
		{
			$content=preg_replace("/\<\{cannedandstaff_(.*?)\}\>/is","",$content);

		}
		else
		{
			$patterns_array=array("/<{adminonly_start}>(.*?)<{adminonly_end}>/is","/<{cannedandstaff_start}>(.*?)<{cannedandstaff_end}>/is");
			$content=@preg_replace($patterns_array,"",$content);	
		}
	}		
	else
	{
		$patterns_array=array("/<{admin_start}>(.*?)<{admin_end}>/is","/<{adminonly_start}>(.*?)<{adminonly_end}>/is","/<{cannedandstaff_start}>(.*?)<{cannedandstaff_end}>/is");
		$content=preg_replace($patterns_array,"",$content);	
	}
	return $content;
}
	
class Header
{
	function belongsToDept ($supp_obj, $id, $dept_id)
	{
		$fields 	= $supp_obj -> prefix_table ("fields");
		$field_dept 	= $supp_obj -> prefix_table ("field_dept");

		while ($id != -1)
		{
			$sql = "select parent_id, field_id from $fields where field_id = '" . $id . "'";
			$res = $supp_obj -> get_rsltset ($sql);
			$id = $res [0]['parent_id'];
		}

		$id = $res [0]['field_id'];

		$sql = "select * from $field_dept where field_id = '" . $id . "' and dept_id = '" . $dept_id . "'";
		$res = $supp_obj -> get_rsltset ($sql);

		if (count ($res) == 0)
		{
			return "false";
		}
		else
		{
			return "true";	
		}

	}

/*Get those departments to which the staff has been assigned to*/
//--------------------------------------------------------------------------------
	function get_staff_departments($supp_obj,$staff_id,$content,$a_predefined)
	{
		$post_vars=$a_predefined['post'];
		@extract($post_vars);
		$departments=$supp_obj->prefix_table("departments");
		$staff_departments=$supp_obj->prefix_table("staff_departments");
		$sql=$supp_obj->get_dept_list_query($a_predefined);
		$loop_sql['dept_']=$sql;
		$loop_sql['subdept_']=$sql;
		$sel_arr=array();
		if(isset($_SESSION['fdept_id']))
		{
			$sel_arr['dept_']['dept_id']=array($_SESSION['fdept_id']);
		}
		if(isset($_SESSION['sub_dept']))
		{
			$sel_arr['subdept_']['dept_id']=array($_SESSION['sub_dept']);
		}

		$sql="select dept_id from $staff_departments where staff_id='$staff_id' ";
		$a_dept=$supp_obj->get_single_column($sql);
		$dept_ids=@implode("','",$a_dept);

	
		$fields=$supp_obj->prefix_table("fields");
		$field_dept=$supp_obj->prefix_table("field_dept");
		$sql="select distinct $fields.field_id, $fields.table_field, 
		$fields.orient_id,
		$fields.field_name from $fields left outer join $field_dept on $fields.field_id=$field_dept.field_id 
		where ( $field_dept.dept_id in ('$dept_ids') or $fields.orient_id='1')  ";
		
		
		$loop_sql['custom_']=$sql;	

		$sql_fields = "select * from $fields";
		$res_fields = $supp_obj -> get_rsltset ($sql_fields);

		for ($i = 0; $i < count($res_fields); $i ++)
		{
			if ($res_fields [$i]['orient_id'] == 1)
			{
				if ($_SESSION ["custom_field"] == $res_fields [$i]['field_id'])
				{
					$content_custom .= "<option value=\"" . $res_fields [$i]['field_id'] .
						"\" selected>" . $res_fields [$i]['field_name'] ."</option>";
				} else {
					$content_custom .= "<option value=\"" . $res_fields [$i]['field_id'] .
						"\">" . $res_fields [$i]['field_name'] ."</option>";
				}
			} else {
				$bFound = false;

				for ($j = 0; $j < count ($a_dept); $j ++)
				{
					if ($this -> belongsToDept ($supp_obj, $res_fields [$i]['field_id'], 
						$a_dept[$j]['dept_id'] ) == "true" && !$bFound)
					{
						$bFound = true;
						
						if ($_SESSION ["custom_field"] == $res_fields [$i]['field_id'])
						{
							$content_custom .= "<option value=\"" . $res_fields [$i]['field_id'] .
								"\" selected>" . $res_fields [$i]['field_name'] ."</option>";
						}
						else
						{
							$content_custom .= "<option value=\"" . $res_fields [$i]['field_id'] .
								"\">" . $res_fields [$i]['field_name'] ."</option>";
						}
						
					}
				}
			}
		}
		if(isset($_SESSION['custom_field'])) {
			$sel_arr['custom_']['field_id']=array($_SESSION['custom_field']);
		}
		$a_content=$supp_obj->replace_loop($loop_sql,$content,'',$sel_arr);
		$content=$a_content[0];
		$content = preg_replace ("/<{custom_fields_list}>/is", $content_custom, $content);
		return $content;
	}
//---------------------------------------------------------------------------------
}
$head=new Header();
//Check whether session exists
if(isset($_SESSION['staff_id']) and $_SESSION['staff_id']!="") {
	$staff_id=$_SESSION['staff_id'];
	$content=preg_replace("/\<\{session_(.*?)\}\>/is","",$content);
	$content=is_admin($supp_obj,$staff_id,$content);	
	$content=$head->get_staff_departments($supp_obj,$staff_id,$content,$a_predefined);
} else {
	$content=preg_replace("/\<\{session_existsstart\}\>(.*?)\<\{session_existsend\}\>/is","",$content);
}
if(isset($_SESSION['staff_username'])) {
	$array['staff_username']=$_SESSION['staff_username'];
	if($_SESSION['employeeID'] == NULL) {
		$staff_username = $array['staff_username'];
		$sql = "SELECT a.emp_number
				FROM hs_hr_users a
				LEFT JOIN hs_hr_employee b ON ( a.emp_number = b.emp_number )
				WHERE a.USER_NAME = '$staff_username'";
		$a_staff = $supp_obj->get_a_line($sql);
		$_SESSION['employeeID'] = $a_staff['0'];
	}
} else {
	$array['staff_username'] = "";	
}
if($_SESSION['first_login'] == 1) {
	$array['onload'] = ' onload="launch_chat();"';
	unset($_SESSION['first_login']);
}
/*check if staff require attendance*/
if($_SESSION['employeeID'] == NULL || $_SESSION['isAdmin'] == "Yes") {
	$content=preg_replace("/<{hrmsession_existsstart}>(.*?)<{hrmsession_existsend}>/is","",$content);	
} else {
	$employeeID = $_SESSION['employeeID'];
	$content=preg_replace("/\<\{hrmsession_(.*?)\}\>/is","",$content);
	$date_start = date("Y-m-d 00:00:00");
	$date_end = date("Y-m-d 23:59:59");
	$zone=$_SESSION['zone'];
	
	$timeStampDiff = ($post_vars['hdnTimestampDiff'] - round(date('Z')/3600, 1))*3600;
	//$punchdate = $post_vars['loaddate']." ".$post_vars['loadtime'];
	$punchdate = date("Y-m-d H:i:s");
	
	/*
	* MARK ATTANDENCE
	*/
	if($post_vars['hdnAction'] == "IN") {
		$sql1 = "SELECT * FROM hs_hr_attendance WHERE employee_id = '".$post_vars['hdnEmployeeId']."' AND (".$supp_obj->date_add_sql('punchin_time',$zone,'minute')." between '$date_start' AND '$date_end') AND punchout_time IS NULL";
		$result = $supp_obj->return_db_handle($sql1);
		$count = $supp_obj->return_num_rows($result);
		
		if($num == 0) {
			/*punch out for previous records*/
		}
		
		if($count == 0) {
			//get max record ID
			$sql1 = "SELECT MAX(attendance_id) as attendance_id FROM hs_hr_attendance";
			$a_attend = $supp_obj->get_a_line($sql1);
			$post_vars['hdnAttendanceId'] = $a_attend['attendance_id']+1;
			
			$avoid_array=array("punchout_time","out_note");
			$insert_array=array("attendance_id"=>$post_vars['hdnAttendanceId'],"employee_id"=>$post_vars['hdnEmployeeId'],
			"punchin_time"=>$punchdate,"in_note"=>$post_vars['attennote'],"timestamp_diff"=>$timeStampDiff,"status"=>"1");
			$sql=$supp_obj->construct_query("hs_hr_attendance","INSERT",$insert_array,$avoid_array);
			$reply_id=$supp_obj->execute_query($sql);
		}
	} else {
		if($post_vars['hdnAction'] == "LUNCH") {
			$avoid_array=array("attendance_id","employee_id","punchin_time","in_note","timestamp_diff","status");
			$insert_array=array("punchout_time"=>$punchdate,"out_note"=>$post_vars['attennote'], "lunchout"=> "1");
			$sql=$supp_obj->construct_query("hs_hr_attendance","UPDATE",$insert_array,$avoid_array);
			$where_cla = " WHERE attendance_id = '".$post_vars['hdnAttendanceId']."'";
			$sql .= $where_cla;
			$reply_id=$supp_obj->execute_query($sql);
		} else if($post_vars['hdnAction'] == "OUT") {
			$avoid_array=array("attendance_id","employee_id","punchin_time","in_note","timestamp_diff","status");
			$insert_array=array("punchout_time"=>$punchdate,"out_note"=>$post_vars['attennote']);
			$sql=$supp_obj->construct_query("hs_hr_attendance","UPDATE",$insert_array,$avoid_array);
			$where_cla = " WHERE attendance_id = '".$post_vars['hdnAttendanceId']."'";
			$sql .= $where_cla;
			$reply_id=$supp_obj->execute_query($sql);
		}
	}
	
	//check if staff have any clock in for today
	$sql = "SELECT * FROM hs_hr_attendance WHERE employee_id = '$employeeID' AND (".$supp_obj->date_add_sql('punchin_time',$zone,'minute')." between '$date_start' AND '$date_end')";
	$results = $supp_obj->return_db_handle($sql);
	$num = $supp_obj->return_num_rows($results);
	
	if($num >= 1) {
		$sql = "SELECT * FROM hs_hr_attendance WHERE employee_id = '$employeeID' AND (".$supp_obj->date_add_sql('punchin_time',$zone,'minute')." between '$date_start' AND '$date_end') AND punchout_time IS NULL";
		$results = $supp_obj->return_db_handle($sql);
		$num = $supp_obj->return_num_rows($results);
		
		if($num == 1) {
			$array['disablein'] = ' disabled="disabled"';
			$array['disableout'] = '';
			//check if todays lunch out is already marked
			$sql = "SELECT * FROM hs_hr_attendance WHERE employee_id = '$employeeID' AND (".$supp_obj->date_add_sql('punchin_time',$zone,'minute')." between '$date_start' AND '$date_end') AND lunchout = 1";
			$results = $supp_obj->return_db_handle($sql);
			$num = $supp_obj->return_num_rows($results);
			if($num == 1) {
				$array['disablelunch'] = ' disabled="disabled"';
			} else {
				$array['disablelunch'] = '';
			}
		} else {
			$array['disablein'] = '';
			//check if todays lunch out is already marked
			$sql = "SELECT * FROM hs_hr_attendance WHERE employee_id = '$employeeID' AND (".$supp_obj->date_add_sql('punchin_time',$zone,'minute')." between '$date_start' AND '$date_end') AND lunchout = 1";
			$results = $supp_obj->return_db_handle($sql);
			$num = $supp_obj->return_num_rows($results);
			if($num == 1) {
				$array['disablelunch'] = ' disabled="disabled"';
			} else {
				$sql = "SELECT * FROM hs_hr_attendance WHERE employee_id = '$employeeID' AND (".$supp_obj->date_add_sql('punchin_time',$zone,'minute')." between '$date_start' AND '$date_end') AND punchout_time IS NULL";
				$results = $supp_obj->return_db_handle($sql);
				$num = $supp_obj->return_num_rows($results);
				if($num == 1) {
					$array['disableout'] = '';
					$array['disablelunch'] = '';
				} else {
					$array['disableout'] = ' disabled="disabled"';
					$array['disablelunch'] = ' disabled="disabled"';
				}
			}
		}

	} else {
		$array['disablein'] = '';
		$array['disableout'] = ' disabled="disabled"';
		$array['disablelunch'] = ' disabled="disabled"';
	}
	$array['REQUEST_URI'] = $_SERVER['REQUEST_URI'];
	$sql = "SELECT * FROM hs_hr_attendance WHERE employee_id = '$employeeID'"." AND (".$supp_obj->date_add_sql('punchin_time',$zone,'minute')." between '$date_start' AND '$date_end') AND punchout_time IS NULL";
	$a_aten=$supp_obj->get_a_line($sql);
	//get attendanceID START
	if($a_aten['attendance_id'] != NULL) {
		$array['attendanceid'] = $a_aten['attendance_id'];
	} else {
		$sql1 = "SELECT MAX(attendance_id) as attendance_id FROM hs_hr_attendance";
		$a_attend = $supp_obj->get_a_line($sql1);
		$array['attendanceid'] = $a_attend['attendance_id']+1;
	}
	//get attendanceID END
	
	//get all today's attendance
	$attendance = "SELECT punchin_time, punchout_time, lunchout FROM hs_hr_attendance WHERE employee_id = '$employeeID'"." AND (".$supp_obj->date_add_sql('punchin_time',$zone,'minute')." between '$date_start' AND '$date_end')";
	$resset = $supp_obj->return_db_handle($attendance);
	$array['LastPunchIn'] = '<table cellpadding="3" cellspacing="0" width="97%" class="attendance_log">';
	$counter_atten = 0;
	$array['LastPunchIn'] .= '<tr>';
	$array['LastPunchIn'] .= '<td class="attendance_head">';
	$array['LastPunchIn'] .= '<strong>#</strong>';
	$array['LastPunchIn'] .= "</td>";
	$array['LastPunchIn'] .= '<td class="attendance_head">';
	$array['LastPunchIn'] .= '<strong>IN</strong>';
	$array['LastPunchIn'] .= "</td>";
	$array['LastPunchIn'] .= '<td class="attendance_head">';
	$array['LastPunchIn'] .= '<strong>Out</strong>';
	$array['LastPunchIn'] .= "</td>";
	$array['LastPunchIn'] .= '<td class="attendance_head">';
	$array['LastPunchIn'] .= '<strong>Info</strong>';
	$array['LastPunchIn'] .= "</td>";
	$array['LastPunchIn'] .= '</tr>';
	while($atten_r = $supp_obj->return_next_row($resset)) {
		$counter_atten++;
		if($counter_atten % 2 == 0) {
			$atten_class = "attendance_bg";
		} else {
			$atten_class = "";
		}
		$array['LastPunchIn'] .= '<tr>';
			$array['LastPunchIn'] .= '<td class="'.$atten_class.'">';
			$array['LastPunchIn'] .= '<strong>'.$counter_atten.'</strong>';
			$array['LastPunchIn'] .= "</td>";
			$array['LastPunchIn'] .= '<td class="'.$atten_class.'">';
			$array['LastPunchIn'] .= date("H:i",strtotime($atten_r['punchin_time']));
			$array['LastPunchIn'] .= "</td>";
			$array['LastPunchIn'] .= '<td class="'.$atten_class.'">';
			if($atten_r['punchout_time'] != NULL) {
			$array['LastPunchIn'] .= date("H:i",strtotime($atten_r['punchout_time']));
			}
			$array['LastPunchIn'] .= "</td>";
			$array['LastPunchIn'] .= '<td class="'.$atten_class.'">';
			if($atten_r['lunchout'] == 1) {
			$array['LastPunchIn'] .= "<strong>LUNCH</strong>";
			} else {
				if($atten_r['punchout_time'] == NULL) {
					$array['LastPunchIn'] .= "IN";
				} else {
					$array['LastPunchIn'] .= "OUT";	
				}
			}
			$array['LastPunchIn'] .= "</td>";
		$array['LastPunchIn'] .= "</tr>";
	}
	$array['LastPunchIn'] .= '</table>';
	
	$array['employeeid'] = $employeeID;
	$array['loadeddate']  = date('Y-m-d');
	$array['loadedtime']  = date('H:i');
	$array['todays_date'] = date("D M d, Y h:i A");
}
/*attendance ends here*/

$pagenames_array=array("statistics","news_view","manage_news");
$tab_array=array("statistics"=>"stats","news_view"=>"news","manage_news"=>"news");
if(@in_array($page_name,$pagenames_array)) {
	$gotoscript=$page_name.".php?typeofsearch=simplesearch&tab=".$tab_array[$page_name];
} else {
	$gotoscript="tickets_view.php?tab=tickets";
}

$array['gotoscript']=$gotoscript;

		$searchtxt=$a_predefined['get']['searchtxt'];
		if(isset($a_predefined['post']['searchtxt'])) {
			$searchtxt=$a_predefined['post']['searchtxt'];
		}
	
		if($searchtxt!="" or isset($a_predefined['post']['searchtxt']) or isset($a_predefined['get']['searchtxt'])) {
			$_SESSION['searchtext']=$searchtxt;
			$_SESSION['filter_column']='';
		}
	//$difference_sql = "select MINUTE(TIMEDIFF(punchout_time, punchin_time)) as time FROM hs_hr_attendance";

if($_SESSION['staff_id']!="") {
	$array['hidedivscript']=$manager->get_hidescript($a_predefined);
}

$array['searchtxt']=$_SESSION['searchtext'];

//echo $page_name;		

$content=$supp_obj->direct_replace($content,$array);
echo $content;
// Check whether the staff is trying to access administration pages
	$staff=$supp_obj->prefix_table("staff");
	if(!isset($_SESSION['staff_id'])) { $_SESSION['staff_id']=""; };
	$sql="select is_admin,allow_canned,allow_staff from $staff where staff_id='".$_SESSION['staff_id']."'";
	$a_sql=$supp_obj->get_a_line($sql);
	$PHP_SELF=$_SERVER['PHP_SELF'];
	$PHP_SELF=substr(strrchr($PHP_SELF, "/"), 1);
	if(ereg("manage_",$PHP_SELF) and $a_sql['is_admin']!="1")
		{
			//unauthorized access
			if(($a_sql['allow_canned']!="y" and $a_sql['allow_staff']!="y"))
			{
				echo "<br /><div class=errormsg>".$generic_msg['cAccess_denied']."</div>";
				include("footer.php");
				exit;
			}
			else
			{
				if($PHP_SELF=="manage_staff.php" and $a_sql['allow_staff']!="y")
				{
					echo "<br /><div class=errormsg>".$generic_msg['cAccess_denied']."</div>";
					include("footer.php");
					exit;
				}
				if($PHP_SELF=="manage_replies.php" and $a_sql['allow_canned']!="y")
				{
					echo "<br /><div class=errormsg>".$generic_msg['cAccess_denied']."</div>";
					include("footer.php");
					exit;
				}
			}
		}
	$supp_obj->server_timezone_diff();
?>
