<?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_CTTimeTracker extends CTMobile_WS_Controller {
	
	function process(CTMobile_API_Request $request) {
		global $adb,$current_user; // Required for vtws_update API
		$current_user = $this->getActiveUser();
		$user = Users::getActiveAdminUser();
		$module = 'CTTimeTracker';
		$recordid = trim($request->get('record'));
		$tracking_title = trim($request->get('tracking_title'));
		$tracking_notes = trim($request->get('tracking_notes'));
		$module_name = trim($request->get('module_name'));
		$related_to = trim($request->get('related_to'));
		$tracking_user = trim($request->get('tracking_user'));
		$is_start_tracking = trim($request->get('is_start_tracking'));
		$old_record = trim($request->get('old_record'));
		$is_edit = trim($request->get('is_edit'));
		$latitude = trim($request->get('latitude'));
		$longitude = trim($request->get('longitude'));
		$check_in_address = trim($request->get('check_in_address'));
		$check_out_address = trim($request->get('check_out_address'));
		
		$response = new CTMobile_API_Response();

		try {
			$nowInDBFormat = date('Y-m-d H:i:s');
			// Set the initial values
			$checkin_status = false;
			define("SECONDS_PER_HOUR", 60*60);
			// Retrieve or Initalize
			if (!empty($recordid)) {
				$mode = 'edit';
				$arrRecordId = explode('x',$recordid);
				$recordModel = Vtiger_Record_Model::getInstanceById($arrRecordId[1], $module);
				$recordModel->set('id', $arrRecordId[1]);
				$recordModel->set('mode', 'edit');

				if($is_start_tracking == true && $is_start_tracking != 'false'){
					list($date_start, $time_start) = explode(' ',  $nowInDBFormat);
					$TimeContRecordModel = Vtiger_Record_Model::getCleanInstance('CTTimeControl');
					$TimeContRecordModel->set('mode', '');
					$TimeContRecordModel->set('date_start', $date_start);
					$TimeContRecordModel->set('time_start', $time_start);
					$TimeContRecordModel->set('related_tracking', $arrRecordId[1]);
					$TimeContRecordModel->set('assigned_user_id', $current_user->id);
					$TimeContRecordModel->set('check_in_location', "$latitude,$longitude");
					$TimeContRecordModel->set('check_in_address', $check_in_address);
					$TimeContRecordModel->save();
					$recordModel->set('tracking_status', 'Start');
				}else{
					if($is_edit != true){
						list($date_end, $time_end) = explode(' ', $nowInDBFormat);
						$recordModel->set('tracking_status', 'End');
						$checkin_status = false;

						$record =  explode('x', $recordid);
						$timeControlQuery = "SELECT * FROM vtiger_cttimecontrol INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_cttimecontrol.cttimecontrolid WHERE vtiger_crmentity.deleted = 0 AND vtiger_cttimecontrol.related_tracking = ? ";
						$timeControlResult = $adb->pquery($timeControlQuery,array($record[1]));
						$num_rows = $adb->num_rows($timeControlResult);
						
						$difference = 0;
						for($i=0;$i<$num_rows;$i++) {
							$start_date = $adb->query_result($timeControlResult,$i,'date_start');
							$start_time = $adb->query_result($timeControlResult,$i,'time_start');
							$end_date = $adb->query_result($timeControlResult,$i,'date_end');
							$end_time = $adb->query_result($timeControlResult,$i,'time_end');
							if($end_date == '' && $end_time == ''){
								$cttimecontrolid = $adb->query_result($timeControlResult,$i,'cttimecontrolid');
								$end_date = $date_end;
								$end_time = $time_end;
								$startdatetime1 = strtotime($start_date.' '.$start_time);
								$enddatetime1 = strtotime($end_date.' '.$end_time);
								$duration = $enddatetime1 - $startdatetime1;
							}

							$startdatetime = strtotime($start_date.' '.$start_time);
						    // calculate the end timestamp
						    $enddatetime = strtotime($end_date.' '.$end_time);
						    // calulate the difference in seconds
						    $difference = $difference + ($enddatetime - $startdatetime);
						}
						
						if($cttimecontrolid != ''){
							$TimeContRecordModel = Vtiger_Record_Model::getInstanceById($cttimecontrolid, 'CTTimeControl');
							$TimeContRecordModel->set('id', $cttimecontrolid);
				            $TimeContRecordModel->set('mode', 'edit');

				            $TimeContRecordModel->set('date_end', $date_end);
				            $TimeContRecordModel->set('time_end', $time_end);
				            $TimeContRecordModel->set('check_out_location', "$latitude,$longitude");
				            $TimeContRecordModel->set('check_out_address', $check_out_address);
				            $TimeContRecordModel->set('check_out_address', $check_out_address);
				            $TimeContRecordModel->set('duration', $duration);

				            if($tracking_notes != ''){
								$TimeContRecordModel->set('tracking_notes', $tracking_notes);
							}
				            $TimeContRecordModel->save();
						}
						
					    $totalTime = $difference;

					    $hours = gmdate("H", $totalTime);
						$minutes = gmdate("i", $totalTime);
						$seconds = gmdate("s", $totalTime);

					    // output the result
					    $duration = $hours . " hr " . $minutes . " min";
					    $recordModel->set('total_time', $totalTime);
					    $recordModel->set('total_hour', $hours);
					    $recordModel->set('total_min', $minutes);
					    $recordModel->set('total_seconds', $seconds);
					}
				}

				if($tracking_title != ''){
					$recordModel->set('tracking_title', $tracking_title);
				}
				
				$check_in_time = "";
				$check_out_time = "";
				if($is_start_tracking == true && $is_start_tracking != 'false'){
					if($recordModel->get('check_in_location') == '' && $recordModel->get('check_in_address') == ''){
						$recordModel->set('check_in_location', "$latitude,$longitude");
						$recordModel->set('check_in_address', $check_in_address);
					}
				}else{
					$recordModel->set('check_out_location', "$latitude,$longitude");
					$recordModel->set('check_out_address', $check_out_address);
				}
				$recordModel->save();
				$moduleWSId = CTMobile_WS_Utils::getEntityModuleWSId($module);
				$lastInsertId = $recordModel->getId();
				$lastInsertWSId= $moduleWSId.'x'.$lastInsertId;
				//$this->recordValues = vtws_update($this->recordValues, $user);
				if($is_start_tracking == true && $is_start_tracking != 'false'){
					
					$message = $this->CTTranslate('Time Tracking started successfully');
					$duration = "0 hr 0 min";
					$check_in_time = Vtiger_Datetime_UIType::getDisplayDateTimeValue($recordModel->get('date_start').' '.$recordModel->get('time_start'));
				}else{
					if($is_edit != true){
						$message = $this->CTTranslate('Time Tracking ended successfully');
						$check_in_time = Vtiger_Datetime_UIType::getDisplayDateTimeValue($recordModel->get('date_start').' '.$recordModel->get('time_start'));
						$check_out_time = Vtiger_Datetime_UIType::getDisplayDateTimeValue($recordModel->get('date_end').' '.$recordModel->get('time_end'));
					}else{
						$message = $this->CTTranslate('Time Tracking updated successfully');
					}
				}

			}else {
				$mode = 'create';
				$recordModel = Vtiger_Record_Model::getCleanInstance($module);
				$recordModel->set('mode', '');

				list($date_start, $time_start) = explode(' ',  $nowInDBFormat);
				
				$recordModel->set('tracking_title', $tracking_title);
				//$this->recordValues['tracking_notes'] = $tracking_notes;
				$tracking_user_id = substr($tracking_user, stripos($tracking_user, 'x')+1);
				$recordModel->set('tracking_user', $tracking_user_id);
				$recordModel->set('assigned_user_id', $current_user->id);
				$related_to_id = substr($related_to, stripos($related_to, 'x')+1);
				$recordModel->set('related_to', $related_to_id);
				if($is_start_tracking == true && $is_start_tracking != 'false'){
					$recordModel->set('tracking_status', 'Start');
					$recordModel->set('check_in_location', "$latitude,$longitude");
					$recordModel->set('check_in_address', $check_in_address);
					$checkin_status = true;
				}else{
					$checkin_status = false;
				}
				$recordModel->save();
				$moduleWSId = CTMobile_WS_Utils::getEntityModuleWSId($module);
				$lastInsertId = $recordModel->getId();
				$lastInsertWSId= $moduleWSId.'x'.$lastInsertId;
				if($is_start_tracking == true && $is_start_tracking != 'false'){
					$TimeContRecordModel = Vtiger_Record_Model::getCleanInstance('CTTimeControl');
					$TimeContRecordModel->set('mode', '');
					$TimeContRecordModel->set('date_start', $date_start);
					$TimeContRecordModel->set('time_start', $time_start);
					$TimeContRecordModel->set('related_tracking', $lastInsertId);
					$TimeContRecordModel->set('assigned_user_id', $current_user->id);
					$TimeContRecordModel->set('check_in_location', "$latitude,$longitude");
					$TimeContRecordModel->set('check_in_address', $check_in_address);
					$TimeContRecordModel->save();
				}
				$check_in_time = "";
				if($is_start_tracking == true && $is_start_tracking != 'false'){
					$message = $this->CTTranslate('Time Tracking started successfully');
					$check_in_time = Vtiger_Datetime_UIType::getDisplayDateTimeValue($date_start.' '.$time_start);
				}else{
					$message = $this->CTTranslate('Time Tracking saved successfully');
				}
				$check_out_time = "";
			    $duration = "0 hr 0 min";
			}
			
			

			if($is_edit != true){
				$response->setResult(array('id'=>$lastInsertWSId,'tracking_status'=>$checkin_status,'message'=>$message,'track_in_time'=>$check_in_time,'track_out_time'=>$check_out_time,'duration'=>$duration));
			}else{
				$response->setResult(array('id'=>$lastInsertWSId,'message'=>$message));
			}
			
		} catch(Exception $e) {
			$response->setError($e->getCode(), $e->getMessage());
		}
		return $response;
	}
	
}
