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

class m_maptoon extends CI_Model{

	var $tb_name_category = 'mt_categories';
	var $tb_name_episode = 'mt_episodes';
	var $tb_name_maptoon_list = 'mt_list';
	var $tb_name_notice = 'mt_notices';
	var $tb_name_cartoonist = 'mt_cartoonists';
	var $tb_name_ep_like = 'mt_ep_recommend_count';
	var $tb_name_grade = 'mt_ep_grade_count';
	var $tb_name_ep_hit = 'mt_ep_hit_log';
	var $tb_name_mt_recommend ='mt_recommend_count';
	var $tb_name_ep_rank ='mt_ep_view_rank';

	function __construct(){
		parent::__construct();

        $this->load->database();
        $this->load->library('session');
	}

	/*
	return maptoon category list
	@param (numeric) primary key of category table
	@return array or FALSE
	 */
	public function get_category($idx='') {
		$idx = trim($idx);
		if(is_numeric($idx)==TRUE && $idx>0) {
			$query = $this->db->get_where($this->tb_name_category,['idx' => $idx]);
			return $query->row_array();
		} else {
			return FALSE;
		}
	}

	/*
	return episodes data by category id
	@param (numeric|string with comma separated) primary key of category table
	@return array or FALSE
	 */
	public function get_episodes_by_category($cid) {
		if(is_numeric($cid)==TRUE && $cid>0) {
			$query = $this->db->get_where(
				$this->tb_name_episode,
				['mt_categories_idx' => $cid]);
			$ret = $query->result_array();
			// echo $this->db->last_query();
		} else if(is_string($cid)==TRUE && strpos($cid,',')>0) {
			$arr = explode(',',$cid);
			$this->db->where_in('idx', $arr);
			$this->db->order_by('Field(idx, '.$cid.')');
			$query = $this->db->get($this->tb_name_episode);
			$ret = $query->result_array();
			// echo $this->db->last_query();
		} else {
			$ret = FALSE;
		}
		return $ret;
	}

	/*
	get episodes info by sql query
	@param (array) episode idx
	@param (string) return data format
	@return (array or string | FALSE)
	 */
	public function get_widget_info_by_episode_idx($arr, $format='') {
		if(is_array($arr)==FALSE) {
			return FALSE;
		}
		$len = count($arr);
		if(is_numeric($len)==FALSE || $len<=0) {
			return FALSE;
		}
		$where_in = implode(',',$arr);
		$where_in = "'".str_replace(',',"','",$where_in)."'";

		$sql = "SELECT a.idx as epi_idx, a.mt_list_idx, a.title, a.main_img, a.ep_no,".
			   "a.display_date, a.view_count, a.grade, a.reg_date,".
			   "b.idx as mt_idx, b.name, b.mt_cartoonists_idx ".
			   "FROM ".$this->tb_name_episode." a, ".$this->tb_name_maptoon_list." b ".
			   "WHERE a.mt_list_idx=b.idx ".
			   "AND a.idx IN ($where_in) ".
			   "ORDER BY FIELD(a.idx,$where_in)";
		$query = $this->db->query($sql);
		$row = $query->result_array();
		$len_row = count($row);
		$where_in2 = [];
		if($len_row<=0) {
			return FALSE;
		} 
		foreach($row as $k=>$v) {
			if(is_numeric($v['mt_cartoonists_idx'])==TRUE 
				&& $v['mt_cartoonists_idx'] > 0) {
				$where_in2[] = $v['mt_cartoonists_idx'];
			}
		}

		$this->db->select('idx, name');
		$this->db->where_in('idx',$where_in2);
		$where_in2_str = implode(',',$where_in2);
		$this->db->order_by('Field(idx, '.$where_in2_str.')');
		$query = $this->db->get($this->tb_name_cartoonist);
		$row2 = $query->result_array();
		// echo $this->db->last_query();	
		for($i=0; $i<$len_row; $i++) {
			$row[$i]['cartoonist'] = $this->get_cartoonist_name_from_data($row2,$row[$i]['mt_cartoonists_idx']);
			$row[$i]['episode_url'] = '/web/maptoon/article?mtId='.$row[$i]['mt_idx'].'&no='.$row[$i]['ep_no'];
			$row[$i]['maptoon_url'] = $this->get_maptoon_url($row[$i]['mt_idx']);
			$row[$i]['display_date_timestamp'] = strtotime($row[$i]['display_date']);
		}

		if($format=='json') {
			return json_encode($row);
		} else {
			return $row;
		}
	}

	function get_cartoonist_name_from_data($arr,$idx) {
		if(is_array($arr)==TRUE && is_numeric($idx)==TRUE && $idx>0) {
			foreach($arr as $v) {
				if($v['idx']==$idx) {
					return $v['name'];
				}
			}
		} else {
			return FALSE;
		}
	}

	/*
	get today maptoon; presented on ongoing maing page
	 */
	public function get_today_maptoon() {
		$sql = "SELECT * FROM ".$this->tb_name_maptoon_list.
			   " WHERE status=0 ORDER BY recommend ASC";
		$qry = $this->db->query($sql);
		$row = $qry->result_array();
		$len_row = count($row);

		if($len_row<=0) {
			return FALSE;
		}
		$result = ['mon' => [], 'tue' => [], 'wed' => [],
				   'thu' => [], 'fri' => [], 'sat' => []];
		$cartoonist = $this->get_cartoonist_list();
		foreach($row as $v) {
			$v['maptoon_url'] = $this->get_maptoon_url($v['idx']);
			$v['description'] = str_replace('\n',' ',$v['description']);
			foreach($cartoonist as $val) {
				if($v['mt_cartoonists_idx']==$val['idx']) {
					$v['cartoonist'] = $val['name'];
				}
			}
			// if($v['date_sun']==1) {
			// 	$result['sun'] = $v;
			// }
			if($v['date_mon']==1) {
				array_push($result['mon'],$v);
			}
			if($v['date_tue']==1) {
				array_push($result['tue'],$v);
			}
			if($v['date_wed']==1) {
				array_push($result['wed'],$v);
			}
			if($v['date_thu']==1) {
				array_push($result['thu'],$v);
			}
			if($v['date_fri']==1) {
				array_push($result['fri'],$v);
			}
			if($v['date_sat']==1) {
				array_push($result['sat'],$v);
			}
		}
		return $result;
	}

	/*
	return maptoon url
	@param (numeric) idx of mt_list table
	@return (string | NULL)
	 */
	public function get_maptoon_url($mt_idx) {
		if(is_numeric($mt_idx)==TRUE && $mt_idx>0) {
			return '/web/maptoon/list?mtId='.$mt_idx;
		} else {
			return NULL;
		}
	}

	/*
	update episodes' idx in category
	@param (numeric) idx of category table
	@param (string) idx of episodes separated with comma
	@return (boolean)
	 */
	public function update_episodes_by_category($cid, $str) {
		if(is_numeric($cid)==TRUE && $str!='') {
			//1.find all episodes in the category
			$ret1 = $this->get_episodes_by_category($cid);
			$len_ret1 = count($ret1);
			$prev_idxs = [];
			if($len_ret1>0) {
				foreach($ret1 as $v) {
					$prev_idxs[] = $v['idx'];
				}	
			}

			//2.remove some episode in case those are not in the updated idx from db table mt_episodes
			$new_idxs = explode(',',$str);
			$idxs_deleted = array_diff($prev_idxs,$new_idxs);
			$len_idxs_deleted = count($idxs_deleted);

			if($len_idxs_deleted>0) {
				// echo '-----<br>'.$idxs_deleted.'<br>-----'; exit;
				$this->db->where_in('idx',$idxs_deleted);
				$this->db->update($this->tb_name_episode, ['mt_categories_idx' => 0]);
				// echo $this->db->last_query();	
			}
			
			//3.update
			$this->db->where('idx',$cid);
			$ret = $this->db->update($this->tb_name_category, ['mt_episodes_idx' => $str]);
			// echo $this->db->last_query();
			return $ret;
		} else {
			return FALSE;
		}
	}

	/*
	get episode thumbnail, title, idx
	@param (string) search keyword
	@return (array) or NULL
	 */
	public function get_episodes_by_search_keyword($str) {
		$str = trim($str);
		if($str!='') {
			$this->db->select(['idx','title','main_img']);
			$this->db->like('title',$str);
			$query = $this->db->get($this->tb_name_episode);
			$row = $query->result_array();
			// echo $this->db->last_query();
			return $row;
		} else {
			return NULL;
		}
	}

	/*
	return list of maptoon
	@param (array) search keywords keys & values
	@return array or FALSE
	 */
	public function get_maptoon_list($arr='') {
		if(is_array($arr)==TRUE && count($arr)>0) {
			$query = $this->db->get_where($this->tb_name_maptoon_list, $arr);
		} else {
			$query = $this->db->get($this->tb_name_maptoon_list);
		}
		$row = $query->result_array();
		return $row;
	}


	/*
	insert maptoon data
	@return (boolean)
	 */
	public function insert_maptoon($arr) {
		if(is_array($arr)==TRUE) {
			return $this->db->insert($this->tb_name_maptoon_list,$arr);
		} else {
			return FALSE;
		}
	}

	/*
	update maptoon data
	@param (numeric) idx of mt_list table
	@param (array) maptoon data
	@return (boolean)
	 */
	public function update_maptoon($idx, $arr) {
		if(is_numeric($idx)==TRUE && is_array($arr)==TRUE) {
			$this->db->where('idx',$idx);
			return $this->db->update($this->tb_name_maptoon_list, $arr);
		} else {
			return FALSE;
		}
	}

	public function delete_maptoon($idx) {
		if(is_numeric($idx)==TRUE && $idx>0) {
			$ret = $this->db->delete($this->tb_name_maptoon_list, ['idx'=>$idx]);
			return $this->db->last_query();
			return $ret;
		} else {
			return FALSE;
		}
	}

	public function get_cartoonist_list() {
		$this->db->order_by('name','ASC');
		$query = $this->db->get($this->tb_name_cartoonist);
		return $query->result_array();
	}

	/*
	return num of episodes by maptoon idx
	@param (numeric) idx of mt_list table
	@return (numeric)
	 */
	public function get_num_of_episodes($mt_idx) {
		if(is_numeric($mt_idx)==TRUE && $mt_idx>0) {
			$query = $this->db->get_where($this->tb_name_episode,['mt_list_idx' => $mt_idx]);
			return $query->num_rows();
		} else {
			return 0;
		}
	}

	/*
	get announcement list
	@return array or FALSE
	*/
	public function get_announcement_list($mt_idx){
		$this->db->order_by($this->tb_name_notice.'.reg_date','DESC');
		$this->db->select($this->tb_name_notice.'.*');
		$this->db->select($this->tb_name_maptoon_list.'.name');
		$this->db->from($this->tb_name_notice);
        $this->db->join($this->tb_name_maptoon_list, $this->tb_name_maptoon_list.'.idx = '.$this->tb_name_notice.'.mt_list_idx');
        if($mt_idx!=0)$this->db->where($this->tb_name_notice.'.mt_list_idx',$mt_idx);
		
		$query = $this->db->get();
		return $query->result_array();
	}

	/*
	get number of announcement by maptoon
	@param (numeric) pk of tb_name_maptoon_list
	@return (numeric)
	 */
	public function get_num_of_announcement_by_maptoon($mt_idx) {
		if(is_numeric($mt_idx)==TRUE && $mt_idx>0) {
			$query = $this->db->get_where($this->tb_name_notice,['mt_list_idx'=>$mt_idx]);
			return $query->num_rows();
		} else {
			return 0;
		}
	}


	/*
	get name of mt_list
	@return array or FALSE
	*/
	public function get_mt_title(){
		$this->db->order_by("name","ASC");
		$this->db->select("idx");
		$this->db->select("name");
		$query = $this->db->get($this->tb_name_maptoon_list);
		return $query->result_array();
	}

	/*
	get_episode_list
	@return array or FALSE
	*/
	public function get_episode_list($req_data){
		$sort_list                = $req_data['sort_list']; // 최신 조회
		$date_reg                 = $req_data['date_reg'];  // 등록 날짜별
		$mt_categories_idx        = $req_data['category'];  // 카테고리
		$mt_list_idx              = $req_data['mt_name'];   // 맵툰 이름
		$title                    = $req_data['ep_title'];  // 맵툰 제목
		$sdate                    = $req_data['sdate'];     // 시작일
		$edate                    = $req_data['edate'];     // 종료일
		$author                   = $req_data['author'];    // 작가
		$offset                   = $req_data['offset'];
        $limit                    = $req_data['limit'];
		
		$this->db->select('a.*');
		$this->db->select('b.mt_cartoonists_idx');
		$this->db->select('b.name');
		$this->db->from($this->tb_name_episode.' AS a');
		$this->db->join($this->tb_name_maptoon_list.' AS b', 'b.idx = a.mt_list_idx');
		if($mt_categories_idx!='') $this->db->where('mt_categories_idx',$mt_categories_idx);
		if($mt_list_idx!='') $this->db->where('mt_list_idx',$mt_list_idx);
		if($title!='')$this->db->where('title',$title);

		//작가 번호로 조회
		if(is_array($author)){
		if(count($author)>0){
		for($i=0;$i<count($author);$i++){
				if($i==0){ $this->db->where('b.mt_cartoonists_idx',$author[$i]['idx']);
			}else{
				$this->db->or_where('b.mt_cartoonists_idx',$author[$i]['idx']);
			}
		}}}

		//등록날짜별 조회
		if(isset($date_reg)){
		switch ($date_reg) {
			case 'td'  : $this->db->where('DATE(a.reg_date) =',date("Y-m-d")); break;
			case 'yd'  : $this->db->where('DATE(a.reg_date) =',date("Y-m-d", strtotime("-1 days"))); break;
			case 'w'  : $this->db->where('DATE(a.reg_date) >=',date("Y-m-d", strtotime("-7 days"))); break;
			case '30d'  : $this->db->where('DATE(a.reg_date) >=',date("Y-m-d", strtotime("-30 days"))); break;
			case 'lm'  : $this->db->where('DATE(a.reg_date) >=',date("Y-m-d", strtotime("-1 months"))); break;
			case 'sel'  : $this->db->where('DATE(a.reg_date) <=',$sdate); $this->db->where('DATE(a.reg_date) >=',$edate); break;
		}}

		$this->db->limit($limit, $offset);
		if($sort_list=="up"||$sort_list=="") $this->db->order_by("reg_date","DESC");
		if($sort_list=="vi") $this->db->order_by("view_count","DESC");

		$res = $this->db->get();
		return $res->result_array();
	}

		/*
	get_episode_list
	@return array or FALSE
	*/
	public function get_episode_list_search_count($req_data){
		$sort_list                = $req_data['sort_list']; // 최신 조회
		$date_reg                 = $req_data['date_reg'];  // 등록 날짜별
		$mt_categories_idx        = $req_data['category'];  // 카테고리
		$mt_list_idx              = $req_data['mt_name'];   // 맵툰 이름
		$title                    = $req_data['ep_title'];  // 맵툰 제목
		$sdate                    = $req_data['sdate'];     // 시작일
		$edate                    = $req_data['edate'];     // 종료일
		$author                   = $req_data['author'];    // 작가

		$this->db->from($this->tb_name_episode.' AS a');
		$this->db->join($this->tb_name_maptoon_list.' AS b', 'b.idx = a.mt_list_idx');
		if($mt_categories_idx!='') $this->db->where('mt_categories_idx',$mt_categories_idx);
		if($mt_list_idx!='') $this->db->where('mt_list_idx',$mt_list_idx);
		if($title!='')$this->db->where('title',$title);
		//작가 번호로 조회
		if(is_array($author)){
		if(count($author)>0){
		for($i=0;$i<count($author);$i++){
				if($i==0){ $this->db->where('b.mt_cartoonists_idx',$author[$i]['idx']);
			}else{
				$this->db->or_where('b.mt_cartoonists_idx',$author[$i]['idx']);
			}
		}}}
		//등록날짜별 조회
		if(isset($date_reg)){
		switch ($date_reg) {
			case 'td'  : $this->db->where('DATE(a.reg_date) =',date("Y-m-d")); break;
			case 'yd'  : $this->db->where('DATE(a.reg_date) =',date("Y-m-d", strtotime("-1 days"))); break;
			case 'w'  : $this->db->where('DATE(a.reg_date) >=',date("Y-m-d", strtotime("-7 days"))); break;
			case '30d'  : $this->db->where('DATE(a.reg_date) >=',date("Y-m-d", strtotime("-30 days"))); break;
			case 'lm'  : $this->db->where('DATE(a.reg_date) >=',date("Y-m-d", strtotime("-1 months"))); break;
			case 'sel'  : $this->db->where('DATE(a.reg_date) <=',$sdate); $this->db->where('DATE(a.reg_date) >=',$edate); break;
		}}
		
		if($sort_list=="up"||$sort_list=="") $this->db->order_by("reg_date","DESC");
		if($sort_list=="vi") $this->db->order_by("view_count","DESC");

		$res = $this->db->count_all_results();
		return $res;
	}

	/*
	get cartoonist idx by_name
	@return array or FALSE
	*/
	public function get_cartoonist_idx_by_name($name) { //test
		$this->db->select("idx");
		$this->db->where('name',$name);
		$query = $this->db->get($this->tb_name_cartoonist);
		return $query->result_array();
	}

	/*
	 return episode data by maptoon id and idx
	 @param array (mt_idx, episode_idx)
	 @return array or FALSE 
	 */
	public function get_episode_by_mt_idx_episode_no($arr){
		$query = $this->db->get_where($this->tb_name_episode,$arr);
		$result= $query -> row();
		$data = (array)$result;
		if(count($data)==0 || ($data['is_display']==0)){
			return false;
		}else{
			return $data;
		}
	}

	/*
	return num of episodes by maptoon idx
	@param (numeric) idx of mt_list table
	@return (numeric)
	 */
	public function get_display_episodes($req_data) {
		$mt_idx            = $req_data['idx'];
		isset($req_data['offset'])?$offset= $req_data['offset']:$offset=0;
		isset($req_data['limit'])?$limit=$req_data['limit']:$limit=0;
		isset($req_data['div'])?$div=$req_data['div']:$div=0;

		if($limit!=0){
			if($div=='main'){//메인페이지
				$this->db->select($this->tb_name_episode.'.*');
				$this->db->select('b.name');
				$this->db->join($this->tb_name_maptoon_list.' as b', 'b.idx = '.$this->tb_name_episode.'.mt_list_idx');
				$this->db->order_by("reg_date","DESC");
			}
			$this->db->limit($limit, $offset);
			$this->db->order_by("ep_no","DESC");
		}else{
			$this->db->order_by("ep_no","ASC");
		}
		if($mt_idx==0){
			$_where = "is_display=1";
		}else{
			$_where = "mt_list_idx=".$mt_idx." AND is_display=1";
		}
		$query = $this->db->get_where($this->tb_name_episode,$_where);
		return $query->result_array();
	}

	/*
	return toal count of display episodes by maptoon idx  
	@param (numeric) idx of mt_list table
	@return (numeric)
	*/
	public function get_totalcount_episodes($mt_idx){   
		if($mt_idx==0){
			$num = $this->db->count_all($this->tb_name_episode);
		}else{
			$_where = "mt_list_idx=".$mt_idx." AND is_display=1";
			$this->db->where($_where);
			$num = $this->db->count_all_results($this->tb_name_episode);
		}
		return $num;
	}

	/*
	find like data and insert or delete
	return String message
	*/
	public function like($req_data){
		$member_id=$req_data['user_id'];

		$this->db->where('member_id',$member_id);
		$query=$this->db->get('member');

		$ep_idx=$req_data['ep_idx'];
		$mt_list_idx=$req_data['mt_list_idx'];
		$mb_idx=$query->result_array()[0]['idx'];

		$data=array('ep_idx'=>$ep_idx,
					'mb_idx'=>$mb_idx); //where

		$query = $this->db->get_where($this->tb_name_ep_like,$data);
		$num=$query->num_rows();
		$message;

		if($num==0){
			//Insert
			$message="좋아요를 선택하셨습니다.";
			$this->db->insert($this->tb_name_ep_like, $data);
			
			$this->db->set("recommend_count","recommend_count+1",false);
			$this->db->where("idx",$ep_idx);
			$this->db->update($this->tb_name_episode);

			$this->db->set("recommend","recommend+1",false);
			$this->db->where("idx",$mt_list_idx);
			$this->db->update($this->tb_name_maptoon_list);
			$state=1;
		}else{
			//Delete
			$message="좋아요를 해지하셨습니다.";
			$this->db->delete($this->tb_name_ep_like, $data);
			$this->db->set("recommend_count","recommend_count-1",false);
			$this->db->where("idx",$ep_idx);
			$this->db->update($this->tb_name_episode);

			$this->db->set("recommend","recommend-1",false);
			$this->db->where("idx",$mt_list_idx);
			$this->db->update($this->tb_name_maptoon_list);
			
			$state=2;
		}

		$return_data=array('message'=>$message,'state'=>$state);
		return $return_data;
	}

	/*
	return grade insert and return grade 
	@param (array) idx of mt_episodes table AND user id
	@return (array)
	*/
	public function star_score($req_data){
		$member_id = $req_data['user_id'];
		$this->db->where('member_id',$member_id);
		$query=$this->db->get('member');

		$mb_idx=$query->result_array()[0]['idx'];
		$ep_idx = $req_data['ep_idx'];
		$grade = $req_data['score'];


		//중복 조회
		// $where_data=array(
		// 	'mb_idx'=>$mb_idx,
		// 	'ep_idx'=>$ep_idx);

		$this->db->where('mb_idx',$mb_idx);
		$this->db->where('ep_idx',$ep_idx);
		$query = $this->db->get($this->tb_name_grade);
		$is_date=$query->result_array();
		if(count($is_date)==0){
			$insert_data=array(
				'mb_idx'=>$mb_idx,
				'ep_idx'=>$ep_idx,
				'grade'=>$grade
			);

			$this->db->insert($this->tb_name_grade, $insert_data);
			
			
			$this->db->select('grade, grade_total');
			$query =$this->db->get_where($this->tb_name_episode,array('idx'=>$ep_idx));

			$grade_data = $query->result_array();
			$c_grade=$grade_data[0]['grade'];
			$c_grade_total=$grade_data[0]['grade_total'];
			
			$u_grade= ($c_grade*$c_grade_total+$grade)/($c_grade_total+1);
			$u_grade_total= $c_grade_total+1;

			$update_data=array(
					'grade'=>$u_grade,
					'grade_total'=>$u_grade_total
			);

			$this->db->where('idx',$ep_idx);
			$this->db->update($this->tb_name_episode,$update_data);


			if ($this->db->affected_rows() > 0)
			{
				$res_data['grade']=$u_grade;
				$res_data['grade_total']=$u_grade_total;
				$res_data['message']="참여하였습니다.";
				$res_data['state']=1;
				return $res_data;
			}
			else
			{
			return "실패하였습니다. 관리자에게 문의바랍니다.";
			}
		}else{
			return "이미 참여하였습니다.";	
		}

	}

	/*
	return confirm like and grade
	@param (array) idx of mt_episodes table AND user id
	@return (array)
	*/
	function ep_is_like_grade($req_data){
		$member_id = $req_data['user_id'];
		$this->db->where('member_id',$member_id);
		$query=$this->db->get('member');

		$mb_idx=$query->result_array()[0]['idx'];
		$ep_idx=$req_data['ep_idx'];
		// echo $ep_idx;

		$query = $this->db->get_where($this->tb_name_ep_like,array('mb_idx'=>$mb_idx,'ep_idx'=>$ep_idx));
		$is_data=$query->num_rows();
		// echo $is_data;
		$res_data=array();
		if($is_data==0){
			$res_data['is_like']=0;	
		}else{
			$res_data['is_like']=1;
			// echo 1;
		}	

		$query = $this->db->get_where($this->tb_name_grade,array('mb_idx'=>$mb_idx,'ep_idx'=>$ep_idx));
		$is_data=$query->num_rows();
		if($is_data==0){
			$res_data['is_grade']=0;	
		}else{
			$res_data['is_grade']=1;
		}	

		return $res_data;
	}

	/*
	return episodes list for article page
	@param (array) idx of mt_episodes ep_no AND mt_idx
	@return (array)
	*/
	function get_article_ep_list($req_data){
		$ep_no=$req_data['ep_no'];
		$mt_list_idx=$req_data['mt_list_idx'];
		
		if($ep_no<8){
			$offset=0;
			$limit=14;
		}else{
			$p_limit=7; // 페이지에 표시 되는 에피소드 수
			$c_page=$ep_no/$p_limit;
			$offset=($c_page-1)*$p_limit+1;
			$limit=21;
		}

		$this->db->select(['idx','title','main_img','ep_no']);
		$this->db->where('is_display',1);

		$_where=[
			'mt_list_idx' => $mt_list_idx,
			'is_display' => 1,
			'DATE(display_date)<=' => date("Y-m-d H:i:s")
		];

		$this->db->limit($limit, $offset);
		$query = $this->db->get_where($this->tb_name_episode,$_where);

		return $query->result_array();
	}

	/*
	insert view count And not return
	@param (array) idx of mt_episodes member mb_idx
	@INSERT hit log AND UPDATE mt_episodes view_count
	*/
	function ep_hit_count($req_data){
		$member_id=$req_data['user_id'];
		if($member_id){
			$this->db->where('member_id',$member_id);
			$query=$this->db->get('member');
			$mb_idx=$query->result_array()[0]['idx'];
		}else{
			$mb_idx=NULL;
		}
		$ep_idx=$req_data['ep_idx'];
		$insert_data=array(
			'mb_idx'=>$mb_idx,
			'ep_idx'=>$ep_idx
		);
		$this->db->insert($this->tb_name_ep_hit,$insert_data);

		$this->db->where('idx',$ep_idx);
		$this->db->set("view_count","view_count+1",false);
		$this->db->update($this->tb_name_episode);
	}

	/*
	get episodes view ranking
	@param() 
	@return(array)
	*/
	function get_ep_view_rank(){
		$this->db->select('a.*, b.mt_list_idx, b.ep_no, b.title, c.name');
		// $this->db->where("a.reg_date>=",date("Y-m-d H:00:00", strtotime("+1 hours")));
		$this->db->order_by('a.reg_date', 'desc');
		$this->db->order_by('a.rank', 'asc');
		$this->db->limit(10);
		$this->db->join($this->tb_name_episode.' as b', 'b.idx = a.ep_idx');
		$this->db->join($this->tb_name_maptoon_list.' as c', 'b.mt_list_idx = c.idx');
		$query=$this->db->get($this->tb_name_ep_rank.' as a');

		return $query->result_array();
	}

	/*
	get episodes view ranking
	@param() 
	@return(array)
	*/
	function get_mt_pop_rank(){
		$this->db->select('a.idx, a.main_img, a.name as mt_name, a.recommend, b.name as ct_name');
		$this->db->order_by('a.recommend','desc');
		$this->db->limit(5);
		$this->db->where('recommend !=',0);
		$this->db->join($this->tb_name_cartoonist.' as b', 'b.idx = a.mt_cartoonists_idx');
		$query=$this->db->get($this->tb_name_maptoon_list.' as a');

		$rank_list=$query->result_array();
		$count_list=$query->num_rows();

		if($count_list<5){
			$_limit=5-$count_list;
			$this->db->select('a.idx, a.main_img, a.name as mt_name, a.recommend, b.name as ct_name');
			$this->db->order_by('rand()');
			$this->db->limit($_limit);
			$this->db->where('recommend',0);
			$this->db->join($this->tb_name_cartoonist.' as b', 'b.idx = a.mt_cartoonists_idx');
			$query_1=$this->db->get($this->tb_name_maptoon_list.' as a');
			$rank_list_1=$query_1->result_array();
			$rank_list=array_merge($rank_list,$rank_list_1);
		}
		
		return $rank_list;
	}

	/*
	update mt_recommend table And return array
	@param (array) member id, mt_idx
	@return (array) message, state
	*/
	function mt_recommend($res_data){
		$member_id=$res_data['user_id'];
		$this->db->where('member_id',$member_id);
		$query=$this->db->get('member');

		$mb_idx=$query->result_array()[0]['idx'];//member idx

		$mt_idx=$res_data['mt_idx'];
		
		$data=array('mt_list_idx'=>$mt_idx,
					'mb_idx'=>$mb_idx); //where

		$query = $this->db->get_where($this->tb_name_mt_recommend,$data);
		$num=$query->num_rows();
		$message;

		if($num==0){
			//Insert
			$this->db->insert($this->tb_name_mt_recommend, $data);
			$this->db->set("recommend","recommend+1",false);
			$this->db->where("idx",$mt_idx);
			$this->db->update($this->tb_name_maptoon_list);
			$message="추천하셨습니다.";
			$state=1;
		}else{
			//Delete
			$this->db->delete($this->tb_name_mt_recommend, $data);
			$this->db->set("recommend","recommend-1",false);
			$this->db->where("idx",$mt_idx);
			$this->db->update($this->tb_name_maptoon_list);
			$message="추천을 취소했습니다.";
			$state=2;
		}

		$return_data=array('message'=>$message,'state'=>$state);
		return $return_data;

	}

	/*
	return reserved idx of epsiodes list 
	@param ()
	@return (array) idx
	*/
	function get_epsiodes_reservation_list(){
        $now_date                   = date("Y-m-d H:i:s");

        $this->db->select('idx');
        $this->db->where('display_date <=', $now_date);
        $this->db->where('display_date !=', '0000-00-00 00:00:00');
        $this->db->where('is_display', '0');
        $this->db->from($this->tb_name_episode);
        $res = $this->db->get();
        $row = $res->result_array();

        return $row;
	}

	/*
	update reserved episodes and return update count 
	@param (array) reserved episodes array
	@return (numeric) update_count
	*/
	function episodes_is_display_update_batch($req_data){
        $arr_update_data = array();
        foreach($req_data as $key=>$val) {
            $arr_update_data[$key]['idx']           = $val['idx'];
            $arr_update_data[$key]['is_display']    = 1;
		}
		
        $row = $this->db->update_batch($this->tb_name_episode, $arr_update_data, 'idx');

        return $row;
	}

}