<?php if (!defined('BASEPATH')) {
    exit('No direct script access allowed');
}

class Grace extends MY_Controller
{
    private $sections;

    public function __construct()
    {
        parent::__construct();
        $this->load->model('post_model', 'post');
        $this->load->model('comment_model', 'comment');
    }

    public function index()
    {
        if ($this->isMobile()) {
            $this->mobile();
        } else {
            $this->desktop();
        }
    }

    private function desktop()
    {
        $section = $this->uri->segment(2);
        $article = $this->uri->segment(3);
        $this->data['sectionCategory'] = NEWS_SECTION_CATEGORY;
        if (is_numeric($article)) {
            $this->article($article);
            $this->load->view('templates/grace/grace-article', $this->data);
        } elseif ($section) {
            $this->section();
            $this->load->view('templates/grace/grace-section', $this->data);
        } else {
            $this->main();
            $this->load->view('templates/grace/grace-home', $this->data);
        }
    }

    private function mobile()
    {
        $section = $this->uri->segment(2);
        $article = $this->uri->segment(3);
        if (is_numeric($article)) {
            $this->load->view('mobile/grace/grace-article', $this->data);
        } else if ($article) {
            $this->load->view('mobile/grace/grace-editor', $this->data);
        } elseif ($section) {
            $this->load->view('mobile/grace/grace-section', $this->data);
        } else {
            $this->load->view('mobile/grace/grace-home', $this->data);
        }
    }

    private function main()
    {
        $this->data['featured'] = $this->post->getPagePostsByCategoryId(getChildrenByParentId(30000), 5)
            ->join('cm_user u', 'p.userID=u.userID', 'left')->where('img !=', '')
            ->order_by('p.dateUpdated', 'desc')->group_by('pp.pageID')
            ->get()->result();
        $this->getLink($this->data['featured']);
        $this->setSections();
        foreach ($this->sections as $k => $s) {
            if($k == 'search') continue;
            $this->data[$k] = $this->sections[$k][2]()
                ->join('cm_user u', 'p.userID=u.userID', 'left')
                ->join('cm_page_attributes pa', 'pp.pageID=pa.pageID', 'left')
                ->join('cm_page_content pcn', 'pp.pageID=pcn.pageID', 'left')
                ->select('p.*')
                ->select('if(pa.pageIcon is null, if(pcn.img is null, if(u.profile_img is null, p.postImage, u.profile_img), pcn.img), pa.pageIcon) pageIcon')
                ->select('0 likes, 0 views, 0 comments')
                ->select("if(u.nickname = '' or u.nickname is null, u.userName, u.nickName) as author")
                ->group_by('p.postID')
                ->get()->result();
            $this->getLink($this->data[$k]);
        }
        foreach ($this->data as $k => $v) {
            getPostsImageUrl($this->data[$k]);
        }
    }

    private function setSections()
    {
        // 은혜충전(구 라이프)의 해당 카테고리의 최신 글 테그
        // 은혜충전(구 라이프)의 해당 카테고리의 업데이트 순과 좋아요순 
        // 페이징처리

        $this->sections = [
            'storyqt' => [[30005, 30008], function () {
                return $this->post->getCountPostsByPageIdAndCategoryId($this->sections['storyqt'][0][0], $this->sections['storyqt'][0][1]);
            }, function () {
                return $this->post->getPostsByPageIdAndCategoryId($this->sections['storyqt'][0][0], $this->sections['storyqt'][0][1], 20);
            }],
            'wordcard' => [[30003, 30005], function () {
                return $this->post->getCountPostsByPageId($this->sections['wordcard'][0]);
            }, function () {
                return $this->post->getPostsByPageId($this->sections['wordcard'][0], 20);
            }],
            'english' => [[30005, 30008], function () {
                return $this->post->getCountPostsByPageIdAndCategoryId($this->sections['english'][0][0], $this->sections['english'][0][1]);
            }, function () {
                return $this->post->getPostsByPageIdAndCategoryId($this->sections['english'][0][0], $this->sections['english'][0][1], 20);
            }],
            'videoqt' => [null, function () {
                return $this->post->getPostQuery()->join('cm_post_video v', 'p.postID=v.postID', 'inner')->count_all_results();
            }, function () {
                return $this->post->getPostQuery()->join('cm_post_video v', 'p.postID=v.postID', 'inner')->limit(20);
            }],
            'cpost' => [[30006, 30008], function () {
                return $this->post->getCountPostsByPageId($this->sections['cpost'][0]);
            }, function () {
                return $this->post_model->getPostsByPageId($this->sections['cpost'][0], 20);
            }],
            'poem' => [[30043], function () {
                return $this->post->getCountPostsByPageId($this->sections['poem'][0]);
            }, function () {
                return $this->post_model->getPostsByPageId($this->sections['poem'][0], 20);
            }],
            'popular' => [[30043], function () {
                return $this->post->getCountPostsByPageId($this->sections['poem'][0]);
            }, function () {
                return $this->post_model->getPostsByPageId($this->sections['poem'][0], 20);
            }],
            'tagFeatured' => [[30043], function () {
                return $this->post->getCountPostsByPageId($this->sections['poem'][0]);
            }, function () {
                return $this->post_model->getPostQuery()->join('cm_post_tag t', 'p.postID=t.postID', 'left');
            }],
            'search' => [[30043], function () {
                $this->load->library('search');
                return $this->search->searchByPostTitle($this->input->get('keyword'), 20, [], true)->count_all_results();
            }, function () {
                $this->load->library('search');
                return $this->search->searchByPostTitle($this->input->get('keyword'), 20, [], true)
                    ->join('cm_post_page pp', 'p.postID=pp.postID', 'left')->limit(20);
            }]
        ];
    }

    private function section()
    {
        $this->setSections();
        $this->load->library('pagination');
        $this->data['totalRows'] = $this->sections[$this->uri->segment(2)][1]();
        $this->pagination->initialize([
            'base_url' => BASE_URL . '/grace/' . $this->uri->segment(2),
            'total_rows' => $this->data['totalRows'],
            'per_page' => 20,
            'full_tag_open' => '',
            'full_tag_close' => '',
            'num_tag_open' => '',
            'num_tag_close' => '',
            'cur_tag_open' => '<a class="current">',
            'cur_tag_close' => '</a>',
            'next_tag_open' => '',
            'next_tag_close' => '',
            'prev_tag_open' => '',
            'prev_tag_close' => '',
            'next_link' => '',
            'prev_link' => '',
            'last_link' => '<img src="' . THEME_FOLDER . '/img/mypage_arrow_right.gif">',
            'first_link' => '<img src="' . THEME_FOLDER . '/img/mypage_arrow_left.gif">',
            'prefix' => 'page-',
            'suffix' => $this->input->get('keyword') ? '?keyword='. $this->input->get('keyword') :''
        ]);
        $countQuery = $this->db->last_query();
        $this->data['posts'] = $this->sections[$this->uri->segment(2)][2]()->offset(
            $this->uri->segment(3) ? str_replace('page-', '', $this->uri->segment(3)) : 0
        )->join('cm_user u', 'p.userID=u.userID', 'left')
            ->join('cm_page_attributes pa', 'pp.pageID=pa.pageID', 'left')
            ->join('cm_page_content pcn', 'pp.pageID=pcn.pageID', 'left')
            ->select('p.*, if(pa.pageIcon is null, if(pcn.img is null, if(u.profile_img is null, p.postImage, u.profile_img), pcn.img), pa.pageIcon) pageIcon,  0 likes, 0 views, 0 comments, u.userName')->get()->result();

        $sqlSegments = explode('WHERE', explode('FROM', $countQuery)[1]);
        $tags = $this->db->query('select t.tag from ' . $sqlSegments[0] . ($this->uri->segment(2) == 'search' ? ' ':' inner join cm_post_tag t on p.postID=t.postID ')  . (isset($sqlSegments[1]) ? 'where ' . $sqlSegments[1] : '') . ' order by p.dateUpdated desc')->result();
        // $this->sections[$this->uri->segment(2)][2]()->join('cm_post_tag t', 'p.postID=t.postID', 'inner');
        $this->data['tags'] = [];
        foreach ($tags as $t) {
            $this->data['tags'] = array_merge($this->data['tags'], explode(strpos($t->tag, ',')? ',': ' ', $t->tag));
        }

        if(count($this->data['posts'])) {
            array_map(function ($c) {
                foreach ($this->data['posts'] as $k => $v) {
                    if ($v->postID == $c->postID) {
                        $this->data['posts'][$k]->comments = $c->cnt;
                    }
                }
            }, $this->comment->getCountByPostId(array_column($this->data['posts'], 'postID'))->get()->result());
            array_map(function ($c) {
                foreach ($this->data['posts'] as $k => $v) {
                    if ($v->postID == $c->postID) {
                        if ($c->title == 'L') {
                            $this->data['posts'][$k]->likes = $c->rating;
                        } else {
                            $this->data['posts'][$k]->views = $c->rating;
                        }
                    }
                }
            }, $this->post->getPostsRankingByPostId(array_column($this->data['posts'], 'postID'))->get()->result());
        }
        $this->data['tags'] = array_unique($this->data['tags']);
        $this->getLink($this->data['posts']);
    }

    private function article($article)
    {
        $this->load->model('comment_model');
        $section = $this->uri->segment(2);

        $this->data['comments'] = $this->comment_model->getByPostId($article)
            ->where('parentID', 0)
            ->join('cm_user', 'cm_comment.userID=cm_user.userID', 'left')
            ->select('*, 0 like, 0 bad, 0 replies')->get()->result();

        $this->comment_model->getRepliesAndRankings($this->data['comments']);

        $this->data['post'] = $this->post->getPostQuery()->join('cm_user u', 'p.userID=u.userID', 'left')
            ->join('cm_page_attributes pa', 'pp.pageID=pa.pageID', 'left')
            ->join('cm_page_content pcn', 'pp.pageID=pcn.pageID', 'left')
            ->where('p.postID', $this->uri->segment(3))->get()->row();
        $this->data['video'] = $this->post->getPostVideo($this->data['post']->postID);


        $this->setSections();
        foreach ($this->sections as $k => $s) {
            if($k == 'search') continue;
            $this->data[$k] = $this->sections[$k][2]()
                ->join('cm_user u', 'p.userID=u.userID', 'left')
                ->join('cm_page_attributes pa', 'pp.pageID=pa.pageID', 'left')
                ->join('cm_page_content pcn', 'pp.pageID=pcn.pageID', 'left')
                ->select('p.*')
                ->select('if(pa.pageIcon is null, if(pcn.img is null, if(u.profile_img is null, p.postImage, u.profile_img), pcn.img), pa.pageIcon) pageIcon')
                ->select('0 likes, 0 views, 0 comments')
                ->select("if(u.nickname = '' or u.nickname is null, u.userName, u.nickName) as author")
                ->group_by('p.postID')
                ->get()->result();
            $this->getLink($this->data[$k]);
        }        
        $this->load->library('search');
        $this->data['related'] = $this->search->searchByPostTitle($this->data['post']->postTitle, 12, [$this->data['post']->postID], true)
            ->join('cm_user u', 'cm_post.userID=u.userID', 'left')
            ->select("*,if(u.nickname = '' or u.nickname is null, u.userName, u.nickName) as author")->get()->result();
        $this->getLink($this->data['related']);
        foreach ($this->data as $k => $v) {
            getPostsImageUrl($this->data[$k]);
        }
    }

    private function getLink(&$rows)
    {
        array_walk($rows, function (&$r) {
            $r->articleURL = '/grace/' . ($this->uri->segment(2) ? $this->uri->segment(2) : 'cpost')  . '/' . $r->postID;
        });
    }
}
