<?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';

	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]);
			return $query->result_array();
		} 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();
			return $ret;
		} else {
			return FALSE;
		}
	}

	/*
	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();
		//echo $this->db->last_query();
		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 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 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") $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 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();
	}
}