<?php
App::uses('AppController', 'Controller');	
/**
 * Controller name
 *
 * @var string
 */

class FunctionsController extends AppController {
	function beforeFilter(){
		$this->Auth->allow();
	}
	
	function _updateAttendance($call){
		//pr('a'); die();
		$data = array();
		$date =date('Y-m-d',strtotime($call['date']));
		$time =date('H:i:s',strtotime($call['date']));
		
		$this->loadModel('Attendance');
		
		//$attendance = $this->Attendance->find('first', array('conditions'=>array('user_id'=>$call['user_id'], 'date'=>$date)));
		
		$attendances = $this->Attendance->find('all', array('conditions'=>array('user_id'=>$call['user_id'], 'date'=>$date),'order' => array('punch_time'=>'DESC')));
		
		if(empty($attendances) ){
			$data['Attendance'] = array(
				'user_id'=> $call['user_id'],
				'emp_id'=> $call['emp_id'], 
				'company_id'=> HRMS_COMPANY_ID, 
				'is_present' =>1,
				'in_time'=> $time, 
				'punch_time'=> $call['date'], 
				'date'=>$date);
			$this->Attendance->save($data);
		}
		else{
			$count = count($attendances);
			$attendance = $attendances[0];
			
			if($count == 1){
				$data['Attendance'] = array(
				'user_id'=> $call['user_id'],
				'emp_id'=> $call['emp_id'], 
				'company_id'=> HRMS_COMPANY_ID, 
				'is_present' =>1,
				'out_time'=> $time, 
				'punch_time'=> $call['date'], 
				'date'=>$date);
			}else{
				$data['Attendance'] = array(
				'id'=> $attendance['Attendance']['id'],
				'out_time'=> $time, 
				'punch_time'=> $call['date']);
			}
			
			$this->Attendance->save($data);
			
			
		}
		
	}
	
	function _updateAttendanceFirstLogin($call){
		//pr('a'); die();
		$data = array();
		$date =date('Y-m-d',strtotime($call['date']));
		$time =date('H:i:s',strtotime($call['date']));
		
		$this->loadModel('Attendance');
		
		$attendance = $this->Attendance->find('first', array('conditions'=>array('user_id'=>$call['user_id'], 'date'=>$date)));
		
		if(empty($attendance) ){
			$data['Attendance'] = array(
				'user_id'=> $call['user_id'],
				'emp_id'=> $call['emp_id'], 
				'company_id'=> HRMS_COMPANY_ID, 
				'is_present' =>1,
				'in_time'=> $time, 
				'punch_time'=> $call['date'], 
				'date'=>$date,
				'first_login'=>1);
			$this->Attendance->save($data);
		}
		
	}
	
	
}