<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');

class Holiday extends MY_Controller
{
	function __construct()
	{
		parent::__construct();

		if($this->logged_user = $this->session->userdata('user'))
		{
			$this->login->checkModuleAccess(4);

			$this->logged_module = $_SESSION['module_data'];

			$this->load->model('hr/model_holiday');
			$this->load->model('hr/model_leave_v3', 'model_leave');
			$this->load->model('admin/model_general');
			$this->load->model('admin/model_announcement');
		}
		else
		{
			redirect(base_url());
		}
	}

	function index($year = null) {
		log_message('error', 'index()');
		$year = $year ? $year : date('Y');
		$data = array(
			'summary' => $this->model_holiday->getSummary($year),
			'state_list' => $this->model_holiday->getStates(458), // hardcoded MY for now. use branch country code soon
			'year_list' => $this->model_holiday->getYears(),
			'holiday_list' => $this->model_holiday->getHolidays(array('a.year' => $year)),
			'page_setup' => $this->template->pageSetup('HR', '', 'Holiday'),
		);
		$this->template->view('hr/holiday/index', $data);	
	}

	function import(){
		log_message('error', 'import()');
		$data = $this->input->post();
		log_message('error', 'year: ' . $data['year']);

		$gApiKey = 'AIzaSyAQU6RJSPKvQisT9Xm3FdJ2q9lLz7dSmeE';
		$gCalUrl = 'https://www.googleapis.com/calendar/v3/calendars/en.malaysia%23holiday%40group.v.calendar.google.com/events?key=';
		$realHolidays = array();
		$aYear = $data['year'];

		// curl google calendar api
		$c = curl_init();
		curl_setopt( $c , CURLOPT_URL , $gCalUrl . $gApiKey);
		curl_setopt( $c , CURLOPT_USERAGENT, "Mozilla/5.0 (Linux Centos 7;) Chrome/74.0.3729.169 Safari/537.36");
		curl_setopt( $c , CURLOPT_RETURNTRANSFER, true);
		curl_setopt( $c , CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt( $c , CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt( $c , CURLOPT_TIMEOUT, 10000); // 10 sec
		$data = curl_exec($c);
		curl_close($c);

		$decodedData = json_decode($data);
		$holidays = $decodedData->items;
		log_message('error', 'holidays count: ' . count($holidays));
		foreach($holidays as $h){
			log_message('error', date('Y', strtotime($h->start->date)));
			if(is_numeric(stripos($h->description, "public")) && (date('Y', strtotime($h->start->date)) == $aYear)){
				// adjust end date. source + 1 to date for a one day holiday
				$tDate = date_create($h->end->date);
				date_sub($tDate, date_interval_create_from_date_string("1 days"));
				$h->end->date = date_format($tDate, 'Y-m-d');
				array_push($realHolidays, $h);
			}
		}
		log_message('error', 'real holidays count: ' . count($realHolidays));
		log_message('error', 'entry 1: ' . print_r($realHolidays[0], true));

		// get all states
		$states = $this->db->select('id, state, alt_name')->where('country_id', 458)->get('_ref__state')->result_array();

		$this->db->trans_begin();

		if(count($states) > 0){
			foreach($realHolidays as $rh){
				if($rh->status == 'confirmed'){
					$qData['year'] = $aYear;
					$qData['active'] = 0;
					$qData['type'] = !stripos($rh->description, 'in') ? 'national' : 'regional';
					$qData['name'] = $rh->summary;
					$qData['country_id'] = 458;
					$qData['original_start_date'] = $rh->start->date;
					$qData['original_end_date'] = $rh->end->date;
					$qData['created_by'] = $this->logged_user['id'];
					$qData['updated_by'] = $this->logged_user['id'];
					$qData['updated_ts'] = date('Y-m-d H:i:s');

					$stateIds = array();
					foreach($states as $s){
						if($qData['type'] == 'regional'){
							if(is_numeric(stripos($rh->description, $s['state'])) || ($s['alt_name'] && is_numeric(stripos($rh->description, $s['alt_name'])))){
								array_push($stateIds, $s['id']);
							}
						}else{
							// insert all
							array_push($stateIds, $s['id']);
						}
					}
					log_message('error', 'count: ' . count($stateIds)); 
					$qData['states'] = json_encode($stateIds);
	
					$insertedId = $this->model_general->insert('hr__holiday', $qData);
				}
			}
		}

		$this->db->trans_complete(); // commit/rollback
		if($this->db->trans_status() == FALSE){
			return $this->sendJsonResponse('Error', 'Failed to import data');
		}else{
			return $this->sendJsonResponse('Success', 'Data successfully imported');
		}
		
	}

	// broadcast changes? change also effected leave
	function update(){
		log_message('error', 'update()');
		$data = $this->input->post();
		log_message('error', 'updating holiday with id: ' . $data['id']);
		$data['updated_by'] = $this->logged_user['id'];
		$data['updated_ts'] = date('Y-m-d H:i:s');
		$broadcastOption = $data['broadcast_option'];
		unset($data['broadcast_option']);

		// get the holiday
		$theHoliday = $this->db->query('select * from hr__holiday where id = ?', array($data['id']))->row();
		log_message('error', 'updating holiday: ' . $theHoliday->name);

		// update db
		if($data['is_moved'] == 1){
			$activeDate = $data['moved_start_date'];
			$data['moved_by'] = $this->logged_user['id'];
			$data['moved_ts'] = date('Y-m-d H:i:s');
			log_message('error', 'moved start date: ' . $data['moved_start_date']);
		}else{
			$activeDate = $theHoliday->original_start_date;
			$data['moved_by'] = null;
			$data['moved_ts'] = null;
			$data['moved_remarks'] = null;
			$data['moved_start_date'] = null;
			$data['moved_end_date'] = null;
		}

		// only broadcast if is_moved changes
		if($broadcastOption > 0 && ($theHoliday->is_moved != $data['is_moved'])){
			if($broadcastOption == 3){
				// announcement
				$descStr = $theHoliday->name . ' holiday has been moved from ' .
					($data['is_moved'] == 1 ? (date_format(date_create($theHoliday->original_start_date), 'D, jS F Y')) : (date_format(date_create($theHoliday->moved_start_date), 'D, jS F Y'))) . // 1=from ori to moved, 0=from moved to ori
					' to ' .
					($data['is_moved'] == 1 ? (date_format(date_create($data['moved_start_date']), 'D, jS F Y')) : (date_format(date_create($theHoliday->original_start_date), 'D, jS F Y'))) . // 1=from ori to moved, 0=from moved to ori
					'. Please be noted.';

				log_message('error', 'creating announcement');
				$pubToDate = date_create(date("Y-m-d"));
				date_add($pubToDate, date_interval_create_from_date_string("7 days"));
				$insertData = array(
					'category_id'   => 4, // 5=general, 3=quotes, 4=policy update
					'header'    	=> 'Public Holiday Update',
					'description'  	=> $descStr,
					'dateFrom'    	=> date("Y-m-d"),
					'dateTo'		=> date_format($pubToDate, 'Y-m-d'),
					'publish'    	=> 0, // default to 0
					'createdBy' 	=> $this->logged_user['id']
				);
				
				$this->model_general->insert('announcement', $insertData);
				
			}else{
				if($broadcastOption >= 1){
					// email
					log_message('error', 'sending email');
				}
				if($broadcastOption == 2){
					// push messaging
					log_message('error', 'sending push messaging');
				}				
			}

			$data['last_broadcasted'] = date('Y-m-d H:i:s');
		}

		$this->model_general->update('hr__holiday', $data, array('id'=>$data['id']));

		// if is_moved changes. change also leave for non-maternity
		// log_message('error', 'checking overlapping leave with ' . $activeDate);
		// $applicationList = $this->model_leave->getOverlappingApplication($activeDate);
		// if($applicationList){
		// 	log_message('error', 'found ' . count($applicationList) . ' possible overlapping leaves');
		// 	// get overlapping leave
		// 	$olLeave = array();
		// 	foreach($applicationList as $app){
		// 		log_message('error', 'id: ' . $app['id']);
		// 		if($app['date_from'] == $app['date_to']){
		// 			// one day
		// 			if($activeDate == $app['date_from']){
		// 				array_push($olLeave, $app);
		// 				// process overlapping leave
		// 				// update application
						
		// 				// update allocation
		// 			}
		// 		}else{
		// 			// multiple day. check if activeDate is in between
		// 			if($activeDate >= $app['date_from'] && $activeDate <= $app['date_to']){
		// 				array_push($olLeave, $app);
		// 			}
		// 		}
		// 	}
		// 	log_message('error', 'ol leave: ' . count($olLeave));
			
		// }else{
		// 	log_message('error', 'no overlapping leaves');
		// }

		return $this->sendJsonResponse('Success', 'Holiday successfully updated');
	}

	// broadcast changes? change also effected leave
	function delete(){
		log_message('error', 'delete()');
		$data = $this->input->post();
		log_message('error', 'deleting holiday with id: ' . $data['id']);
		$data['is_delete'] = 1;
		$data['active'] = 0;
		$data['deleted_by'] = $this->logged_user['id'];
		$data['deleted_ts'] = date('Y-m-d H:i:s');

		$this->model_general->update('hr__holiday', $data, array('id'=>$data['id']));

		return $this->sendJsonResponse('Success', 'Holiday successfully deleted');
	}

	function sendJsonResponse($status, $message){
		print json_encode(array(
			"status" => $status,
			"msg"	 => $message
		));
	}

}