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

class Cmtv extends CI_Controller
{

    private $parentCategoryName = 'crossmaptv';

    private $categoryDescription = array(
        30 => '언제나 하나님 안에서 글을 품는 여행작가',
        31 => '삶과 믿음의 지혜와 지식',
        32 => '매일매일 은혜를 채우는 시간',
        33 => '영어로 성경을 읽어봐요',
        34 => '신앙에 질문들 모조리 답해드립니다',
    );

    private $cmtvCategories = array();
    private $cmtvCategoryId = array();
    private $cmtvCategoryDetail = array();

    public function __construct()
    {
        parent::__construct();
        $this->load->library('user_agent');
        $this->cmtvCategories = $this->config->item('categories')[$this->parentCategoryName];
        $this->cmtvCategoryId = array_values($this->cmtvCategories);
        $this->load->library('Post', '', 'post');
        $this->load->model('editor_model');
        $this->load->model('category_model');
        $this->load->model('config_model');
        $cmtvCategoryDetail = $this->category_model->findById($this->cmtvCategoryId)->result();
        foreach ($cmtvCategoryDetail as $category) {
            $this->cmtvCategoryDetail[$category->idx] = $category;
        }
		$this->db->query("SET  sql_mode = 'STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'");
    }

    private function getIndexSlide()
    {
        $query = $this->db->query("SELECT
            `p`.`idx` `editorId`,
            `p`.`partner_img` `editorImg`,
            `p`.`main_img` `editorMainImg`,
            `p`.`partner_name` `editorName`,
            `p`.`partner_intro` `editorIntro`,
            `l`.`title`,
            `l`.`head_title`,
            `l`.`sub_title`,
            `l`.`content`,
            `l`.`category_idx` `categoryId`,
            `l`.`idx`,
            `l`.`main_img` `mainImg`,
            `l`.`hit_count` `views`,
            `l`.`like_count` `likes`,
            `l`.`comment_count` `comments`,
            `l`.*
        FROM
            `life` `l`
                LEFT JOIN
            `partner` `p` ON `l`.`partner_idx` = `p`.`idx`
            inner join cm_config c on l.idx = c.PostId
        WHERE
            c.Type = 'cmtv' and c.Page = 'cmtvhomehot'
            AND `l`.`is_display` = 'Y'
            AND `l`.`is_del` = 'N' order by c.OrderNum");
        return $this->post->urify($query->result());
    }

    private function getCategorySlide($categoryId)
    {
        $query = $this->db->query("SELECT
            `p`.`idx` `editorId`,
            `p`.`partner_img` `editorImg`,
            `p`.`main_img` `editorMainImg`,
            `p`.`partner_name` `editorName`,
            `p`.`partner_intro` `editorIntro`,
            `l`.`title`,
            `l`.`head_title`,
            `l`.`sub_title`,
            `l`.`content`,
            `l`.`category_idx` `categoryId`,
            `l`.`idx`,
            `l`.`main_img` `mainImg`,
            `l`.`hit_count` `views`,
            `l`.`like_count` `likes`,
            `l`.`comment_count` `comments`,
            `l`.*
        FROM
            `life` `l`
                LEFT JOIN
            `partner` `p` ON `l`.`partner_idx` = `p`.`idx`
            inner join cm_config c on l.idx = c.PostId
        WHERE
            c.Type = 'cmtv' and c.Page = 'categorylatest' and c.CategoryId = $categoryId
            AND `l`.`is_display` = 'Y'
            AND `l`.`is_del` = 'N' order by c.OrderNum");
        return $this->post->urify($query->result());
    }

    public function index()
    {
        $graceHomeConfigured = $this->getIndexSlide();
        if (count($graceHomeConfigured)) {
            $graceHomeTopConfigured = array();
            foreach($graceHomeConfigured as $c) {
                $graceHomeTopConfigured[] = $c->idx;
            }
            $slide = $this->post->getPostsEditorRecent($this->cmtvCategoryId, 8 - count($graceHomeConfigured), 'reg_date', 'desc', $graceHomeTopConfigured);
            $slide = array_merge($graceHomeConfigured, $slide);
        } else {
            $slide = $this->post->getPostsEditorRecent($this->cmtvCategoryId, 8, 'reg_date');
        }


        $ignores = array();
        foreach ($slide as $s) {
            array_push($ignores, $s->idx);
        }

        $slide2 = $this->post->getPostsByCategoryId($this->cmtvCategoryId, 8 - count($slide), 'reg_date', 'desc', $ignores);
        foreach ($slide2 as $s) {
            array_push($slide, $s);
        }

        foreach (array(
            'word' => array($this->cmtvCategories['word'], $this->agent->is_mobile() ? 6 : 10),
            'worship' => array($this->cmtvCategories['worship'], $this->agent->is_mobile() ? 6 : 10),
            'social' => array($this->cmtvCategories['social'], $this->agent->is_mobile() ? 6 : 10),
            'tv' => array($this->cmtvCategories['tv'], $this->agent->is_mobile() ? 6 : 10)) as $category => $props) {
            $data[$category] = $this->post->getPostsByCategoryId($props[0], $props[1]);
        }
        $newUpdated = array('a');
        foreach ($data as $k => $v) {
            foreach ($v as $p) {
                if (time() - 3600 * 24 > strtotime($p->update_date)) {
                    array_push($newUpdated, $k);
                    break;
                }
            }
        }

        $data['popularPosts'] = $this->post->getTop10($this->cmtvCategoryId);
        $data['editors'] = $this->editor_model->findByCategoryId($this->cmtvCategoryId)->limit(4)->get()->result();
        $data['slide'] = $slide;
        $data['post'] = $slide[0];
        $data['cmtvCategories'] = $this->cmtvCategoryDetail;
        $data['newUpdated'] = array_merge(array('a'), $newUpdated);
        $this->load->view('cmtv/cmtv', $data);
    }

    public function category()
    {
        $categoryTitle = urldecode($this->uri->segment(3));
        $categoryId = $this->uri->segment(4);
        if (!$categoryId) {
            show_404();
        }

        $orderByLikes = $this->uri->segment(5);




        $graceHomeConfigured = $this->getCategorySlide($categoryId);
        if (count($graceHomeConfigured)) {
            $graceHomeTopConfigured = array();
            foreach($graceHomeConfigured as $c) {
                $graceHomeTopConfigured[] = $c->idx;
            }
            $slide = $this->post->getPostsEditorRecent($this->cmtvCategoryId, 8 - count($graceHomeConfigured), 'reg_date', 'desc', $graceHomeTopConfigured);
            $slide = array_merge($graceHomeConfigured, $slide);
        } else {
            $slide = $this->post->getPostsEditorRecent($categoryId, 8, 'reg_date');

        }


        $ignores = array();
        foreach ($slide as $s) {
            array_push($ignores, $s->idx);
        }

        $slide2 = $this->post->getPostsByCategoryId($categoryId, 8 - count($slide), 'reg_date', 'desc', $ignores);
        foreach ($slide2 as $s) {
            array_push($slide, $s);
        }

        $slideIdx = array();
        foreach ($slide as $s) {
            array_push($slideIdx, $s->idx);
        }
        $posts = $this->post->getPostsByCategoryId($categoryId, 21, $orderByLikes ? 'like_count' : 'update_date', 'desc', $slideIdx);

        $postIds = array();
        foreach ($posts as $p) {
            array_push($postIds, $p->idx);
        }

        $editorTotal = $this->editor_model->findByCategoryId($categoryId)->count_all_results();
        $data = array(
            'slide' => $slide,
            'posts' => array_slice($posts, 0, 20),
            'isPostMore' => count($posts) > 20,
            'post' => &$slide[0],
            'editorTotal' => $editorTotal,
            'isLikesOrder' => $orderByLikes,
            'editors' => $this->editor_model->getEditors($categoryId, 4),
            'cmtvCategories' => $this->cmtvCategoryDetail,
            'categoryTitle' => $this->cmtvCategoryDetail[$categoryId]->category_name,
            'categoryId' => $categoryId,
            // 'categoryDescription' => $this->categoryDescription[$categoryId],
            'pageInitPostIds' => array_merge($slideIdx, $postIds),
        );
        $data['popularPosts'] = $this->post->getTop10($categoryId);
        $this->load->view('cmtv/category', $data);
    }

    private function getChannelEditorPick($alternativePost) {
        $config = $this->config_model->findByTypeAndPage('cmtv', 'channellatest')->get()->result();
        foreach($config as $c) {
            if($c->CategoryId == $this->uri->segment(4)) return $this->post->getPost($c->PostId);
        }
        return $alternativePost;
    }

    public function channel()
    {
        $viewTypeVideos = $this->uri->segment(5);
        $editorId = $this->uri->segment(4);
        $posts = $this->post->getEditorPosts($editorId, $this->agent->is_mobile() ? 8 : 15, $viewTypeVideos == 'views' ? 'like_count' : 'update_date');
        $postIds = array();
        foreach ($posts as $p) {
            array_push($postIds, $p->idx);
        }
        $this->load->view('cmtv/channel' . ($viewTypeVideos ? '_videos' : ''), array(
            'posts' => $posts,
            'post' => $this->getChannelEditorPick($posts[0]),
            'editor' => $this->editor_model->findById($this->uri->segment(4)),
            'cmtvCategories' => $this->cmtvCategoryDetail,
            'isLikesOrder' => $viewTypeVideos == 'views',
            'pageInitPostIds' => $postIds,
        ));
    }

    public function channels()
    {
        $orderByLikes = $this->uri->segment(5);
        $categoryId = $this->uri->segment(4);
        $data = array('channels' => $this->editor_model->findByCategoryId($categoryId)->limit(24)->get()->result(),
            'channels' => $this->editor_model->findByCategoryId($categoryId)->limit(24)->get()->result(),
            'cmtvCategories' => $this->cmtvCategoryDetail);
        $data['post'] = $data['channels'][rand(0, count($data['channels']) - 1)];
        $data['post']->title = $data['post']->editorName;
        $data['post']->content = $data['post']->editorIntro;
        $data['post']->mainImg = $data['post']->editorImg;
        $this->load->view('cmtv/channels', $data);
    }

    public function view()
    {
        $postId = $this->uri->segment(3);
        $data = array('post' => $this->post->getPost($postId), 'cmtvCategories' => $this->cmtvCategoryDetail);
        $data['post']->views = $data['post']->views + 1;
        $this->db->where('idx', $data['post']->idx)->update('life', array('hit_count' => $data['post']->views));
        if ($data['post']) {
            $editorPosts = $this->post->getEditorPosts($data['post']->partner_idx, 100, 'update_date', 'desc', [$data['post']->idx]);
            $data['editorPost'] = $editorPosts[rand(0, count($editorPosts)-1)];

            $excepts = array($data['post']->idx);
            array_push($excepts, $data['editorPost']->idx);

            $data['iLike'] = $this->session->userdata('C_Member_Id') ? $this->db->where('content_idx', $postId)->where('content_type', 3)->where('member_id', $this->session->userdata('C_Member_Id'))->from('like_log')->count_all_results() : false;
            $recents = $this->post->getPostsByCategoryId($this->cmtvCategoryId, 1000, 'update_date', 'desc', $excepts);
            shuffle($recents);
            $data['recentPosts'] = array_slice($recents, 0, 15);
            $this->load->view('cmtv/view', $data);
        } else {
            header('location:/cmtv');
        }
    }

    public function posts()
    {
        $excepts = $this->input->post('excepts') ? explode(',', $this->input->post('excepts')) : array(0);
        $page = $this->input->post('page');
        $pageId = $this->input->post('pageId');
        $orderByLikes = $this->input->post('orderBy');

        $posts = $page == 'editor' ? $this->post->getEditorPosts($pageId, 10, $orderByLikes == 'views' ? 'hit_count' : 'update_date', 'desc', $excepts) :
        ($page == 'category' ? $this->post->getPostsByCategoryId($pageId, 10, $orderByLikes ? 'like_count' : 'update_date', 'desc', $excepts) :
            $this->post->getEditorPosts($pageId, 10, $orderByLikes ? 'like_count' : 'update_date', 'desc', $excepts)
        );

        foreach ($posts as $k => $p) {
            $posts[$k]->editorNameUrl = cleanUrl($posts[$k]->editorName);
            $posts[$k]->mainImg = imgSrc($posts[$k]->mainImg);
            $posts[$k]->timeAgo = time_elapsed_string($posts[$k]->reg_date);
        }
        echo json_encode(array('code' => 200, 'message' => 'success', 'data' => $posts));
    }

}
