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

class Grace extends CI_Controller
{

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

    private $graceCategories = array(30, 31, 32, 33, 34, 46);
    private $graceCategoryDetail = array();

    public function __construct()
    {
        parent::__construct();
        $this->load->library('Post', '', 'post');
        $this->load->model('life_model');
        $this->load->model('editor_model');
        $this->load->model('category_model');
        $this->load->model('config_model');
        $graceCategoryDetail = $this->category_model->findByParentId(35)->result();
        foreach ($graceCategoryDetail as $category) {
            $this->graceCategoryDetail[$category->idx] = $category;
        }
    }

    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 = 'grace' and c.Page = 'gracehometop'
            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->getPostsByCategoryId($this->graceCategories, 3 - count($graceHomeConfigured), 'reg_date', 'desc', $graceHomeTopConfigured);
            $slide = array_merge($graceHomeConfigured, $slide);
        } else {
            $slide = $this->post->getPostsByCategoryId($this->graceCategories, 3, 'reg_date');
        }
        foreach (array(
            'wordCards' => array(30, 8),
            'books' => array(31, 8),
            'dailyQt' => array(32, 8),
            'engWords' => array(33, 2),
            'qna' => array(34, 2)) 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->getPostsByCategoryId($this->graceCategories, 6, 'hit_count', 'desc');
        $data['slide'] = $slide;
        $data['post'] = $slide[0];
        $data['graceCategories'] = $this->graceCategoryDetail;
        $data['newUpdated'] = array_merge(array('a'), $newUpdated);
        $this->load->view('grace/grace', $data);
    }

    public function category()
    {
        $categoryTitle = urldecode($this->uri->segment(3));
        $categoryId = $this->uri->segment(4);
        if(!isset($this->graceCategoryDetail[$categoryId])) { 
            go('/grace');
            exit(301);
        }
        if (!$categoryId) {
            show_404();
        }

        $orderByLikes = $this->uri->segment(5);
        $cmConfig = $this->config_model->findByTypeAndNameAndPage('display', 'grace', 'submenu-top')->get();
        if ($cmConfig->num_rows()) {
            $cfPostId = array();
            foreach ($cmConfig->result() as $cf) {
                array_push($cfPostId, $cf->PostId);
            }
            $configuredPosts = $this->post->getPostJoin1(implode(",", $cfPostId));
            if ($configuredCount = count($configuredPosts)) {
                if ($configuredCount < 6) {
                    $slide = $this->post->getPostsByCategoryId($this->graceCategories, 6 - $configuredCount, 'reg_date', 'desc', $cfPostId);
                    $slide = array_merge($this->post->urify($configuredPosts), $slide);
                } else {
                    $slide = $this->post->urify($configuredPosts);
                }
            } else {
                $slide = $this->post->getPostsByCategoryId($this->graceCategories, 6, 'reg_date');
            }
        } else {
            $slide = $this->post->getPostsByCategoryId($categoryId, 6, 'reg_date');
        }
        // print_r($slide);die;

        $slideIdx = array();
        foreach ($slide as $s) {
            array_push($slideIdx, $s->idx);  
        }
        $posts = $this->post->getPostsByCategoryId($categoryId, 16, $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' => $posts,
            'post' => &$posts[0],
            'editorTotal' => $editorTotal,
            'isLikesOrder' => $orderByLikes,
            'editors' => $this->editor_model->findByCategoryId($categoryId)->limit(6)->get()->result(),
            'graceCategories' => $this->graceCategoryDetail,
            'categoryTitle' => empty($this->graceCategoryDetail[$categoryId]) ? $categoryTitle : $this->graceCategoryDetail[$categoryId]->category_name,
            'categoryId' => $categoryId,
            'categoryDescription' => $this->graceCategoryDetail[$categoryId]->description,
            'pageInitPostIds' => array_merge($slideIdx, $postIds),
        );
        $this->load->view('grace/category', $data);
    }

    public function editor()
    {
        $orderByLikes = $this->uri->segment(5);
        $editorId = $this->uri->segment(4);
        $posts = $this->post->getEditorPosts($editorId, 16, $orderByLikes ? 'like_count' : 'update_date');
        $this->load->view('grace/editor', array(
            'posts' => $posts,
            'post' => &$posts[0],
            'editor' => $this->editor_model->findById($this->uri->segment(4)),
            'graceCategories' => $this->graceCategoryDetail,
            'isLikesOrder' => $orderByLikes,
            'pageInitPostIds' => array_map(function ($p) {return $p->idx;}, $posts),
        ));
    }

    public function view()
    {
        $postId = $this->uri->segment(3);
        $data = array('post' => $this->post->getPost($postId), 'graceCategories' => $this->graceCategoryDetail);
        if ($data['post']) {
            $data['editorPosts'] = $this->post->getEditorPosts($data['post']->partner_idx, 4, 'update_date', 'desc', [$data['post']->idx]);

            $excepts = array($data['post']->idx);
            foreach ($data['editorPosts'] as $p) {
                array_push($excepts, $p->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;
            $data['recentPosts'] = $this->post->getPostsByCategoryId($this->graceCategories, 8, 'update_date', 'desc', $excepts);
            $this->load->view('grace/view', $data);
        } else {
            header('location:/grace');
        }
    }

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

        if($page == 'editor') {
            $posts = $this->post->getEditorPosts($pageId, 16, $orderByLikes ? 'like_count' : 'update_date', 'desc', $excepts);
        }else if($page == 'category') {
            $posts = $this->post->getPostsByCategoryId($pageId, 16, $orderByLikes ? 'like_count' : 'update_date', 'desc', $excepts);
        }else {
            $posts = $this->post->getEditorPosts($pageId, 16, $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);
        }
        echo json_encode(array('code' => 200, 'message' => 'success', 'data' => $posts));
    }

}
