<?php
defined('BASEPATH') or exit('No direct script access allowed');
header("Content-Type: text/html; charset=UTF-8");
/**
 * 인클루드 class
 *
 * cm_controller: 부모 Class(CI_Controller 확장한 custome class)
 */
include_once (APPPATH . 'core/web/cm_controller.php');

class maptoon extends cm_Controller
{

    function __construct()
    {
        parent::__construct();
        $this->load->library('session');
        $this->load->library('user_agent');
        $this->load->helper('crossmap/tool_helper');
        $this->load->helper('crossmap/exception_helper');
		//header('location:/');
		//exit(3);
    }

    /*
     * extract part of widget data
     */
    function get_widget_data($orig_arr, $key, $num)
    {
        if (is_array($orig_arr) == FALSE || trim($key) == '' || is_numeric($num) == FALSE || $num <= 0) {
            return FALSE;
        }
        array_multisort(array_column($orig_arr, $key), SORT_DESC, $orig_arr);
        $ret = array_slice($orig_arr, 0, $num);
        return $ret;
    }

    function fn_index()
    {
        $this->config->load('filecache', TRUE);
        $filecache = $this->config->item('file_cache_path', 'filecache');

        $this->load->library('maptoon_lib', [
            'file_cache_path' => $filecache
        ]);
        // 1. get slideshow
        $slideshow = $this->maptoon_lib->get_category_cache(8);
        $slideshow_arr = json_decode($slideshow, TRUE);
        // 2. 뜨끈뜨끈한 신작
        $new_release = $this->maptoon_lib->get_category_cache(9);
        $new_release_arr = json_decode($new_release, TRUE);
        $new_release_date = $this->get_widget_data($new_release_arr, 'reg_date', 6);
        $new_release_count = $this->get_widget_data($new_release_arr, 'view_count', 6);
        $new_release_grade = $this->get_widget_data($new_release_arr, 'grade', 6);
        // 3. 성경을 재미있게
        $fun = $this->maptoon_lib->get_category_cache(10);
        $fun_arr = json_decode($fun, TRUE);
        $fun_date = $this->get_widget_data($fun_arr, 'reg_date', 3);
        $fun_count = $this->get_widget_data($fun_arr, 'view_count', 3);
        $fun_grade = $this->get_widget_data($fun_arr, 'grade', 3);

        $faith = $this->maptoon_lib->get_category_cache(11);
        $faith_arr = json_decode($faith, TRUE);
        $faith_date = $this->get_widget_data($faith_arr, 'reg_date', 9);
        $faith_count = $this->get_widget_data($faith_arr, 'view_count', 9);
        $faith_grade = $this->get_widget_data($faith_arr, 'grade', 9);

        $menu_home = 1;
        $return_data = [
            'slideshow' => $slideshow_arr,
            'new_release' => $new_release_arr,
            'new_release_date' => $new_release_date,
            'new_release_count' => $new_release_count,
            'new_release_grade' => $new_release_grade,
            'fun_date' => $fun_date,
            'fun_count' => $fun_count,
            'fun_grade' => $fun_grade,
            'faith_date' => $faith_date,
            'faith_count' => $faith_count,
            'faith_grade' => $faith_grade,
            'menu_home' => $menu_home
        ];
        return $this->load->view('/web/maptoon/maptoon_main', $return_data, true);
    }

    /*
     * 완결 웹툰 페이지
     */
    function fn_completed()
    {
        $this->config->load('filecache', TRUE);
        $filecache = $this->config->item('file_cache_path', 'filecache');

        // today webtoon
        $this->load->model('maptoon/m_maptoon');
        $today = $this->m_maptoon->get_today_maptoon();
        $today_date = strtolower(date("D"));

        $completed = $this->db->select('l.*, c.name cartoonist')
            ->join('mt_cartoonists c', 'l.mt_cartoonists_idx=c.idx')
            ->get_where('mt_list l', [
            'status' => 1
        ])
            ->result();

        // menu
        $menu_completed = 1;
        $return_data = [
            'completed' => $completed,
            'today' => $today,
            'today_date' => $today_date,
            'menu_completed' => $menu_completed
        ];
        return $this->load->view('/web/maptoon/maptoon_completed', $return_data, true);
    }

    /*
     * 연재 웹툰 페이지
     */
    function fn_ongoing()
    {
        $this->config->load('filecache', TRUE);
        $filecache = $this->config->item('file_cache_path', 'filecache');

        // today webtoon
        $this->load->model('maptoon/m_maptoon');
        $today = $this->m_maptoon->get_today_maptoon();
        $today_date = strtolower(date("D"));

        $this->load->library('maptoon_lib', [
            'file_cache_path' => $filecache
        ]);
        $recomm = $this->maptoon_lib->get_category_cache(13);
        $recomm_arr = json_decode($recomm, TRUE);
        $recomm_date = $this->get_widget_data($recomm_arr, 'reg_date', 6);
        $recomm_count = $this->get_widget_data($recomm_arr, 'view_count', 6);
        $recomm_grade = $this->get_widget_data($recomm_arr, 'grade', 6);

        $story = $this->maptoon_lib->get_category_cache(14);
        $story_arr = json_decode($story, TRUE);
        $story_date = $this->get_widget_data($story_arr, 'reg_date', 3);
        $story_count = $this->get_widget_data($story_arr, 'view_count', 3);
        $story_grade = $this->get_widget_data($story_arr, 'grade', 3);

        $read = $this->maptoon_lib->get_category_cache(15);
        $read_arr = json_decode($read, TRUE);
        $read_date = $this->get_widget_data($read_arr, 'reg_date', 3);
        $read_count = $this->get_widget_data($read_arr, 'view_count', 3);
        $read_grade = $this->get_widget_data($read_arr, 'grade', 3);

        // menu
        $menu_ongoing = 1;
        $return_data = [
            'recomm_date' => $recomm_date,
            'recomm_count' => $recomm_count,
            'recomm_grade' => $recomm_grade,
            'story_date' => $story_date,
            'story_count' => $story_count,
            'story_grade' => $story_grade,
            'read_date' => $read_date,
            'read_count' => $read_count,
            'read_grade' => $read_grade,
            'today' => $today,
            'today_date' => $today_date,
            'menu_ongoing' => $menu_ongoing
        ];
        return $this->load->view('/web/maptoon/maptoon_ongoing', $return_data, true);
    }

    // ---------------------------------------------------------------------------
    // PURPOSE : maptoon list page
    // CREATE : 2019-03-19
    // ---------------------------------------------------------------------------
    function fn_list()
    {
        $mt_id = $this->input->get('mtId');

        if ($mt_id == null) {
            header("Location: /web/maptoon");
        } else {
            $req_data['idx'] = $mt_id;
            $this->load->model('maptoon/m_maptoon');
            // 맵툰 정보
            $mt_data = $this->m_maptoon->get_maptoon_list($req_data);

            if (count($mt_data) == 0) {
                header("Location: /web/maptoon");
            }

            // 공지사항
            $notices = $this->m_maptoon->get_announcement_list($mt_id);
            $arr_notice = array();
            if (count($notices) != 0) {
                $c_date = date("Y-m-d H:i:s");
                foreach ($notices as $val) {
                    if ($val['s_date'] <= $c_date && $c_date <= $val['e_date']) {
                        array_push($arr_notice, $val['contents']);
                    }
                }
            }

            $this->input->get('page') == null ? $page = 1 : $page = $this->input->get('page');
            $limit = 10; // 페이지 당 표시할 에피소드
            $offset = ($page - 1) * $limit;

            $req_data['offset'] = ($page - 1) * $limit;
            $req_data['limit'] = $limit;

            // display episode 가져오기
            $episodes = $this->m_maptoon->get_display_episodes($req_data);
            // print_r($episodes);

            // paging 설정
            if ($page == '')
                $page = 1;

            // pagination
            $page_data = array();
            $page_data['total_count'] = $this->m_maptoon->get_totalcount_episodes($mt_id); // 전체 에피소드 수
            $page_data['limit'] = $limit;
            $page_data['base_url'] = '/web/maptoon/list';

            $this->load->library('mt_pagination');
            $pagination = $this->mt_pagination->create_pagenation($page_data);
            $return_data = $page_data;
            $return_data['page'] = $page;

            $menu_list = 1;
            $return_data['menu_list'] = $menu_list;
            $return_data['pagination'] = $pagination; // page
            $return_data['notice'] = $arr_notice; // 공지사항
            $return_data['mt_data'] = $mt_data; // 맵툰 정보
            $return_data['episodes'] = $episodes; // 에피소드 array

            return $this->load->view('/web/maptoon/maptoon_list', $return_data, true);
        }
    }

    // ---------------------------------------------------------------------------
    // PURPOSE : maptoon article page
    // CREATE : 2019-03-19
    // ---------------------------------------------------------------------------
    function fn_article()
    {
        $mt_idx = $this->input->get('mtId');
        $episode_no = $this->input->get('no');

        $req_data["mt_list_idx"] = $mt_idx;
        $req_data["ep_no"] = $episode_no;

        $this->load->model('maptoon/m_maptoon');
        $episode = $this->m_maptoon->get_episode_by_mt_idx_episode_no($req_data);
        if ($episode == false || $episode == NULL || count($episode) == 0) {
            header("Location: /web/maptoon");
            return false;
        }

        $user_id = $this->session->userdata('C_Member_Id');
        $req_data2 = array(
            'user_id' => $user_id,
            'ep_idx' => $episode['idx']
        );

        // 좋아요 & 별점 참여 유무 확인
        if ($user_id != '' || isset($user_id)) {
            $is_data = $this->m_maptoon->ep_is_like_grade($req_data2);
        }
        if (isset($is_data)) {
            $return_data['is_like'] = $is_data['is_like'];
            $return_data['is_grade'] = $is_data['is_grade'];
        } else {
            $return_data['is_like'] = 0;
            $return_data['is_grade'] = 0;
        }

        // 페이징 데이터 가져오기
        $req_data["ep_idx"] = $episode['idx'];

        $te_req_data['idx'] = $mt_idx;
        $list = $this->m_maptoon->get_display_episodes($te_req_data);
        $return_data['total_ep_count'] = $this->m_maptoon->get_totalcount_episodes($mt_idx);

        // 맵툰 정보 공유 하기 위해
        $mt_req_data['idx'] = $mt_idx;

        // 조회수 업데이트
        $this->m_maptoon->ep_hit_count($req_data2);

        // 누적인기 웹툰
        $mt_pop_rank = $this->m_maptoon->get_mt_pop_rank();

        $mt_data = $this->m_maptoon->get_maptoon_list($mt_req_data);

        $return_data["menu_article"] = 1;
        $return_data["data"] = $episode;
        $return_data["mt_data"] = $mt_data;
        $return_data['mt_pop_rank'] = $mt_pop_rank;
        $return_data['list'] = $list;

        return $this->load->view('/web/maptoon/maptoon_article', $return_data, true);
    }

    // ---------------------------------------------------------------------------
    // PURPOSE : recommened click function ajax
    // CREATE : 2019-03-21
    // ---------------------------------------------------------------------------
    function fn_ajax_recommened()
    {
        $user_id = $this->session->userdata('C_Member_Id');
        $response_data = array();
        if ($user_id == '' || ! isset($user_id)) {
            $message = "로그인이 필요한 서비스입니다.";
            $response_data = array(
                'message' => $message,
                'state' => 0
            );
        } else {
            $ep_idx = $this->input->post('ep_idx');
            $mt_list_idx = $this->input->post('mt_list_idx');
            $req_data = array(
                'user_id' => $user_id,
                'ep_idx' => $ep_idx,
                'mt_list_idx' => $mt_list_idx
            );
            $this->load->model('maptoon/m_maptoon');
            $response_data = $this->m_maptoon->like($req_data);
        }
        echo json_encode($response_data);
    }

    // ---------------------------------------------------------------------------
    // PURPOSE : starScore click function ajax
    // CREATE : 2019-03-25
    // ---------------------------------------------------------------------------
    function fn_ajax_star_score()
    {
        $user_id = $this->session->userdata('C_Member_Id');
        $response_data = array();
        if ($user_id == '' || ! isset($user_id)) {
            $message = "로그인이 필요한 서비스입니다.";
            $response_data = array(
                'message' => $message,
                'state' => 0
            );
        } else {
            $ep_idx = $this->input->post('ep_idx');
            $score = $this->input->post('score');
            $req_data = array(
                'user_id' => $user_id,
                'ep_idx' => $ep_idx,
                'score' => $score
            );
            $this->load->model('maptoon/m_maptoon');
            $response_data = $this->m_maptoon->star_score($req_data);
        }
        echo json_encode($response_data);
    }

    function fn_ajax_mt_recommend()
    {
        $user_id = $this->session->userdata('C_Member_Id');
        $mt_idx = $this->input->post('mt_list_idx');

        if ($user_id == '' || ! isset($user_id)) {
            $message = "로그인이 필요한 서비스입니다.";
            $response_data = array(
                'message' => $message,
                'state' => 0
            );
        } else {
            $req_data = array(
                'user_id' => $user_id,
                'mt_idx' => $mt_idx
            );
            $this->load->model('maptoon/m_maptoon');
            $response_data = $this->m_maptoon->mt_recommend($req_data);
        }
        echo json_encode($response_data);
    }

    function fn_ongoing_1()
    {
        $this->config->load('filecache', TRUE);
        $filecache = $this->config->item('file_cache_path', 'filecache');

        // today webtoon
        $this->load->model('maptoon/m_maptoon');
        $today = $this->m_maptoon->get_today_maptoon();
        $today_date = strtolower(date("D"));

        $this->load->library('maptoon_lib', [
            'file_cache_path' => $filecache
        ]);
        $recomm = $this->maptoon_lib->get_category_cache(13);
        $recomm_arr = json_decode($recomm, TRUE);
        $recomm_date = $this->get_widget_data($recomm_arr, 'reg_date', 6);
        $recomm_count = $this->get_widget_data($recomm_arr, 'view_count', 6);
        $recomm_grade = $this->get_widget_data($recomm_arr, 'grade', 6);

        $story = $this->maptoon_lib->get_category_cache(14);
        $story_arr = json_decode($story, TRUE);
        $story_date = $this->get_widget_data($story_arr, 'reg_date', 3);
        $story_count = $this->get_widget_data($story_arr, 'view_count', 3);
        $story_grade = $this->get_widget_data($story_arr, 'grade', 3);

        $read = $this->maptoon_lib->get_category_cache(15);
        $read_arr = json_decode($read, TRUE);
        $read_date = $this->get_widget_data($read_arr, 'reg_date', 3);
        $read_count = $this->get_widget_data($read_arr, 'view_count', 3);
        $read_grade = $this->get_widget_data($read_arr, 'grade', 3);

        // menu
        $menu_ongoing = 1;
        $return_data = [
            'recomm_date' => $recomm_date,
            'recomm_count' => $recomm_count,
            'recomm_grade' => $recomm_grade,
            'story_date' => $story_date,
            'story_count' => $story_count,
            'story_grade' => $story_grade,
            'read_date' => $read_date,
            'read_count' => $read_count,
            'read_grade' => $read_grade,
            'today' => $today,
            'today_date' => $today_date,
            'menu_ongoing' => $menu_ongoing
        ];
        return $this->load->view('/web/maptoon/maptoon_ongoing_1', $return_data, true);
    }

    function fn_comments()
    {
        $mt_idx = $this->input->get('mtId');
        $episode_no = $this->input->get('no');
        $req_data["mt_list_idx"] = $mt_idx;
        $req_data["ep_no"] = $episode_no;

        $this->load->model('maptoon/m_maptoon');
        $episode = $this->m_maptoon->get_episode_by_mt_idx_episode_no($req_data);
        if ($episode == false || $episode == NULL || count($episode) == 0) {
            header("Location: /web/maptoon");
            return false;
        }

        $user_id = $this->session->userdata('C_Member_Id');
        $req_data2 = array(
            'user_id' => $user_id,
            'ep_idx' => $episode['idx']
        );

        // 좋아요 & 별점 참여 유무 확인
        if ($user_id != '' || isset($user_id)) {
            $is_data = $this->m_maptoon->ep_is_like_grade($req_data2);
        }
        if (isset($is_data)) {
            $return_data['is_like'] = $is_data['is_like'];
            $return_data['is_grade'] = $is_data['is_grade'];
        } else {
            $return_data['is_like'] = 0;
            $return_data['is_grade'] = 0;
        }

        // 페이징 데이터 가져오기
        $req_data["ep_idx"] = $episode['idx'];

        $te_req_data['idx'] = $mt_idx;
        $list = $this->m_maptoon->get_display_episodes($te_req_data);
        $return_data['total_ep_count'] = $this->m_maptoon->get_totalcount_episodes($mt_idx);

        // 맵툰 정보 공유 하기 위해
        $mt_req_data['idx'] = $mt_idx;

        // 조회수 업데이트
        $this->m_maptoon->ep_hit_count($req_data2);

        // 누적인기 웹툰
        $mt_pop_rank = $this->m_maptoon->get_mt_pop_rank();

        $mt_data = $this->m_maptoon->get_maptoon_list($mt_req_data);

        $return_data["menu_article"] = 1;
        $return_data["data"] = $episode;
        $return_data["mt_data"] = $mt_data;
        $return_data['mt_pop_rank'] = $mt_pop_rank;
        $return_data['list'] = $list;

        return $this->load->view('/web/maptoon/maptoon_comments', $return_data, true);
    }
}