<?php
require_once(__DIR__."/../includes/sysinit.php");

class Attendance
{
	// Properties of the class:
	var $hddnAttendanceId, $selUserCode, $edtAttendanceIn, $edtAttendanceOut, $edtAttendanceInLat, $edtAttendanceInLng, $edtAttendanceOutLat, $edtAttendanceOutLng, 
		$edtAttendanceInIp, $edtAttendanceOutIp;
	function __construct(){}
	function __destruct(){}

	function addAttendance()
	{
		if (empty($this->hddnAttendanceId))
		{
			if ($this->checkAttendanceExists())
			SableSystem::ajaxResponse(false, "", "This Attendance has already been added.", 
				5, "hddnAttendanceId", false, "hddnAttendanceId");
			$this->loadAttendance();
		}
		else
		{
			$this->updateAttendance();
		}
	}

	function loadAttendance()
	{
		global $sableDB;
		$insertQuery = "INSERT INTO attendance (
						user_code, attendance_in, attendance_out, attendance_in_lat, attendance_in_lng, attendance_out_lat, attendance_out_lng, attendance_in_ip, attendance_out_ip
						) VALUES (
						'".$this->selUserCode."',
						'".$this->edtAttendanceIn."',
						'".$this->edtAttendanceOut."',
						'".addslashes($this->edtAttendanceInLat)."',
						'".addslashes($this->edtAttendanceInLng)."',
						'".addslashes($this->edtAttendanceOutLat)."',
						'".addslashes($this->edtAttendanceOutLng)."',
						'".addslashes($this->edtAttendanceInIp)."',
						'".addslashes($this->edtAttendanceOutIp)."')";
		$res=$sableDB->updateQuery($insertQuery);
		//Check if the Attendance details were successfully added:
		if ($res)
		{
			$this->setAttendanceId();
			SableDBFunctions::loadAuditDetail($_SESSION['user']['user_code'], 'New Attendance added: '.$this->hddnAttendanceId, $this->hddnAttendanceId);
			SableSystem::ajaxResponse(true, '/attendance/', 'The Attendance was successfully added.', 0, "", 0, "");
		}
		else
			SableSystem::ajaxResponse(false, "", "Add of a new Attendance failed. Please try again or contact support.", 
				5, "hddnAttendanceId", false, "hddnAttendanceId");
	}

	function updateAttendance()
	{
		global $sableDB;
		$code = SableSystem::sableDecode($this->hddnAttendanceId);
		$updateQuery = "UPDATE attendance set 
						user_code = '".$this->selUserCode."', 
						attendance_in = '".$this->edtAttendanceIn."', 
						attendance_out = '".$this->edtAttendanceOut."', 
						attendance_in_lat = '".addslashes($this->edtAttendanceInLat)."', 
						attendance_in_lng = '".addslashes($this->edtAttendanceInLng)."', 
						attendance_out_lat = '".addslashes($this->edtAttendanceOutLat)."', 
						attendance_out_lng = '".addslashes($this->edtAttendanceOutLng)."', 
						attendance_in_ip = '".addslashes($this->edtAttendanceInIp)."', 
						attendance_out_ip = '".addslashes($this->edtAttendanceOutIp)."' 
						where attendance_id = '".$code."'";
		$res=$sableDB->updateQuery($updateQuery);
		//Check if the details were successfully updated:
		if ($res)
		{
			SableDBFunctions::loadAuditDetail($_SESSION['user']['user_code'], 
				'Attendance details modified: '.$this->hddnAttendanceId, $code);
			SableSystem::ajaxResponse(true, '/attendance/', 'The Attendance was successfully updated.', 0, "", 0, "");
		}
		else 
			SableSystem::ajaxResponse(false, "", "Modification of the Attendance failed. Please try again or contact support.", 
				5, "hddnAttendanceId", false, "hddnAttendanceId");
	}

	private function getAttendanceId()
	{
		global $sableDB;
		$sql = "select attendance_id 
				from attendance 
				where user_code = {$this->selUserCode} and attendance_in = '{$this->edtAttendanceIn}'";
		return $sableDB->getValue($sql);
	}

	private function checkAttendanceExists()
	{
		$cid = $this->getAttendanceId();
		if (!empty($cid)) return true; else return false;
	}

	private function setAttendanceId()
	{
		$this->hddnAttendanceId = $this->getAttendanceId();
	}

	function viewAttendance()
	{
		$url = '/attendance/view.php?'.SableSystem::sableDecode($this->hddnAttendanceId);
		SableSystem::ajaxPageRedirect($url);
	}

	function editAttendance()
	{
		$url = '/attendance/edit.php?'.SableSystem::sableDecode($this->hddnAttendanceId);
		SableSystem::ajaxPageRedirect($url);
	}

	function deleteAttendance()
	{
		global $sableDB;
		$code = SableSystem::sableDecode($this->hddnAttendanceId);
		$cnt = $sableDB->getValue("select count(*) from attendance where attendance_id = ".$code);
		if ($cnt <= 0)
			SableSystem::ajaxResponse(false, "", "Delete failed - invalid Attendance selected.", 
				5, "hddnAttendanceId", false, "hddnAttendanceId");
		else
		{
			$sql = "delete from attendance where attendance_id = '".$code."'";
			$res = $sableDB->updateQuery($sql);
			if ($res)
			{
				SableDBFunctions::loadAuditDetail($_SESSION["user"]["user_code"], 'Attendance record deleted.', $code);
				SableSystem::ajaxPageRedirect('/attendance/','The Attendance record was successfully deleted.');
			}
			else
			SableSystem::ajaxResponse(false, "", "
			System error: The Attendance failed to delete. Please try again later or contact support.", 
				5, "hddnAttendanceId", false, "hddnAttendanceId");
		}
	}
	
	private function checkGPS($coord)
	{
		if (empty($coord))
			SableSystem::ajaxResponse(true, "/home/", 
									   "Attendance Registration Failed - GPS Not Enabled.".PHP_EOL."Please ensure your device is GPS capable and that you have granted permissions for this app to use Location Services.", 5, "hddnAttendanceId", false, 
									  "hddnAttendanceId");
	}
	
	function checkIn()
	{
		global $sableDB;
		$this->checkGPS($this->edtAttendanceInLat);
		
		$this->selUserCode = $_SESSION['user']['user_code'];
		$this->edtAttendanceIn = date('Y-m-d H:i:s');
		$ip = SableGeneralFunctions::getRealIpAddr();
		$name = SableDBFunctions::getUserDisplayNameFromUserCode($this->selUserCode);
		$insertQuery = "INSERT INTO attendance (
						user_code, attendance_in, attendance_out, attendance_in_lat, attendance_in_lng, attendance_out_lat, attendance_out_lng, attendance_in_ip, attendance_out_ip
						) VALUES (
						'{$this->selUserCode}',
						'{$this->edtAttendanceIn}',
						NULL,
						'{$this->edtAttendanceInLat}',
						'{$this->edtAttendanceInLng}',
						NULL,
						NULL,
						'{$ip}',
						NULL)";
		$res=$sableDB->updateQuery($insertQuery);
		//Check if the Attendance details were successfully added:
		if ($res)
		{
			$this->setAttendanceId();
			SableDBFunctions::loadAuditDetail($_SESSION['user']['user_code'], 
											  "Employee \"{$name}\" checked in: {$this->edtAttendanceIn}", 
											  $this->hddnAttendanceId);
			SableSystem::ajaxResponse(true, '/home/', 'You have successfully checked in.', 0, "", 0, "");
		}
		else
			SableSystem::ajaxResponse(false, "", "You could not be checked in. Please try again or contact support.", 
				5, "edtAttendanceInLat", false, "edtAttendanceInLat");
	}
	
	function checkOut()
	{
		global $sableDB;
		
		$attendance = $sableDB->getRow("select *
									from attendance 
									where user_code = {$_SESSION['user']['user_code']} 
									order by attendance_in DESC 
									limit 0,1"); //get just the latest entry for the user		
		
		if ($attendance['attendance_out'] ?? 0)
		{
			SableSystem::ajaxResponse(false, "", "You are already checked out.", 
									  5, "edtAttendanceOutLat", false, "edtAttendanceOutLat");
		}
		else
		{
			$this->checkGPS($this->edtAttendanceOutLat);

			$this->edtAttendanceIn = $attendance['attendance_in'];
			$this->selUserCode = $_SESSION['user']['user_code'];
			$this->setAttendanceId();
	
			$this->edtAttendanceOut = date('Y-m-d H:i:s');
			$ip = SableGeneralFunctions::getRealIpAddr();
			$name = SableDBFunctions::getUserDisplayNameFromUserCode($this->selUserCode);
			$insertQuery = "update attendance 
							set attendance_out = '{$this->edtAttendanceOut}', 
							attendance_out_lat = '{$this->edtAttendanceOutLat}', 
							attendance_out_lng = '{$this->edtAttendanceOutLng}', 
							attendance_out_ip = '{$ip}' 
							where attendance_id = {$this->hddnAttendanceId}";

			$res=$sableDB->updateQuery($insertQuery);
			//Check if the Attendance details were successfully added:
			if ($res)
			{
				SableDBFunctions::loadAuditDetail($_SESSION['user']['user_code'], 
												  "Employee \"{$name}\" checked out: {$this->edtAttendanceOut}", 
												  $this->hddnAttendanceId);
				SableSystem::ajaxResponse(true, '/home/', 'You have successfully checked out.', 0, "", 0, "");
			}
			else
				SableSystem::ajaxResponse(false, "", "You could not be checked out. Please try again or contact support.", 
					5, "edtAttendanceOutLat", false, "edtAttendanceOutLat");
		}
	}	

} //classAttendance