<?
	include_once("config.php");
	class Diet extends Fly5 {
		function fetchRepeats($a)
		{
			//echo "diet fetch";
			$a[hid] = 'im39';
			$seq = query("
				select * from 
					diet
					left join meal on diet.no=dietno
					where 
						diet.name=:dietname and hid=:hid and isnull(date)
					order by
						seq", $a);
			$firstdate = date_create("2001-01-01");
			$date = $a[date];
			if(!$date)
				$date = date("Y-m-d");
			$date = date_create($date);
			$days = $date->diff($firstdate)->days;
			
			$result = array();
			for($i = 0; $i < count($seq); $i++) {
			// for($i = 0; $i < 1; $i++) {
				// $t = $seq[($days+$i)%count($seq)];
				$t = $seq[$i];
				$menu = $this->parseMealsTime($t[menu]);
				$t[menu] = array();
				for($j=0; $j<count($menu); $j++)
					$t[menu][$j] = $menu[$j];
				$t[date] = $date->format("Y-m-d");
				$t[seq] = $i+1;
				unset($t[creationtime]);
				$date->add(new DateInterval('P1D'));
				array_push($result, $t);
			}
			return $result;
		}
		
		function fetchSpecials($a)
		{
			//echo "diet fetch";
			$a[hid] = 'im39';
			$seq = query("
				select * from 
					diet
					left join meal on diet.no=dietno
					where 
						diet.name=:dietname and hid=:hid and not isnull(date)
					", $a);
			for($i = 0; $i < count($seq); $i++) 
			{
				$t = $seq[$i];
				$menu = $this->parseMealsTime($t[menu]);
				$t[menu] = array();
				for($j=0; $j<count($menu); $j++)
				{
					$t[menu][$j] = $menu[$j];
					// echo $menu[$j];
				}
				$seq[$i] = $t;
			}
			return $seq;
		}
		
		function fetchMonthlyMeals($a)
		{
			$a[hid]='im39';
			$seq = query("
				select * from 
					diet
					left join meal on diet.no=dietno
					where 
						diet.name=:dietname and hid=:hid and isnull(date)
					order by
						seq", $a);
			$firstdate = $seq[0][firstdate];
			$timestamp = new DateTime($firstdate); //기준일
			$now_time = new DateTime($a[day]); //오늘 날짜
			$datediff = date_diff($timestamp, $now_time); //기준일과 오늘 차이
			$mealCount = count($seq); //식단별 식사 개수
			$dated = $datediff->format('%r%a');
			$days = $dated+$mealCount;
			
			$ck = $days%$mealCount; //차이가 8배수 되면 0으로 리셋
			$today = date('w',strtotime($a[day])); //요일 (숫자로 표시됨 : 일 = 0, 월 = 1, ... , 토 = 6)
			//$week = array("일","월","화","수","목","금","토"); //요일 한글표시용 배열
			$j = $ck%$mealCount; //식단 요일 체크
			//echo $today;
			//echo $
			for($i=0; $i<30; $i++){
				if($j % $mealCount == 0)
					$j = 0;
				$lists[$i] = $seq[$j][menu];
				$j++;
				//$ck = ($ck+1)%$mealCount;
			}
			$array = $lists;
			
			$specialMeals = query("select * from diet a left join meal b on a.combowith = b.dietno 
				where a.name=:dietname and hid=:hid and isnull(date) order by seq", $a);
			
			if($a[dietname] ==='소아식' || $a[dietname]==='유아식'){
				
				$j = $today; // 요일	
				for($i=0; $i<30; ){
						if($j>7){
							$j=1; //요일 초기화
						}
						if($j==1||$j==3||$j==5){ // 월수금
								$stest = array();
								$temp= explode('$',$array[$i]);
								$lunch = preg_split("/\r\n|\n|\r/",$temp[2]);

								if($j==1)//월요일
									$stest = preg_split("/\r\n|\n|\r/",$specialMeals[0][menu]);
								if($j==3)//수요일
									$stest = preg_split("/\r\n|\n|\r/",$specialMeals[1][menu]);
								if($j==5)//금요일
									$stest = preg_split("/\r\n|\n|\r/",$specialMeals[2][menu]);
								
								$stest[2] = $lunch[2];
								$temp[2] = implode("\n",$stest);
								$array[$i] = implode('$', $temp);
								
						}
						$i++;
						$j++;
				}
				
		 }
		 else if ($a[dietname] ==='일반식(선택식)' || $a[dietname] ==='일반식/선택식'){
				$j = $today;
				//echo $j;
				for($i=0; $i<30; ){
						if($j>7){
							$j=1; //요일 초기화
						}
						$stest = array();
						//echo $j;
						if($j==6 || $j==7 || $j==0){//토요일 
							$stest = preg_split("/\r\n|\n|\r/",$specialMeals[0][menu]);
							
							//$stest[2] = $lunch[2];
							$temp[0] = implode("\n",$stest);
							$array[$i] = implode('$', $temp);
							
							//$array[$i+1] = null;
							
						}
						$i++;
						$j++;
				}
				
		 }
			
			return $array;
		}
		
		function parseMealsTime($array)
		{
			$result = $array;
			$temp = array();
			
			if(count($array)>1)
			{
				for($i=0 ; $i<count($array) ; $i++)
				{
					$dayMeal = $array[$i];
					
					$r = array();
					$lines = explode("$", $dayMeal);
					foreach($lines as $l) {
						if(!empty($l))
						{
							array_push($r, $l);
						}
					}
					$temp[$i] = $r;
				}
			}
			else
			{
				// echo $array."@@@@@@@@@";
				// echo "test";
				$r = array();
				$lines = explode("$", $array);
				foreach($lines as $l) {
					if(!empty($l))
					{
						array_push($r, $l);
					}
				}
				for($i=0; $i<count($r); $i++)
				{
					$temp[$i] = $r[$i];
					// echo $r[$i];
				}
			}
			return $temp;
		}
		
		function fetchMeals($a)
		{
			$specials = $this->fetchSpecials($a);
			$repeat = $this->fetchRepeats($a);
			
			// $repeats = $this->parseMealsTime($repeat->menu);
			
			// echo $repeats;
			
			return array(
				specials=>$specials,
				repeats=>$repeat,
			);
		}
		function fetchPreview($a)
		{
			$a[daycount] = date('t', strtotime($a[day]));
			// echo $a[daycount];
			$meals = array(
				specials=>$this->fetchSpecials($a),
				repeats=>$this->fetchRepeats($a),
			);
			
			$monthlyMeals = $this->fetchMonthlyMeals($a);
			
			$result = $this->parseMealsTime($monthlyMeals);
			
			return $result;
		}
		function execute(&$view, $path, $args)
		{
			$a = $_REQUEST;
			switch($path) {
			case "Diet/api/fetchDietInfo":
				$result = $this->fetchDietInfo($a);
				break;
			case "Diet/api/fetch":
				$result = $this->fetch($a);
				break;
			case "Diet/api/searchSummary":
				$result = $this->searchSummary($a);
				break;
			case "Diet/api/cancelMeal":
				$result = $this->cancelMeal($a);
				break;
			case "Diet/api/cancelGihodo":
				$result = $this->cancelGihodo($a);
				break;
			case "Diet/api/searchMeal":
				$result = $this->searchMeal($a);
				break;
			case "Diet/api/fetchOrders":
				$result = $this->fetchOrders($a);
				break;
			case "Diet/api/fetchGihodo":
				$result = $this->fetchGihodo($a);
				break;
			case "Diet/api/fetchMeals":
				$result = $this->fetchMeals($_REQUEST);
				break;
			case "Diet/api/fetchPreview":
				$result = $this->fetchPreview($_REQUEST);
				break;
			case "Diet/api/putMeal":
				query("update meal set menu=:menu
					where no=:mealno and dietno=:dietno", $a);
					$result = 'ok';
				break;
			case "Diet/api/putDiet":
				query("update diet set info=:info
					where no=:dietno", $a);
					$result = 'ok';
				break;
			case "Diet/api/putDate":
				query("update diet set firstdate=:firstdate
					where no=:dietno", $a);
					$result = 'ok';
				break;
			case "Diet/api/parseDiet":
				$result = $this->parseMealsTime($_REQUEST);
				break;
			default:
				$view = "$path.pug";
				return;
			}
			reply_json($result);
		}
		function fetchDiets($hid)
		{
			$rows = query("select * from diet");
			return $rows;
		}
		function main(&$view)
		{
			$view = 'Diet/main.pug';
			return array(
				diets=>$this->fetchDiets('im39'),
				meal=>$this->fetchMeals(array(
					dietname=>'일반식',
				)),
			);
		}
		function mainProto(&$view) 
		{
			$view = "Diet/main-proto.pug";
			return $this->main($view);
		}
		function preview(&$view)
		{
			$view = 'Diet/preview.pug';
			return array(
				diets=>$this->fetchDiets('im39'),
				meal=>$this->fetchMeals(array(
					dietname=>'일반식',
				)),
			);
		}
		
		function cancelMeal(&$view){
			$a = $_REQUEST;
			$rows = query("update mealorder set canceled=-1 where no=:choiceno",$a);
			return $rows;
			
		}
		
		function cancelGihodo(&$view){
			$a = $_REQUEST;
			$rows = query("update mealorder set canceled=-1 where patientno=:choiceno",$a);
			return $rows;
			
		}
		
		function searchMeal(&$view){
			
			$a = $_REQUEST;
			$selectType ='';
			$selectTime ='';
			$date ='';
			
			if($a[selectType] && $a[selectType]!=='전체')
				$selectType = "and  d.dietname=:selectType";
			if($a[selectWard] && $a[selectWard]!=='전체')
				$selectWard = "and  ward=:selectWard";
			if($a[selectOptionType] && $a[selectOptionType]!=='전체')
				$selectType = "and  d.mealtype=:selectOptionType";
			if($a[selectOptionType] && $a[selectOptionType]==='보호자식')
				$selectType = "and  forguardian=1";
			if($a[selectOptionType] && $a[selectOptionType]==='기호도')
				$selectType = "and  content is not null";
			if($a[selectTime] && $a[selectTime]!=='전체')
				$selectTime =" and d.mealtime=:selectTime";
			if($a[startDate])
				$sdate = " and date_format(date,'%Y-%m-%d') >= :startDate";
			if($a[endDate])
				$edate = " and date_format(date,'%Y-%m-%d') <= :endDate";
			
			$mealChoice = query("select d.*, e.ward as ward from
				(SELECT max(a.date) date, max(a.no) as no, max(diet.name) dietname, max(a.forguardian) as forguardian
							,max(a.canceled) as canceled, max(a.patientno) as patientno, 
							max(c.name) as name, max(room) as room, max(bedno) as bedno,
							max(a.creationtime) as creationtime, max(a.mealtime) as mealtime,
							max(a.mealtype) as mealtype, GROUP_CONCAT(b.content) as content 
							FROM mealorder as a left outer join mealorderselection as b on a.no = b.mealorderno 
							left outer join diet on a.dietno = diet.no
							left outer join uis.ocs_patient as c on patientno=c.no
							group by a.no order by a.creationtime desc
				 )as d left join wardmap as e on d.room =  e.room and d.bedno = e.bedno
				where 1=1 $selectType $selectTime $sdate $edate $selectWard and d.canceled = 0 order by d.creationtime desc
				 ",$a);
			
			$selectMealType = query("select * from diet",$a);
			$selectOptionType = query("select * from mealtypeall ",$a);		
			$selectMealTime = query("select * from mealtime ",$a);
			$selectWard = query("select * from s4ward where hid=:hid",$a);
			return array(
					mealChoice => $mealChoice,
					selectMealType=>$selectMealType,
					selectOptionType=>$selectOptionType,
					selectMealTime=>$selectMealTime,
					selectWard=>$selectWard,
             );
		}
		/*
		function choiceMeal(&$view){
			
			$view = 'Diet/choiceMeal.pug';
			$a = $_REQUEST;
		
			$mealChoice = query("select d.*, e.ward as ward from
				(SELECT max(a.date) date, max(a.no) as no, max(diet.name) dietname, max(a.forguardian) as forguardian
							,max(a.canceled) as canceled, max(a.patientno) as patientno, 
							max(c.name) as name, max(room) as room, max(bedno) as bedno,
							max(a.creationtime) as creationtime, max(a.mealtime) as mealtime,
							max(a.mealtype) as mealtype, GROUP_CONCAT(b.content) as content 
							FROM mealorder as a left outer join mealorderselection as b on a.no = b.mealorderno 
							left outer join diet on a.dietno = diet.no
							left outer join uis.ocs_patient as c on patientno=c.no
							where 1=1 $selectType $selectTime $date 
							group by a.no 
				 )as d left join wardmap as e on d.room =  e.room and d.bedno = e.bedno order by creationtime desc",$a);
			
			$selectMealType = query("select * from diet",$a);
			$selectOptionType = query("select * from mealtypeall ",$a);		
			$selectMealTime = query("select * from mealtime ",$a);
			$selectWard = query("select * from s4ward where hid='IM39'",$a);

			 return array(
					cdiets=>$this->fetchDiets('im39'),
					mealChoice => $mealChoice,
					selectMealType=>$selectMealType,
					selectOptionType=>$selectOptionType,
					selectMealTime=>$selectMealTime,
					selectWard=> $selectWard,

             );
		}
		*/
		function fetchOrders($a){
			if($a[selectWard])
				$ward = " and ward=:selectWard ";
			if($a[guardian])
				$guardian = " and forguardian=:guardian ";
			if($a[alt])
				$alt = " and mealtype='선택식' ";
			if($a[mealtime])
				$mealtime = " and mealtime=:mealtime ";
			if($a[startDate])
				$sdate = " and date_format(a.creationtime,'%Y-%m-%d') >= :startDate";
			if($a[endDate])
				$edate = " and date_format(a.creationtime,'%Y-%m-%d') <= :endDate";
			
			$orders = query("
				select c.*, b.*, a.* from mealorder a
					join uis.ocs_patient b on
						patientno=b.no
						
					left join wardmap c on	
						c.room=b.room and c.bedno=b.bedno
					where
						1=1						
						$sdate
						$edate
						$ward
						$alt
						$guardian
						$mealtime
						and a.canceled = 0
					order by a.creationtime desc
					limit 1000
			", $a);
			$tastes = array();
			foreach($orders as &$o) {
				$pno = $o[patientno];
				if (!$tastes[$pno]) // query수 줄이기
					$tastes[$pno] = query("select content from mealtaste 
					join mealorderoption b on mealoptionno=b.no
					where patientno=:patientno and checked=1", $o);
				$o[tastes] = $tastes[$pno];
			}
			if($a[tastes]) {
				$orders = array_filter($orders, function($o){
					return count($o[tastes]) > 0;
				});
			}
			return $orders;
		}
		
		//기호도 조회
		function fetchGihodo($a){
			if($a[selectWard])
				$ward = " and ward=:selectWard ";
			if($a[guardian])
				$guardian = " and forguardian=:guardian ";
			if($a[mealtime])
				$mealtime = " and mealtime=:mealtime ";
			if($a[startDate])
				$sdate = " and date_format(a.creationtime,'%Y-%m-%d') >= :startDate";
			if($a[endDate])
				$edate = " and date_format(a.creationtime,'%Y-%m-%d') <= :endDate";
			
			$orders = query("
				select max(a.no) no, 
					   max(a.patientno) patientno, 
					   max(c.ward) ward, 
					   max(b.last_room) last_room, 
					   max(b.last_bedno) last_bedno, 
					   max(b.name) name, 
					   max(a.MlOrdNm) MlOrdNm, 
					   max(a.creationtime) creationtime 
				from mealorder a join uis.ocs_patient b on patientno=b.no 
				left join wardmap c on c.room=b.last_room and c.bedno=b.last_bedno 
				where 1=1 
					  $ward 
					  $guardian 
					  $mealtime 
					  $sdate 
					  $edate 
					  and mealtype='기호도' 
					  and a.canceled = 0 
				group by b.no
				order by creationtime desc
						limit 1000
			", $a);
			
			
			$tastes = array();
			foreach($orders as &$o) {
				$pno = $o[patientno];
				if (!$tastes[$pno]) // query수 줄이기
					$tastes[$pno] = query("select content from mealtaste 
					join mealorderoption b on mealoptionno=b.no
					where patientno=:patientno and checked=1", $o);
				$o[tastes] = $tastes[$pno];
			}
			if($a[tastes]) {
				$orders = array_filter($orders, function($o){
					return count($o[tastes]) > 0;
				});
			}
			return $orders;
		}
		
		function Orders(&$view){
			$view = 'Diet/orders.pug';
			$a = $_REQUEST;
			return array(
				wards=>query("select * from s4ward where hid='IM39'",$a),
			);
		}
		
		function gihodo(&$view){
			$view = 'Diet/gihodo.pug';
			$a = $_REQUEST;
			return array(
				wards=>query("select * from s4ward where hid='IM39'",$a),
			);
		}
		
		function searchSummary(&$view){
			
			$a = $_REQUEST;
			
			
			if($a[selectWard] && $a[selectWard]!=='전체')
				$selectWard = "and  ward=:selectWard";
			if($a[selectOptionType] && $a[selectOptionType]!=='전체')
				$selectType = "and  b.mealtype=:selectOptionType";
			if($a[selectOptionType] && $a[selectOptionType]==='보호자식')
				$selectType = "and  b.forguardian=1";
			if($a[startDate])
				$sdate = " and date_format(b.creationtime,'%Y-%m-%d') >= :startDate";
			if($a[endDate])
				$edate = " and date_format(b.creationtime,'%Y-%m-%d') <= :endDate";
			
			
			$selectSumlist = query("SELECT max(d.ward) as ward
			, max(b.mealtime) as mealtime 
			, max(b.mealtype) mealtype
			, count(*) cnt 
			FROM diet as a left outer join mealorder as b on a.no = b.dietno 
			left outer join uis.ocs_patient c on b.patientno = c.no 
			left outer join wardmap as d on d.room = c.room and d.bedno = c.bedno 
			where b.canceled = 0 $selectType $sdate $edate  group by d.ward , b.mealtime , b.mealtype 
			order by d.ward desc ",$a);
			
			$selectChoiceMeal = query("SELECT max(a.name) name, 
			max(c.content) content,  count(*) cnt 
			FROM diet as a 
			left join mealorder as b on a.no=b.dietno 
			left join mealorderselection as c on b.no = c.mealorderno 
			where b.canceled = 0  $sdate $edate 
			GROUP by a.name , c.content having content is not null",$a);
			
			$selectMorningCnt = query("select sum(a.cnt) cnt from (SELECT count(*) cnt 
			FROM diet as a left outer join mealorder as b on a.no = b.dietno 
			left outer join uis.ocs_patient c on b.patientno = c.no 
			left outer join wardmap as d on d.room = c.room and d.bedno = c.bedno 
			where b.canceled = 0 $selectType $sdate $edate  group by d.ward , b.mealtime , b.mealtype 
			having 1=1 and b.mealtime='조식'  order by d.ward desc ) a",$a);
			
			$selectLunchCnt = query("select sum(a.cnt) cnt from (SELECT count(*) cnt 
			FROM diet as a left outer join mealorder as b on a.no = b.dietno 
			left outer join uis.ocs_patient c on b.patientno = c.no 
			left outer join wardmap as d on d.room = c.room and d.bedno = c.bedno 
			where b.canceled = 0 $selectType $sdate $edate  group by d.ward , b.mealtime , b.mealtype 
			having 1=1 and b.mealtime='중식'  order by d.ward desc ) a",$a);
			
			$selectNightCnt = query("select sum(a.cnt) cnt from (SELECT count(*) cnt 
			FROM diet as a left outer join mealorder as b on a.no = b.dietno 
			left outer join uis.ocs_patient c on b.patientno = c.no 
			left outer join wardmap as d on d.room = c.room and d.bedno = c.bedno 
			where b.canceled = 0  $selectType $sdate $edate  group by d.ward , b.mealtime , b.mealtype 
			having 1=1 and b.mealtime='석식'  order by d.ward desc ) a",$a);
			
			$selectSumCnt = query("select sum(a.cnt) cnt from ( SELECT count(*) cnt 
			FROM diet as a left outer join mealorder as b on a.no = b.dietno 
			left outer join uis.ocs_patient c on b.patientno = c.no 
			left outer join wardmap as d on d.room = c.room and d.bedno = c.bedno 
			where b.canceled = 0 $selectType $sdate $edate  group by d.ward , b.mealtype 
			having 1=1  order by d.ward desc ) a",$a);
			
			$selectChoiceSum = query("select sum(a.cnt) cnt from ( 
			SELECT max(a.name) , max(b.mealtype), max(c.content), count(*) cnt 
			FROM `diet` as a left join mealorder as b on a.no=b.dietno 
			left join mealorderselection as c on b.no = c.mealorderno 
			where b.canceled = 0 $sdate $edate 
			GROUP by a.name , c.content  having content is not null
			) a", $a);
			
			$selectOptionType = query("select * from mealtypeall ",$a);		
			$selectMealTime = query("select * from mealtime ",$a);
			$selectWard = query("select * from s4ward where hid=:hid",$a);
			
			
			return array(
					selectSumlist => $selectSumlist,
					selectChoiceMeal=>$selectChoiceMeal,
					selectOptionType=>$selectOptionType,
					selectMorningCnt=>$selectMorningCnt,
					selectLunchCnt=>$selectLunchCnt,
					selectNightCnt=>$selectNightCnt,
					selectSumCnt=>$selectSumCnt,
					selectChoiceSum=>$selectChoiceSum,

             );
		}
		
		function summary(&$view){
			
			$view = 'Diet/summary.pug';
			$a = $_REQUEST;
		    
			if($a[selectOptionType] && $a[selectOptionType]!=='전체')
				$selectType = "and  b.mealtype=:selectOptionType";
			
			$selectSumlist = query("SELECT max(d.ward) as ward
			, max(b.mealtime) as mealtime 
			, max(b.mealtype) mealtype
			, count(*) cnt 
			FROM diet as a left outer join mealorder as b on a.no = b.dietno 
			left outer join uis.ocs_patient c on b.patientno = c.no 
			left outer join wardmap as d on d.room = c.room and d.bedno = c.bedno 
			where b.canceled = 0 group by d.ward , b.mealtime , b.mealtype 
			order by d.ward desc ", $a);
			
			$selectChoiceMeal = query("SELECT max(a.name) name, 
			max(c.content) content,  count(*) cnt 
			FROM diet as a 
			left join mealorder as b on a.no=b.dietno 
			left join mealorderselection as c on b.no = c.mealorderno 
			where b.canceled = 0
			GROUP by a.name , c.content having content is not null",$a);
			
			$selectMealType = query("select * from diet",$a);
			$selectOptionType = query("select * from mealtypeall ",$a);		
			$selectMealTime = query("select * from mealtime ",$a);
			$selectWard = query("select * from s4ward where hid='IM39'",$a);

			$selectMorningCnt = query("select sum(a.cnt) cnt from ( SELECT count(*) cnt 
			FROM diet as a left outer join mealorder as b on a.no = b.dietno 
			left outer join uis.ocs_patient c on b.patientno = c.no 
			left outer join wardmap as d on d.room = c.room and d.bedno = c.bedno 
			where b.canceled = 0 $date group by d.ward , b.mealtime , b.mealtype 
			having 1=1 and b.mealtime='조식' $selectType order by d.ward desc) a ",$a);
			
			$selectLunchCnt = query("select sum(a.cnt) cnt from ( SELECT count(*) cnt 
			FROM diet as a left outer join mealorder as b on a.no = b.dietno 
			left outer join uis.ocs_patient c on b.patientno = c.no 
			left outer join wardmap as d on d.room = c.room and d.bedno = c.bedno 
			where b.canceled = 0 $date group by d.ward , b.mealtime , b.mealtype 
			having 1=1 and b.mealtime='중식'  $selectType order by d.ward desc ) a",$a);
			
			$selectNightCnt = query("select sum(a.cnt) cnt from ( SELECT count(*) cnt 
			FROM diet as a left outer join mealorder as b on a.no = b.dietno 
			left outer join uis.ocs_patient c on b.patientno = c.no 
			left outer join wardmap as d on d.room = c.room and d.bedno = c.bedno 
			where b.canceled = 0 $date group by d.ward , b.mealtime , b.mealtype 
			having 1=1 and b.mealtime='석식'  $selectType order by d.ward desc ) a  ",$a);
			
			$selectSumCnt = query("select sum(a.cnt) cnt from ( SELECT count(*) cnt 
			FROM diet as a left outer join mealorder as b on a.no = b.dietno 
			left outer join uis.ocs_patient c on b.patientno = c.no 
			left outer join wardmap as d on d.room = c.room and d.bedno = c.bedno 
			where b.canceled = 0 group by d.ward , b.mealtype 
			having 1=1  $selectType order by d.ward desc ) a ",$a);
			
			$selectChoiceSum = query("select sum(a.cnt) cnt from ( 
			SELECT max(a.name) , max(b.mealtype), max(c.content), count(*) cnt 
			FROM `diet` as a left join mealorder as b on a.no=b.dietno 
			left join mealorderselection as c on b.no = c.mealorderno 
			where b.canceled = 0 
			GROUP by a.name , c.content having content is not null
			) a", $a);
			
			
			 return array(
					selectSumlist => $selectSumlist,
					selectChoiceMeal=>$selectChoiceMeal,
					selectOptionType=>$selectOptionType,
					selectMorningCnt=>$selectMorningCnt,
					selectLunchCnt=>$selectLunchCnt,
					selectNightCnt=>$selectNightCnt,
					selectSumCnt=>$selectSumCnt,
					selectChoiceSum=>$selectChoiceSum,
             );
		}
		
		function buildMealObject($text)
		{
			//echo $j;
			$mealtimes = explode('$', $text);
			$result = array();
			foreach($mealtimes as $m) {
				$ll = trim($m, "\r\t\n ");
				if(!$ll)
					continue;
				$ll = explode("\n", $ll);
				$meal = array(
					name=>$ll[0],
					data=>implode("\n", array_slice($ll, 1)),
				);
				
				$result[$meal[name]] = $meal;
				//array_push($result, $meal);
			}
			//echo $result;
			return $result;
		}
		function fetch($a){
			$a[hid]='im39';
			if(!$a[n])
				$a[n] = 1;
			if($a[dietname] == '일반식(기본)')
				$a[dietname] = '일반식/기본식';
			$seq = query("
				select * from 
					diet
					left join meal on diet.no=dietno
					where 
						diet.name=:dietname and hid=:hid and isnull(date)
					order by
						seq", $a);
			$firstdate = $seq[0][firstdate];
			$timestamp = new DateTime($firstdate); //기준일
			$now_time = new DateTime($a[date]); //오늘 날짜
			$datediff = date_diff($timestamp, $now_time); //기준일과 오늘 차이
			$mealCount = count($seq); //식단별 식사 개수
			$dated = $datediff->format('%r%a');
			$days = $dated+$mealCount;
			
			$ck = $days%$mealCount; //차이가 8배수 되면 0으로 리셋
			$today = date('w'); //요일 (숫자로 표시됨 : 일 = 0, 월 = 1, ... , 토 = 6)
			$week = array("일","월","화","수","목","금","토"); //요일 한글표시용 배열
			$j = $ck%$mealCount; //식단 요일 체크
			
			$dt = $now_time;
			
			
			for($i=0; $i<$a[n]; $i++){
				if($j % $mealCount == 0)
					$j = 0;
				$result[$i] = array(
					date=>$dt->format('Y-m-d'),
					meals=>$this->buildMealObject($seq[$j][menu]),
				);
				$lists[$i] = $seq[$j][menu];
				$j++;
				$ck = ($ck+1)%$mealCount;
				
				$dt->add(DateInterval::createfromdatestring('+1 day'));
			}
			$dt->add(DateInterval::createfromdatestring('-3 day'));

			/**/
			$specialMeals = query("select * from diet a left join meal b on a.combowith = b.dietno 
				where a.name=:dietname and hid=:hid and isnull(date) order by seq", $a);
			
			if($a[dietname] ==='소아식' || $a[dietname]==='유아식'){
				$j=$today;
				for($i=0; $i<$a[n]; ){
					if($j>7){
						$j=1; //요일 초기화
					}
					if($j==1||$j==3||$j==5){ // 월수금
							//echo $j;
							$stest = array();
							$temp= explode('$',$lists[$i]);
							//echo $seq[2][menu];
							$lunch = preg_split("/\r\n|\n|\r/",$temp[2]);
							if($j==1)//월요일
								$stest = preg_split("/\r\n|\n|\r/",$specialMeals[0][menu]);
							if($j==3)//수요일
								$stest = preg_split("/\r\n|\n|\r/",$specialMeals[1][menu]);
							if($j==5)//금요일
								$stest = preg_split("/\r\n|\n|\r/",$specialMeals[2][menu]);
							
							$stest[2] = $lunch[2];
							$temp[2] = implode("\n",$stest);
							$result[$i] = array(
								date=>$dt->format('Y-m-d'),							
								meals=>$this->buildMealObject(implode('$', $temp)),
							); 
					}
					$j++;
					$i++;
					$dt->add(DateInterval::createfromdatestring('+1 day'));

				}
			 }
			 else if ($a[dietname] ==='일반식(선택식)' || $a[dietname] ==='일반식/선택식'){
				$j = $today;
			    //$dt->add(DateInterval::createfromdatestring('-3 day'));
				for($i=0; $i<$a[n]; ){
						if($j>7){
							$j=1; //요일 초기화
						}
						$stest = array();
						if($j==6 || $j==7 || $j==0){//토요일 
							$stest = preg_split("/\r\n|\n|\r/",$specialMeals[0][menu]);
							
							$temp[0] = implode("\n",$stest);
							$result[$i] = array(
								date=>$dt->format('Y-m-d'),
								meals=>$this->buildMealObject(implode('$', $temp)),
							); 
						}
						$j++;
						$i++;
						$dt->add(DateInterval::createfromdatestring('+1 day'));

				}
					
			 }
			
			return $result;
		}
		function fetchDietInfo($a){
			$rows = query("select * from diet where 
				hid=:hid and name=:dietname", $a);
			return $rows[0];
		}
	}
