<?
	include_once("config.php");
	class Schedule extends Fly5 {
		function fetchBeds($a)
		{
			$result = query("select * from s4wardmember 
				join uis.terminal on terminalno=terminal.no
				join s4ward on wardno=s4ward.no and terminalno=terminal.no
			where s4ward.hid=:hid and s4ward.name=:wardname", $a);
			return $result;
		}
		function dispatch($a)
		{
			$receivers = json_decode($a[receivers], true);
			if(!$receivers || count($receivers) == 0) {
				$recievers = array();
				$rows = query("select * from uis.terminal where 서비스코드=:hid", $a);
				foreach($rows as $t)
				{
					$r = array(
						hid=>$a[hid],
						room=>$t[room],
						bedno=>$t[bedno],
					);
					array_push($receivers, $r);
				}
			} 
			//고성능필요
			$pdo = pdo();
			$dbh = $pdo->prepare("insert into mail 
					(hid, room, bedno, content, mailtype)
					values
					(:hid, :room, :bedno, :content, :mailtype)");
			foreach($receivers as $r)
			{
				$r[content] = $a[content];
				$r[mailtype] = $a[noticekind];
				/*
				query("insert into mail 
					(hid, room, bedno, content, mailtype)
					values
					(:hid, :room, :bedno, :content, :mailtype)", $r);
				*/
				$dbh->execute($r);
			}
			return $receivers;
		}
		function createSchedule($a)
		{
			if($a[repeateveryday])
				$a[repeateveryday] = 1;//정수화
			$all = array();
			if ($a[receivers]) {
				if(!is_array($a[receivers])) {
					$a[receivers] = json_decode($a[receivers], true);
				}
				foreach($a[receivers] as $r) {
					if(!is_array($r)) {
						$r = json_decode($r, true);
					}
					array_push($all, array(
						hid=>$a[hid],
						room=>$r[room],
						bedno=>$r[bedno],
					));
				}
			}
			$a[receivers] = json_encode2($all);
			if(!$a[content]) {
				$content = array(
					note=>$a[noticenote],
					filename=>$a[filename],
				);
				$a[content] = json_encode2($content);
			}
			
			if ($a[scheduled]) {
				$a[contenthash] = sha1("$a[receivers] $a[content] $a[dispatchtime] $s[hid] $a[repeateveryday] $a[noticekind]");
				try {
					query("insert into 
						s4schedule 
							(hid, noticekind, receivers, dispatchtime, repeatinterval, expiredate, memo, content, contenthash, repeateveryday, spawned, parentno)
						values
							(:hid, :noticekind, :receivers, :dispatchtime, :repeatinterval, :expiredate, :noticememo, :content, :contenthash, :repeateveryday, :spawned, :parentno)
					", $a);
				} catch(Exception $e){
					if (strpos($e->getMessage(), "for key 'contenthash'") !== false)
						return array(info=>"이미 예약된 스케줄 입니다.\n".$a[contenthash]);
					else {
						throw $e;
					}
				}
			} else {
				return $this->dispatch($a);
			}
			return $a;
		}
		function execute(&$view, $path, $args)
		{
			$a = $_REQUEST;
			switch($path) {
			case "Schedule/api/processSchedules":
				$result = $this->processSchedules($a);
				break;
			case "Schedule/api/expandSchedules":
				$result = $this->expandSchedules($a);
				break;
			case "Schedule/api/createSchedule":
				$result = $this->createSchedule($a);
				break;
			case "Schedule/api/statusDelete":
				$result = $this->statusDelete($a);
				break;
			case "Schedule/api/statusEnabled":
				$result = $this->statusEnabled($a);
				break;
			case "Schedule/api/statusAbled":
				$result = $this->statusAbled($a);
				break;
			case "Schedule/api/fetchBeds":
				$result = $this->fetchBeds($a);
				break;
			case "Schedule/api/buildWards":
				$result = $this->buildWards($a);
				break;
			case "Schedule/api/fetch":
				$result = $this->fetch($a);
				break;
			case "Schedule/api/search":
				$result = $this->searchMsg($a);
				break;
			default:
				$view = "$path.pug";
				return;
			}
			reply_json($result);
		}
		function updateWardTerminal($a)
		{
			query("insert into s4ward (hid, name) values(:hid, :wardname)
				on duplicate key update no=no", $a);
			$w = query("select no from s4ward where hid=:hid and name=:wardname", $a)[0];
			$a[wardno] = $w[no];
			query("insert into s4wardmember (wardno, terminalno)
				values (:wardno, :terminalno)
				on duplicate key update no=no", $a);
		}
		function buildWardsByRoomNo($a)
		{
			$rows = query("select no, room from uis.terminal where 서비스코드=:hid", $a);
			$wards = array();
			foreach($rows as $r) {
				if (!is_numeric($r[room])) {
					$r[wardname] = "기타";
				} else {
					$w = substr($r[room], 0, strlen($r[room])-2);
					$r[wardname] = $w;
				}
				if(!$w) continue;
				$r[hid] = $a[hid];
				$r[terminalno] = $r[no];
				$this->updateWardTerminal($r);
			}
		}
		function buildWards($a)
		{
			$a[hid] = 'IM39';
			$rows = query("select * from wardmap");
			$wards = array();
			query("delete from s4ward where hid=:hid", $a);
			$n=0;
			foreach($rows as $r) {
				query("insert into s4ward (hid, name)
					values(:hid, :ward)
					on duplicate key update no=no", $r);
				$rows = query("select * from s4ward where hid=:hid and name=:ward", $r);
				$ward = $rows[0];
				//$r[hid] = $a[hid];
				$rows = query("select * from uis.terminal where room=:room and bedno=:bedno and 서비스코드=:hid", $r);
				$t = $rows[0];
				if(!$t) {
					echo "Warning: terminal not found [$r[room] - $r[bedno]]\n";
					continue;
				}
				query("insert into s4wardmember
						(wardno, terminalno)
					values
						(:wardno, :terminalno)
					on duplicate key update no=no", array(
					wardno=>$ward[no],
					terminalno=>$t[no],
				));
				$n++;
			}
			echo "$n terminals\nok";
		}
		/*function fetchJobs($hid)
		{
			$rows = query("select * from s4job where hid=:hid", array(
				hid=>$hid,
			));
			return $rows;
		}*/
		function main(&$view)
		{
			$view = 'Schedule/main.pug';
			return array(
				cookies=>$_COOKIE,
				noticekinds=>query("select * from s4noticekind"),
				//jobs=>$this->fetchJobs($_COOKIE[hid]),
				wards=>query("select * from s4ward where hid=:hid", $_COOKIE),
			);
		}
		function mainProto(&$view) 
		{
			$view = "Schedule/main-proto.pug";
			return $this->main($view);
		}
		function fetch($a)
		{
			$selectType = query("SELECT * FROM s4noticekind ", $a);
			//$schedules = query("Select no, noticenote, noticekind, dispatchtime, repeatinterval, enabled,receivers,memo  from s4schedule where hid=:hid and deleted = 0  ", $a);
			$schedules = query("Select * from s4schedule where hid=:hid and deleted = 0  ", $a);
			return array(
					schedules => $schedules,
					selectType => $selectType,
             );
		}
		function statusDelete($a)
		{
			$rows = query("update s4schedule set deleted=1 where no=:no", $a);
			return $rows;
		}
		function statusEnabled($a)
		{
			
			$rows = query("update s4schedule set enabled=0 where no=:no", $a);
			
			return $rows;
		}
		function statusAbled($a)
		{
			
			$rows = query("update s4schedule set enabled=1 where no=:no", $a);
			
			return $rows;
		}
		
		function searchMsg(&$view){
			
			$a = $_REQUEST;
			$a[hid] = 'IM39';
			$selectType ='';
			$date ='';
			
			if($a[selectType] && $a[selectType]!=='전체')
				$selectType = "and noticekind=:selectType";
			if($a[startDate])
				$sdate = " and date_format(creationtime,'%Y-%m-%d') >= :startDate";
			if($a[endDate])
				$edate = " and date_format(creationtime,'%Y-%m-%d') <= :endDate";
			
			$schedules = query("SELECT * FROM s4schedule WHERE hid=:hid and deleted = 0 $selectType $sdate $edate ORDER BY creationtime DESC",$a);
			return array(
					schedules => $schedules,
					startDate => $a[startDate],
					endDate => $a[endDate],
			);
		}
		
		function file_post_contents($url, $data)
		{
			$postdata = json_encode($data);
			$opts = array('http' =>
				array(
					'method'  => 'POST',
					//'header'  => 'Content-type: application/json',//'application/x-www-form-urlencoded'
					'header'  => 'Content-type: application/x-www-form-urlencoded',
					'content' => $postdata,
				)
			);
			$context = stream_context_create($opts);
			return file_get_contents($url, false, $context);
		}	
		
		/**
			1회 예약 스케줄을 즉시 변환 스케줄로 변경
		*/		
		function processSchedules()
		{
			// 반복 없는 예약 
			$rows = query("select * from s4schedule where
				deleted=0 and enabled=1 and repeateveryday=0 and 
				dispatchtime <= NOW()
				");
			$n = 0;
			$result = array();
			foreach($rows as $s) {
				$s[scheduled] = false;
				$this->createSchedule($s);
				query("update s4schedule set deleted = 1 where no=:no", $s);
				array_push($result, $s);
				$n++;
				if ($n>3) // 다음에 처리
					break;
			}
			return $result;			
		}
		/**
			그날의 반복 예약 스케줄을 1회 예약스케줄로 변경하여 insert
		*/
		function expandSchedules()
		{
			$rows = query("select * from s4schedule where
				deleted=0 and enabled=1 and repeateveryday<>0");
			foreach($rows as $s) {
				//if($s[repeateveryday]) {
				echo "spawned\n";
				$t = explode(' ', $s[dispatchtime])[1];
				$dt = date("Y-m-d ").$t;
				$s[repeateveryday] = 0;
				$s[scheduled] = true;
				$s[dispatchtime] = $dt;
				$s[spawned] = 1;
				$s[parentno] = $s[no];
				$this->createSchedule($s);
				//}
			}
			//return $rows;
		}
	}