<?php defined('BASEPATH') or exit('No direct script access allowed');
header("Content-Type: text/html; charset=UTF-8");

class main extends MY_Controller
{
    public 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');
        $this->load->library('Post', '', 'post');
        $this->load->model('config_model');
        $this->load->model('web/m_advertisement');

    }

    public function index()
    {
        $this->load->helper('cookie');
        $session_id = get_cookie('crossmap_save_id');
        # session
        $SES_MEMBER_ID = $this->session->userdata('C_Member_Id');
        if ($session_id != '' && $SES_MEMBER_ID == '') {
            # model - session 가져오기
            $this->load->model('web/m_ci_sessions');
            $session_result = $this->m_ci_sessions->ci_sessions_select($session_id);
            session_decode($session_result['data']);
        }

        if ($SES_MEMBER_ID != '') {
            $expire_date = date("Y-m-d H:i:s", strtotime("+10 minutes"));

            # model - 중복로그인 체크용
            $req_data = array();
            $req_data['member_id'] = $SES_MEMBER_ID;
            $req_data['member_ip'] = $_SERVER['REMOTE_ADDR'];
            $req_data['expire_date'] = $expire_date;
            $this->load->model('web/m_member_login');
            $this->m_member_login->member_login_member_id_member_ip_update($req_data);
        }

        $graceCategories = array('result' => $this->category_model->findById(array_values($this->config->item('categories')['grace']))->result());
        foreach ($graceCategories['result'] as $gcategory) {
            $graceCategories[$gcategory->idx] = $gcategory;
        }
        $arr_bible_postcard = $this->post->getPostsByCategoryId(array($this->config->item('categories')['grace']['postcard']), 24);
        $arr_christian_reading = $this->post->getPostsByCategoryId(array($this->config->item('categories')['grace']['book']), 24);

        $arr_heart_opening_story = $this->post->getPostsByCategoryId(array($this->config->item('categories')['grace']['dailyQT']), 18);
        $arr_heart_opening_story1 = array_slice($arr_heart_opening_story, 0, 2);
        $arr_heart_opening_story2 = array_slice($arr_heart_opening_story, 2, 15);
        $arr_heart_opening_story = array_merge($arr_heart_opening_story1, array(
            array(
                'banner_url' => 'https://dramabible.org/',
                'main_img' => '/assets/images/banner-2020-342343.jpg',
                'title' => '<span style="color:#26bcb7">AD</span> 성경 듣기! 드라마 바이블로 더욱 생동감있게!!',
            ),
        ));
        $arr_heart_opening_story = array_merge($arr_heart_opening_story, $arr_heart_opening_story2);

        $arr_gracious_verse = $this->post->getPostsByCategoryId(array($this->config->item('categories')['grace']['enQT']), 18);
        $arr_qna = $this->post->getPostsByCategoryId(array($this->config->item('categories')['grace']['qna']), 18);

        $arr_headline_news = $this->getHomeTopNews();

        $photoHeadlineNewsPostId = array();
        foreach ($arr_headline_news as $k => $phn) {
            $photoHeadlineNewsPostId[] = $phn['idx'];
            $arr_headline_news[$k]['theme_img'] = $phn['main_img'];
            $arr_headline_news[$k]['content_idx'] = $phn['idx'];
        }

        $lackingNews = $this->db->order_by('reg_date', 'desc')
            ->where('is_del', 'N')->where('is_display', 'Y')
            ->limit(24 - count($arr_headline_news))->where_not_in('idx', $photoHeadlineNewsPostId)->get('news')->result_array();
        foreach ($lackingNews as $val) {
            array_push($arr_headline_news, array('title' => $val['title'],
                'theme_img' => $val['main_img'] ? $val['main_img'] : $val['theme_img'], 'content_idx' => $val['idx']));
        }

        $return_data = array();
        $return_data['advertisement'] = $this->m_advertisement->find_ad_by_page_key('Main');
        $return_data['arr_today_word'] = $this->getHomeTodayWord();
        $return_data['arr_headline_news'] = $arr_headline_news;
        $return_data['arr_daily_cutie'] = $this->getDailyQt();
        $return_data['arr_heart_opening_story'] = $arr_heart_opening_story;
        $return_data['arr_gracious_verse'] = $arr_gracious_verse;
        $return_data['arr_qna'] = $arr_qna;
        $return_data['arr_tv_gospel'] = $this->post->getPostsByCategoryId(array(40), 16);
        $return_data['arr_tv_praise'] = $this->post->getPostsByCategoryId(array(38), 16);
        $return_data['arr_tv_testimony'] = $this->post->getPostsByCategoryId(array(39), 16);
        $return_data['arr_tv_talkshow'] = $this->post->getPostsByCategoryId(array(41), 16);
        $return_data['arr_bible_postcard'] = $arr_bible_postcard;
        $return_data['arr_christian_reading'] = $arr_christian_reading;
        $return_data['arr_Prayer'] = $this->post->getPostsByCategoryId(array(26), 24);
        $return_data['graceCategories'] = $graceCategories;

        $this->load->library('user_agent');
        if ($this->agent->is_mobile()) {
            $return_data['is_mobile'] = true;
        } else {
            $return_data['is_mobile'] = false;
        }
        $this->load->view('/web/nmain', $return_data);
    }

    private function getDailyQt()
    {
        $config = $this->config_model->findByTypeAndPage('home', 'homedailyqt')->get()->result();
        if (count($config)) {
            $today = date('Y-m-d');
            foreach($config as $c) {
                if(strstr($c->DpTime, $today)) {
                    return $this->post->getPost($c->PostId);                  
                }
            }            
        } 
        return $this->post->getPostsByCategoryId($this->config->item('categories')['grace']['dailyQT'], 1)[0];        
    }

    private function getHomeTopNews()
    {
        $config = $this->config_model->findByTypeAndPage('home', 'hometopnews')->get()->result();
        if (count($config)) {
            $posts = array();
            foreach ($config as $c) {
                $posts[] = $c->PostId;
            }
            $news = $this->db->where_in('idx', $posts)->get('news')->result_array();
            $nnews = array();
            foreach ($config as $c) {
                foreach($news as $n) {
                    if($n['idx'] == $c->PostId) {
                        $nnews[$c->OrderNum] = $n;
                    }
                }
            }
            ksort($nnews);
            return array_values($nnews);
        } else {
            return $this->post->getPostsByCategoryId($this->config->item('categories')['grace']['dailyQT'], 1)[0];
        }
    }

    private function getHomeTodayWord() {
        $config = $this->config_model->findByTypeAndPage('home', 'hometodayword')->get()->result_array();                
        if(count($config)) {
            $today = date('Y-m-d');
            foreach($config as $c) {
                if(strstr($c['DpTime'], $today)) {
                    return array('word' => $c['Title'], 'title' => $c['Headline']);                    
                }
            }
        }return array('word' => '', 'title' => '');
    }
}
