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

class News extends MY_Controller
{

    public function __construct()
    {
        parent::__construct();
    }

    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/news/news-article', $this->data);
        } elseif ($section) {
            $this->section();
            $this->load->view('templates/news/news-section', $this->data);
        } else {
            $this->main();
            $this->load->view('templates/news/news-home', $this->data);
        }
    }

    private function mobile()
    {
        $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('mobile/news/news-article', $this->data);
        } elseif ($section) {
            list($section, $children) = $this->getSectionSegments();
            $this->data['posts'] = $this->getSectionPosts($children, 26);
            getNewsArticleURL($this->data['posts'], $section);
            $this->load->library('search');
            $this->data['relatedNews'] = $this->search->searchByPostTitle($this->data['posts'][0]->postTitle, 2, [$this->data['posts'][0]->postSeq]);
            getNewsArticleURL($this->data['relatedNews'], $section);
            $this->data['hotNews'] = getNewsArticleURL($this->post_model->getPostsRankingByRankTypeAndCategoryId('V', $children, 27)->get()->result());
            $this->data['photoNews'] = $this->post_model->getPostsRankingByRankTypeAndCategoryId('V', 30024, 3)->get()->result();
            $this->load->view('mobile/news/news-section', $this->data);
        } else {
            $this->main();
            $this->load->view('mobile/news/news-home', $this->data);
        }
    }

    public function main()
    {
        $this->data['posts'] = [];
        $this->data['sortByPosted'] = [];
        $this->load->model('category_model');
        $this->load->model('post_model');

        $sectionCategories = $this->category_model->getAll(array_values(NEWS_SECTION_CATEGORY));
        foreach (NEWS_SECTION_CATEGORY as $sn => $sc) {
            $children = getChildrenByParentId($sc);
            $this->data['posts'][$sn] = $this->post_model->getPostsByCategoryId($children, 7)->get()->result();
            $contentSection = ($sn == 'opinions' ? 'channel' : 'news');
            $sectionCategory = ['title' => '', 'id' => 0];
            foreach ($sectionCategories as $s) {
                if ($s->categoryID == $sc) {
                    $sectionCategory['title'] = $s->categoryTitle;
                    $sectionCategory['id'] = $s->categoryID;
                }
            }
            foreach ($this->data['posts'][$sn] as $post) {
                $post->sectionCategory = $sectionCategory;
                $post->articleURL = '/' . $contentSection . '/' . ($sn == 'opinions' ? $post->pageID : $sn) . '/' . $post->postSeq;
                !count($this->data['sortByPosted']) ? (function () use ($post) {
                    array_push($this->data['sortByPosted'], $post);
                })() : (function () use ($post) {
                    array_push($this->data['sortByPosted'], $post);
                    if (strtotime($post->datePosted) > strtotime($this->data['sortByPosted'][0]->datePosted)) {
                        $l = array_shift($this->data['sortByPosted']);
                        array_push($this->data['sortByPosted'], $l);
                    }
                })();
            }
        }
        $this->data['hotNews'] = getNewsArticleURL($this->post_model->getPostsRankingByRankTypeAndCategoryId(
            'V',
            getChildrenByParentId(10000),
            27
        )->get()->result());
        $this->data['photoNews'] = $this->post_model->getPostsRankingByRankTypeAndCategoryId('V', 30024, 3)->get()->result();
        $this->data['prayNews'] = $this->post_model->getPostsByPageId(30009, 4)->get()->result();
        foreach ($this->data as $k => $v) {
            getPostsImageUrl($this->data[$k]);
        }
    }

    public function section()
    {
        list($section, $children) = $this->getSectionSegments();
        $this->pagination->initialize([
            'base_url' => BASE_URL . '/news/' . $section,
            'total_rows' => $this->post_model->getCountPostsByCategoryId($children),
            'per_page' => 10,
            '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-'
        ]);
        $this->data['posts'] = $this->getSectionPosts($children, 17);
        getNewsArticleURL($this->data['posts'], $section);
        $this->data['sortByPosted'] = [];
        array_push($this->data['sortByPosted'], $this->data['posts'][0]);
        $this->data['sortByPosted'] = array_merge($this->data['sortByPosted'], array_slice($this->data['posts'], 3, 6));
        $this->data['posts1'] = array_slice($this->data['posts'], 1, 3);
        $this->data['posts2'] = array_slice($this->data['posts'], 9);
        $this->data['posts'] = array_merge($this->data['posts1'], $this->data['posts2']);
        unset($this->data['posts1'], $this->data['posts2']);
        $this->data['hotNews'] = getNewsArticleURL($this->post_model->getPostsRankingByRankTypeAndCategoryId('V', $children, 27)->get()->result());
        $this->data['photoNews'] = $this->post_model->getPostsRankingByRankTypeAndCategoryId('V', 30024, 3)->get()->result();
        $this->data['prayNews'] = $this->post_model->getPostsByPageId(30009, 4)->get()->result();
        foreach ($this->data as $k => $v) {
            getPostsImageUrl($this->data[$k]);
        }
    }

    private function getSectionSegments()
    {
        $this->load->model('post_model');
        $section = $this->uri->segment(2);
        $this->load->library('pagination');
        $children = getChildrenByParentId(NEWS_SECTION_CATEGORY[$section]);
        array_push($children, NEWS_SECTION_CATEGORY[$section]);
        return [$section, $children];
    }

    private function getSectionPosts($children, $rowCount)
    {
        return $this->post_model->getPostsByCategoryId($children, $rowCount, ($this->uri->segment(3) ? substr($this->uri->segment(3), 5) : 0))->get()->result();
    }

    public 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['page'] = $this->post_model->getPost($article);
        $this->data['column'] = $this->getColumn();
        // $this->data['focus'] = $this->post_model->getPostsByPageId(30, 0, 0, 10000, [$this->data['page']['postID']]);
        $this->data['page']->parentTitle = '';
        if ($this->data['page']->parentID != 0 && $this->data['page']->parentID % 10000 !== 0) {
            $parentCategory = $this->category_model->getOne($this->data['page']->parentID);
            if ($parentCategory) {
                $this->data['page']->parentTitle = $parentCategory->categoryTitle;
            }
        }
        $this->data['reporter'] = $this->getReporterByUserId($this->data['page']->userID);
        $this->data['ranking'] = $this->getRankingByPostId($this->data['page']->postSeq);

        $this->data['hotNews'] = getNewsArticleURL($this->post_model->getPostsRankingByRankTypeAndCategoryId('V', getChildrenByParentId(NEWS_SECTION_CATEGORY[$section]), 27)->get()->result());

        $this->data['photoNews'] = $this->post_model
            ->getPostsRankingByRankTypeAndCategoryId('V', 30024, 3)->get()->result();
        $this->data['prayNews'] = $this->post_model->getPostsByPageId(30009, 4)->get()->result();
        $this->load->library('search');
        $this->data['relatedNews'] = $this->search->searchByPostTitle($this->data['page']->postTitle, 5, [$this->data['page']->postSeq]);
        getNewsArticleURL($this->data['relatedNews'], $section);
        foreach ($this->data as $k => $v) {
            getPostsImageUrl($this->data[$k]);
        }
    }

    private function getColumn($limit = 2, $offset = 0)
    {
        return $this->db->limit($limit)->join('cm_user u', 'u.userID = p.userID', 'left')
            ->join('cm_user_group g', 'u.groupID = g.groupID', 'left')->where('g.groupID', 7)
            ->order_by('datePosted', 'desc')->get('cm_post p')->result();
    }

    private function getReporterByUserId($userID)
    {
        return $this->db->from('cm_user u')
            ->join('cm_user_press up', 'u.userID=up.userID', 'left')
            ->join('cm_press p', 'up.pressID=p.pressID', 'left')
            ->where('u.userID', $userID)
            ->select('u.*, p.press_name, p.logo_img, p.homepage')
            ->get()->row();
    }

    public function getRankingByPostId($postId)
    {
        $ranking = ['V' => 0, 'R' => 0, 'L' => 0];
        $rows = $this->db->where('postID', $postId)
            ->get('cm_post_ranking')->result();
        foreach ($rows as $row) {
            foreach ($ranking as $k => $r) {
                if ($row->title == $k) {
                    $ranking[$k] = $row->rating;
                }
            }
        }
        return $ranking;
    }
}
