<?php
 /*+*******************************************************************************
 * The content of this file is subject to the CRMTiger Pro license.
 * ("License"); You may not use this file except in compliance with the License
 * The Initial Developer of the Original Code is vTiger
 * The Modified Code of the Original Code owned by https://crmtiger.com/
 * Portions created by CRMTiger.com are Copyright(C) CRMTiger.com
 * All Rights Reserved.
  ***************************************************************************** */


class CTMobile_WS_AttendanceReport extends CTMobile_WS_Controller {
	
	function process(CTMobile_API_Request $request) {
		global $current_user,$adb;
		$current_user = $this->getActiveUser();
		$default_charset = VTWS_PreserveGlobal::getGlobal('default_charset');
		$presence = array('0', '2');
		$response = new CTMobile_API_Response();
		$user_id = $request->get('user_id');
		$attendance_type = $request->get('attendance_type');
		$daterange = $request->get('daterange');
		
		if($daterange != ''){
			$date = explode(' - ',$daterange);
			$date1 = date("Y-m-d", strtotime($date[0]));
			$date2 = date("Y-m-d", strtotime($date[1]));
		}
	
		$index = trim($request->get('index'));
		$size = trim($request->get('size'));
		$limit = ($index*$size) - $size;
		
		
		$data = array();
		$sql = "SELECT vtiger_ctattendance.*,vtiger_crmentity.createdtime,vtiger_crmentity.modifiedtime FROM vtiger_ctattendance INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_ctattendance.ctattendanceid WHERE vtiger_crmentity.deleted = 0 AND vtiger_crmentity.crmid > 0 ";

		if(!empty($user_id))
			$sql.=" AND vtiger_ctattendance.employee_name = '$user_id'";

		if($attendance_type != ''){
			if($attendance_type == 'events_attendance'){
				$sql.=" AND ( vtiger_ctattendance.eventid != '' OR vtiger_ctattendance.eventid IS NOT NULL ) ";
			}else if($attendance_type == 'home_attendance'){
				$sql.=" AND (vtiger_ctattendance.eventid IS NULL OR vtiger_ctattendance.eventid = '') ";
			}
		}

		if(!empty($daterange))
			$sql.=" AND DATE(vtiger_crmentity.createdtime) BETWEEN '$date1' AND '$date2' ";
		
		$sql.= " ORDER BY vtiger_crmentity.modifiedtime DESC";
		$totalQuery = $sql;
		if($index != '' && $size != ''){
			$sql.= " LIMIT $limit, $size";
		}
		
		$result1 = $adb->pquery($totalQuery,array());
		$recordsTotal = $adb->num_rows($result1);
		$result2 = $adb->pquery($sql,array());
		$numofrows = $adb->num_rows($result2);
		$last_latitude = '';
		$last_longitude = '';
		$isLast = true;
		for($i=0;$i<$numofrows;$i++){
			$row = $adb->query_result_rowdata($result2,$i);
			$eventid = $row['eventid'];

			$setype = '';
			$modulelabel = '';
			if($eventid != ''){
				$rel_query = "SELECT * FROM vtiger_crmentity WHERE crmid = ? and deleted = 0";
				$rel_Results = $adb->pquery($rel_query,array($eventid));
				if($adb->num_rows($rel_Results)){
					$setype = $adb->query_result($rel_Results,0,'setype');
					if($setype == 'Events'){
						$moduleModels = Vtiger_Module_Model::getInstance('Calendar');
					}else{
						$moduleModels = Vtiger_Module_Model::getInstance($setype);
					}
					if(!in_array($moduleModels->get('presence'), $presence)){
						continue;
					}
					$label = $adb->query_result($rel_Results,0,'label');
					if($setype == 'Events' || $setype == 'Calendar'){
						$calendarRecordModel = Vtiger_Record_Model::getInstanceById($eventid);
						if($calendarRecordModel->get('activitytype') == 'Task'){
							$setype = 'Calendar';
						}else{
							$setype = 'Events';
						}
					}
					$row['eventid'] = array('value'=>vtws_getWebserviceEntityId($setype, $eventid),'label'=>html_entity_decode($label,ENT_QUOTES,$default_charset));
				}else{
					$row['eventid'] = array('value'=>'','label'=>'');
				}
			}else{
				$row['eventid'] = array('value'=>'','label'=>'');
			}

			if($row['createdtime'] != ''){
				$row['check_in_time'] = Vtiger_Util_Helper::convertDateTimeIntoUsersDisplayFormat($row['createdtime']);
			}
			if($row['modifiedtime'] != ''){
				$row['check_out_time'] = Vtiger_Util_Helper::convertDateTimeIntoUsersDisplayFormat($row['modifiedtime']);
			}
			if($row['employee_name'] != ''){
				$userRecordModel = Vtiger_Record_Model::getInstanceById($row['employee_name'],'Users');
				if(!empty($userRecordModel->get('user_name'))){
					$row['employee_name'] = array('value'=>vtws_getWebserviceEntityId('Users', $row['employee_name']),'label'=>html_entity_decode($userRecordModel->get('first_name').' '.$userRecordModel->get('last_name'),ENT_QUOTES,$default_charset));
				}else{
					$query = "SELECT groupname FROM vtiger_groups WHERE groupid = ?";
					$groupResults = $adb->pquery($query,array($row['employee_name']));
					$row['employee_name'] = array('value'=>vtws_getWebserviceEntityId('Groups', $row['employee_name']),'label'=>html_entity_decode($adb->query_result($groupResults,0,'groupname'),ENT_QUOTES,$default_charset));
				}
			}

			/*$total_time = $row['total_time'];

			$hours = floor($total_time / 3600);
		    $minutes = floor(($total_time / 60) % 60);
		    $seconds = $total_time % 60;

		    $user_total_time = "$hours:$minutes:$seconds";*/
			$row['attendance_status'] = vtranslate($row['attendance_status'],'CTAttendance');
			if(Users_Privileges_Model::isPermitted('CTAttendance', 'DetailView', $row['cttimetrackerid'])){
				array_push($data,array('ctattendanceid'=>$row['ctattendanceid'],'attendance_status'=>$row['attendance_status'],'employee_name'=>$row['employee_name'],'eventid'=>$row['eventid'],'check_in_time'=>$row['check_in_time'],'check_out_time'=>$row['check_out_time'],'check_in_location'=>$row['check_in_location'],'check_out_location'=>$row['check_out_location'],'check_in_address'=>$row['check_in_address'],'check_out_address'=>$row['check_out_address']));
			}
		}

		if($index && $size){
			if($recordsTotal > $index*$size){
				$isLast = false;
			}else{
				$isLast = true;
			}
		}


		$users = array();
		$USER_MODEL = Users_Record_Model::getCurrentUserModel();
		$AccessibleUsers = $USER_MODEL->getAccessibleUsers();
		foreach ($AccessibleUsers as $userid => $username) {
			array_push($users,array('id'=>$userid,'label'=>$username));
		}
		
		if(count($data) == 0){
			$message = $this->CTTranslate('No records found');
			$response->setResult(array('Data'=>array(),'code'=>404,'message'=>$message,'isLast'=>$isLast,'recordsTotal'=>$recordsTotal,'users'=>$users));
		}else{
			$response->setResult(array('Data'=>$data,'isLast'=>$isLast,'recordsTotal'=>$recordsTotal,'users'=>$users));
		}
		
		return $response;
	}
	
}
