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

class Model_holiday extends CI_Model {
	function __construct() {
		parent::__construct();
	}

	// called by cron or manually. MY only for now
	function getApiData($year){
		log_message('error', 'getApiDate()');

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

		// 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){
			if(is_numeric(stripos($h->description, "public")) && (date('Y', strtotime($h->start->date)) == $currentYear)){
				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')->where('country_id', 458)->get('_ref__state')->result_array();

		if(count($states) > 0){
			foreach($realHolidays as $rh){
				if($rh['status'] == 'confirmed'){
					$qData['year'] = $currentYear;
					$qData['active'] = 0;
					$qData['type'] = !stripos($rh['description'], 'in') ? 'national' : 'regional';
					$qData['name'] = $rh['summary'];
					$qData['original_start_date'] = $rh->start->date;
					$qData['original_end_date'] = $rh->end->date;
					$qData['created_by'] = $this->logged_user['id'];

					$insertedId = $this->model_general->insert('hr__holiday', $qData);
				}
			}
		}

		return $realHolidays;
	}

	function getStates($c){
		log_message('error', 'getStates()');
		$this->db->select('id, state')->where('country_id', $c); 
		$this->db->order_by('state', 'asc');
		$query = $this->db->get('_ref__state');

		log_message('error', $this->db->last_query());
		return ($query->num_rows() > 0) ? $query->result_array() : null;
	}

	function getYears(){
		log_message('error', 'getYears()');
		$this->db->select('distinct(a.year)'); 
		$this->db->order_by('a.year', 'asc');
		$query = $this->db->get('hr__holiday a');

		log_message('error', $this->db->last_query());
		return ($query->num_rows() > 0) ? $query->result_array() : null;
	}

	// get upcoming holidays. national vs regional counts
	function getSummary($year){
		log_message('error', 'getSummary()');

		$obj1 = $this->db->query(
			'select (select count(*) from hr__holiday where type=? and year=? and is_delete=0 and active=1) as count_national, 
			(select count(*) from hr__holiday where type=? and year=? and is_delete=0 and active=1) as count_regional from hr__holiday group by year'
		, array('national', $year, 'regional', $year))->row();
		if(!$obj1){
			$obj1 = new stdClass();
			$obj1->count_national = 0;
			$obj1->count_regional = 0;
		}
		$obj2 = $this->db->query(
			'select id as next_id, name as next_name, if(is_moved=1,moved_start_date,original_start_date) as next_date 
			from hr__holiday where year=? and active=1 and is_delete=0 and if(is_moved=1,moved_start_date > now(),original_start_date > now()) order by next_date limit 1;'
		, array($year))->row();
		if(!$obj2){
			$obj2 = new stdClass();
			$obj2->next_id = null;
			$obj2->next_name = null;
			$obj2->next_date = null;
		}
		$mainObj = (object) array_merge((array) $obj1, (array) $obj2);
		return $mainObj;
	}

	// filtered
	function getHolidays($filters = array()){
		log_message('error', 'getHolidays()');
		$this->db->select('a.*'); 
			
		if(!empty($filters)){
			foreach ($filters as $filter => $value) {
				$this->db->where($filter, $value);
			}
		}

		$this->db->where('a.is_delete', 0);
		$this->db->order_by('a.original_start_date', 'asc');
		$query = $this->db->get('hr__holiday a');

		// for each, convert json_encoded states id to strings

		log_message('error', $this->db->last_query());
		return ($query->num_rows() > 0) ? $query->result_array() : null;
	}

	// for leave. temp till merge with above
	public function getHolidays2($cId, $sId, $y){
		log_message('error', 'getHolidays2()');
		log_message('error', 'getting holidays for: ' . $cId . ' ' . $sId . ' ' . $y);

		$q = $this->db->query('
			SELECT *
			FROM hr__holiday
			WHERE is_delete=0
			AND active=1
			AND country_id = ?
			AND states like ?
			AND year = ?
			ORDER BY original_start_date ASC
		', array($cId, '%' . $sId . '%', $y));
		
		log_message('error', $this->db->last_query());
		log_message('error', 'rows: ' . count($q->result_array()));
		return $q->result_array();
	}

	function cloneHolidays(){
		
	}

}