<?
class Portfolio {
	var $DB;
	var $_LIST_NUM = 20;
	var $_PDS = _PDS;
	var $_PDS_SUB = "/portfolio/";
	var $_T_PDS = _PDS;
	var $_T_PDS_SUB = "/portfolio/thumb/";
	
	# 생성자
	function Portfolio($db) {
		$this->DB = $db;
		$this->_PDS .= $this->_PDS_SUB;
		$this->_T_PDS .= $this->_T_PDS_SUB;
		$this->_B_PDS .= $this->_B_PDS_SUB;
	}
#############카테고리S#######################
	function set_category_insert($argu){
		$data = array(
			"title"			=> $argu["title"],
			"title_sub"			=> $argu["title_sub"],
			"published"		=> ($argu["published"]=="Y")?"Y":"N",
		);

		$sth = $this->DB->autoPrepare(TABLE_CATEGORY, array_keys($data), DB_AUTOQUERY_INSERT);
		$res = $this->DB->execute($sth, array_values($data));

		if (DB::isError($res)) {
			//debug($res);
			go_url("", $res->getMessage());
			exit;
		}
		
		$id=mysql_insert_id();

		return true;
	}

	function set_category_modify($argu){
		$data = array(
			"title"			=> $argu["title"],
			"title_sub"			=> $argu["title_sub"],
			"published"		=> ($argu["published"]=="Y")?"Y":"N",
		);
		$res = $result = $this->DB->autoExecute(TABLE_CATEGORY, $data, DB_AUTOQUERY_UPDATE, " id = '{$argu['id']}' ");

		if (DB::isError($res)) {
			go_url("", $res->getMessage());
			exit;
		}

		return true;
	}

	# 목록
	function get_category_list($argu,&$total,$limit = true){
		global $_adminpage;

		$addwhere = "where (1=1) ";
		if(!$_adminpage){$addwhere .= " and (published = 'Y') ";}

		if($argu['s_string']){$addwhere .= " and (title like '%{$argu['s_string']}%') ";	}

		$query = "
			select
				count(*)
			from
				".TABLE_CATEGORY."
			".$addwhere;

		$res = $total = $this->DB->getOne($query);
		if (DB::isError($res)) {
			go_url("", $res->getMessage());
			exit;
		}

		$query = "
			select
				*
			from
				".TABLE_CATEGORY."
			".$addwhere."
			order by id asc
		";

		if($argu["listnum"]){
			$_listnum = $argu["listnum"];
		}
		else{
			$_listnum = $this->_LIST_NUM;
		}

		if($limit)
		$query .= "
			limit ".($argu['p']-1)*$_listnum.",".$_listnum;

		$res = $list =& $this->DB->getAll($query, array(), DB_FETCHMODE_ASSOC);

		if (DB::isError($res)) {
			go_url("", $res->getMessage());
			exit;
		}

		return $list;
	
	}

	function get_category_lnb(){
		global $_adminpage;

		$addwhere = "where (1=1) ";
		$addwhere .= " and (published = 'Y') ";

		$query = "
			select
				*
			from
				".TABLE_CATEGORY."
			".$addwhere."
			order by id asc
		";

		$res = $list =& $this->DB->getAll($query, array(), DB_FETCHMODE_ASSOC);

		if (DB::isError($res)) {
			go_url("", $res->getMessage());
			exit;
		}

		return $list;
	
	}

	function get_category_one(){

		global $_adminpage;

		$addwhere = " where (1=1) ";
		if(!$_adminpage) $addwhere .= "and (published = 'Y')";

		$query = "SELECT 
					*
				  FROM ".TABLE_CATEGORY." 
				  ".$addwhere."
				  ORDER BY id asc limit 0, 1";
		
		$res = $row = $this->DB->getRow($query,DB_FETCHMODE_ASSOC);

		if (DB::isError($res)) {
			go_url("", $res->getMessage());
			exit;
		}

		return $row;
	}



	#상세보기
	function get_category_view($id){
		$query = "SELECT 
					*
				  FROM ".TABLE_CATEGORY."
				  where id = '".$id."'";

		$res = $row = $this->DB->getRow($query,DB_FETCHMODE_ASSOC);
		if (DB::isError($res)) {
			go_url("", $res->getMessage());
			exit;
		}

		return $row;
	}

	#삭제#
	function set_category_delete($id){

		$query = "DELETE FROM ".TABLE_CATEGORY." WHERE id = '".$id."'";
		
		$res = $this->DB->query($query);
		if (DB::isError($res)) {
			go_url("", $res->getMessage());
			exit;
		}
		$p_query = "DELETE FROM ".TABLE_PORTFOLIO." WHERE category = '".$id."'";
		
		$p_res = $this->DB->query($query);
		if (DB::isError($p_res)) {
			go_url("", $p_res->getMessage());
			exit;
		}

		return true;
	}

#############카테고리E#######################

	# 등록
	function set_insert($argu){
		//$res = $order_num = $this->DB->getOne("select ifnull(max(order_num),0)+1 from ".TABLE_PORTFOLIO." where category = '".$argu["category"]."'");
		$res = $order_num = $this->DB->getOne("select ifnull(max(order_num),0)+1 from ".TABLE_PORTFOLIO);
		if (DB::isError($res)) {
			go_url("", $res->getMessage());
			exit;
		}
		
		

		//썸네일 업로드
		if($_FILES['thumb'] !== null && $_FILES['thumb'][error] == 0 && $_FILES['thumb'][size] > 0 ){
			$thumb_info		= getimagesize($_FILES["thumb"]["tmp_name"]);
			$thumb_width		= $file_info[0]; //이미지 가로 사이즈
			$thumb_height	= $file_info[1]; //이미지 세로 사이즈
			$thumb_type		= $_FILES['thumb']['type'];

			if($thumb_width > 385){
				$thumb = thumb_upload($_FILES['thumb'],'/pds/portfolio/thumb/','T','385');
			}
			else{
				$thumb = thumb_upload($_FILES['thumb'],'/pds/portfolio/thumb/','O','');
			}
		}
		

		$data = array(
			"category"		=> $argu["category"],
			"title"			=> $argu["title"],
			"description"	=> strip_tags($argu["description"]),
			"client"		=> $argu["client"],
			"location"		=> $argu["location"],
			"period"		=> $argu["period"],
			"area"			=> $argu["area"],
			"published"		=> ($argu["published"]=="Y")?"Y":"N",
			"reg_date"		=> _NowTime,
			"order_num"		=> $order_num,
			"thumb"			=> $thumb,
			"main"			=> ($argu["main"]=="Y")?"Y":"N",
		);

		$sth = $this->DB->autoPrepare(TABLE_PORTFOLIO, array_keys($data), DB_AUTOQUERY_INSERT);
		$res = $this->DB->execute($sth, array_values($data));

		if (DB::isError($res)) {
			//debug($res);
			go_url("", $res->getMessage());
			exit;
		}
		
		$id=mysql_insert_id();

		$files = array();
		foreach ($_FILES['images'] as $k => $l) {
			foreach ($l as $i => $v) {
				if (!array_key_exists($i, $files))
					$files[$i] = array();
				$files[$i][$k] = $v;
			}
		}

		foreach ($files as $file) {
			$img_original[] = thumb_upload($file,'/pds/portfolio/','T','1088');
		}

		$images = json_encode($img_original);
		$ordering = json_encode($argu["ordering"]);
		$data_file = array(
			"images"    => $images,
			"images_ordering" => $ordering
		);

		$res = $this->DB->autoExecute(TABLE_PORTFOLIO, $data_file, DB_AUTOQUERY_UPDATE, " id = '{$id}'");
		if (DB::isError($res)) {
			//debug($res);
			go_url("", $res->getMessage());
			exit;
		}

		return true;
	}


	#수정
	function set_modify($argu){
		
		//썸네일 업로드
		if($_FILES['thumb'] !== null && $_FILES['thumb'][error] == 0 && $_FILES['thumb'][size] > 0 ){
			$thumb_info		= getimagesize($_FILES["thumb"]["tmp_name"]);
			$thumb_width		= $file_info[0]; //이미지 가로 사이즈
			$thumb_height	= $file_info[1]; //이미지 세로 사이즈
			$thumb_type		= $_FILES['b_thumb']['type'];

			if($thumb_width > 385){
				$thumb = thumb_upload($_FILES['thumb'],'/pds/portfolio/thumb/','T','385',$argu["tmp_thumb"]);
			}
			else{
				$thumb = thumb_upload($_FILES['thumb'],'/pds/portfolio/thumb/','O','',$argu["tmp_thumb"]);
			}
		}
		else{
			$thumb = $argu["tmp_thumb"];
		}
		

		$data = array(
			"category"		=> $argu["category"],
			"title"			=> $argu["title"],
			"description"	=> strip_tags($argu["description"]),
			"client"		=> $argu["client"],
			"location"		=> $argu["location"],
			"period"		=> $argu["period"],
			"area"			=> $argu["area"],
			"published"		=> ($argu["published"]=="Y")?"Y":"N",
			"thumb"			=> $thumb,
			"main"			=> ($argu["main"]=="Y")?"Y":"N",
		);
		$res = $result = $this->DB->autoExecute(TABLE_PORTFOLIO, $data, DB_AUTOQUERY_UPDATE, " id = '{$argu['id']}' ");

		if (DB::isError($res)) {
			go_url("", $res->getMessage());
			exit;
		}

		$files = array();
		foreach ($_FILES['images'] as $k => $l) {
			foreach ($l as $i => $v) {
				if (!array_key_exists($i, $files))
					$files[$i] = array();
				$files[$i][$k] = $v;
			}
		}

		$f=0;
		foreach ($files as $file) {
			$img_original[] = thumb_upload($file,'/pds/portfolio/','T','1457',$argu["tmp_image"][$f]);
		$f++;
		}

		$images = json_encode($img_original);
		$ordering = json_encode($argu["ordering"]);
		$data_file = array(
			"images"    => $images,
			"images_ordering" => $ordering
		);

		$res = $this->DB->autoExecute(TABLE_PORTFOLIO, $data_file, DB_AUTOQUERY_UPDATE, " id = '{$argu['id']}'");
		if (DB::isError($res)) {
			//debug($res);
			go_url("", $res->getMessage());
			exit;
		}
		return true;
	}

	# 목록
	function get_list($argu,&$total,$limit = true){
		global $_adminpage;

		$addwhere = "where (1=1) ";
		if(!$_adminpage){$addwhere .= " and (published = 'Y') ";}
		//if($_adminpage){$addwhere .= " and (category = '{$argu['category']}') ";}
		if($argu['s_category']){$addwhere .= " and (category = '{$argu['s_category']}') ";}

		if($argu['Search']){
			$addwhere .= " and (title like '%{$argu['Search']}%'".$p_where.") ";	
		}

		if(!$_adminpage){
			$sort = " id desc";
		}
		else{
			$sort = " id desc";
		}

		$query = "
			select
				count(*)
			from
				".TABLE_PORTFOLIO."
			".$addwhere;

		$res = $total = $this->DB->getOne($query);
		if (DB::isError($res)) {
			go_url("", $res->getMessage());
			exit;
		}

		$query = "
			select
				*,
				(select title from ".TABLE_CATEGORY." as c where c.id=category) as cate
			from
				".TABLE_PORTFOLIO."
			".$addwhere."
			order by ".$sort."
		";

		if($argu["listnum"]){
			$_listnum = $argu["listnum"];
		}
		else{
			$_listnum = $this->_LIST_NUM;
		}

		if($limit)
		$query .= "
			limit ".($argu['p']-1)*$_listnum.",".$_listnum;

		$res = $list =& $this->DB->getAll($query, array(), DB_FETCHMODE_ASSOC);

		if (DB::isError($res)) {
			go_url("", $res->getMessage());
			exit;
		}

		return $list;
	
	}

	function get_list_limit($limit,$category,$id=""){
		global $_adminpage;

		$addwhere = "where (1=1) and (main='Y') ";
		if(!$_adminpage){$addwhere .= " and (published = 'Y') ";}
		if($id){$addwhere .= " and (id not in('".$id."')) ";}
		if($argu['category']){$addwhere .= " and (category = '{$argu['category']}') ";}

		if(!$_adminpage){
			$sort = " event_date desc";
		}
		else{
			$sort = " event_date desc";
		}


		$query = "
			select
				*,
				(select title from ".TABLE_CATEGORY." as c where c.id=category) as cate
			from
				".TABLE_PORTFOLIO."
			".$addwhere."
			order by ".$sort."
			limit ".$limit."
		";

		$res = $list =& $this->DB->getAll($query, array(), DB_FETCHMODE_ASSOC);

		if (DB::isError($res)) {
			go_url("", $res->getMessage());
			exit;
		}

		return $list;
	
	}


	#상세보기
	function get_view($id){
		$query = "SELECT 
					*,
					(select title from ".TABLE_CATEGORY." as c where c.id=category) as cate
				  FROM ".TABLE_PORTFOLIO."
				  where id = '".$id."'";

		$res = $row = $this->DB->getRow($query,DB_FETCHMODE_ASSOC);
		if (DB::isError($res)) {
			go_url("", $res->getMessage());
			exit;
		}

		return $row;
	}

	#삭제#
	function set_delete($id){
		$_row = $this -> get_view($id);

		if($_row["thumb"]){
			if(file_exists($this->_T_PDS."/".$_row["thumb"])) unlink($this->_T_PDS."/".$_row["thumb"]);
		}

		$images = json_decode($_row["images"]);
		if(count($images) > 0){
			for($i=0;$i<count($images);$i++){
				if(file_exists($this->_PDS."/".$images[$i])) unlink($this->_PDS."/".$images[$i]);
			}
		}

		$query = "DELETE FROM ".TABLE_PORTFOLIO." WHERE id = '".$id."'";
		
		$res = $this->DB->query($query);
		if (DB::isError($res)) {
			go_url("", $res->getMessage());
			exit;
		}

		return true;
	}

	function get_total($argu) {
		$addwhere = "where (1=1) ";
		if(!$_adminpage){$addwhere .= " and (published = 'Y') ";}
		if($argu['s_category']){$addwhere .= " and (category = '{$argu['s_category']}') ";}

		
		$query = "
			select
				count(*)
			from
				".TABLE_PORTFOLIO."
			".$addwhere;

		$res = $total = $this->DB->getOne($query);
		if (DB::isError($res)) {
			go_url("", $res->getMessage());
			exit;
		}

		return $total;
	}

	//진열순서변경
	function set_order_modify($argu){
		$data = array(
			"order_num" => $argu["order_num"]
		);
		$res = $this->DB->autoExecute(TABLE_PORTFOLIO, $data, DB_AUTOQUERY_UPDATE, " id = '{$argu['id']}' ");
		if (DB::isError($res)) {
			//debug($res);
			go_url("",$res->getMessage());
			exit;
		}
		
		return true;
	}


		/*****
		 * 이전 게시물 정보를 가져온다.
		 *****/
		function get_prev($id, $category='', $search=''){
			// TODO : 답변형의 경우 정확한 이전정보 가져오는 방법을 생각해보자
			global $_adminpage;
			$addwhere = "";
			if($category){
				$addwhere = " and (category='".$category."')";
			}

			if($search){
				$addwhere .= " and (title like '%{$argu['Search']}%') ";	
			}

			$query = "
				select
					*
				from
					".TABLE_PORTFOLIO."
				where
					id > '{$id}'
					$addwhere
				order by
					id asc
				limit 1
			";

			$res = $row = $this->DB->getRow($query,DB_FETCHMODE_ASSOC);
			if (DB::isError($res)) {
				//debug($res);
				//go_url("", $res->getMessage());
				return false;
			    exit;
			}
			return $row;
		}

		/*****
		 * 다음 게시물 정보를 가져온다.
		 *****/
		function get_next($id, $category='', $search=''){
			// TODO : 답변형의 경우 정확한 다음정보 가져오는 방법을 생각해보자
			global $_adminpage;
			$addwhere = "";
			if($category){
				$addwhere = " and (category='".$category."')";
			}

			if($search){
				$addwhere .= " and (title like '%{$argu['Search']}%') ";	
			}

			$query = "
				select
					*
				from
					".TABLE_PORTFOLIO."
				where
					id < '{$id}'
					$addwhere
				order by
					 id desc
				limit 1
			";

			$res = $row = $this->DB->getRow($query,DB_FETCHMODE_ASSOC);
			if (DB::isError($row)) {
				//debug($res);
				//go_url("", $res->getMessage());
				return false;
			    exit;
			}
			return $row;
		}


		function set_order($argu){
			
			if($argu["s_mode"] == "up"){

				//$res = $id = $this->DB->getOne("select id from ".TABLE_PORTFOLIO." where (order_num < '".$argu["order_num"]."') and (category = '".$argu["category"]."') order by order_num desc limit 1");
				$res = $id = $this->DB->getOne("select id from ".TABLE_PORTFOLIO." where (order_num < '".$argu["order_num"]."') order by order_num desc limit 1");

				if($id){
					
					$query = "
						update ".TABLE_PORTFOLIO."
						set
							order_num = order_num - 1
						where
							id = '".$argu["id"]."'
					";
					$res = $this->DB->query($query);
					if (DB::isError($res)) {
						go_url("", $res->getMessage());
						exit;
					}
					
					$query1 = "
						update ".TABLE_PORTFOLIO."
						set
							order_num = order_num + 1
						where
							id = '".$id."'
					";

					$res1 = $this->DB->query($query1);
					if (DB::isError($res1)) {
						go_url("", $res1->getMessage());
						exit;
					}

				}
				else{
					go_url("", "정열값이 최상위 입니다.");
					exit;
				}
			
			}
			else if($argu["s_mode"] == "down"){
				//$res = $id = $this->DB->getOne("select id from ".TABLE_PORTFOLIO." where (order_num > '".$argu["order_num"]."')and (category = '".$argu["category"]."') order by order_num asc limit 1");
				$res = $id = $this->DB->getOne("select id from ".TABLE_PORTFOLIO." where (order_num > '".$argu["order_num"]."') order by order_num asc limit 1");

				if($id){
					
					$query = "
						update ".TABLE_PORTFOLIO."
						set
							order_num = order_num + 1
						where
							id = '".$argu["id"]."'
					";
					$res = $this->DB->query($query);
					if (DB::isError($res)) {
						go_url("", $res->getMessage());
						exit;
					}
					
					$query1 = "
						update ".TABLE_PORTFOLIO."
						set
							order_num = order_num - 1
						where
							id = '".$id."'
					";

					$res1 = $this->DB->query($query1);
					if (DB::isError($res1)) {
						go_url("", $res1->getMessage());
						exit;
					}

				}
				else{
					go_url("", "정열값이 최하위 입니다.");
					exit;
				}
			}
			
			return true;
		}
}
?>