<?php

class News extends MY_Controller
{

    private $parentCategoryName = 'grace-category';

    private $lifeCategories = array('ids' => array());

    public function __construct()
    {
        parent::__construct();
        $this->load->library('pagination');
        $this->load->library('post');
        $this->load->model('category_model');
        $this->load->model('editor_model');
        $this->load->model('life_model');
        $this->lifeCategories['result'] = $this->category_model->findById()->result();
        foreach ($this->lifeCategories['result'] as $c) {
            array_push($this->lifeCategories['ids'], $c->idx);
        }
    }

    public function index()
    {
        $table = $this->table();
        // print_r($table['rows']);die;
        $page = $this->input->get('page') ? $this->input->get('page') : 1;

        $config['base_url'] = '/adm/' . strtolower(__CLASS__);
        $config['total_rows'] = $table['total'];
        $config['per_page'] = $this->param('limit');
        $this->pagination->initialize($config);

        if ($this->input->get('pageset')) {
            foreach ($table['rows'] as $k => $r) {
                $table['rows'][$k]->title = html_entity_decode(convertEmoji($table['rows'][$k]->title));
                $table['rows'][$k]->main_img = imgSrc($table['rows'][$k]->main_img);
            }
            $this->response($table);
        } else {
            $data = array(
                'lifeCategories' => $this->lifeCategories['result'],
                'graceEditors' => $this->editor_model->findByCategoryId($this->lifeCategories['ids'])->get()->result(),
                'paging' => $this->pagination->create_links(),
                'table' => $table,
                'page' => $page,
            );

            $this->load->view('adm/news', $data);
        }
    }

    private function gettableRows()
    {
        $sql = "SELECT * FROM news where reg_date > '2019-12-01'";
        $sql .= $this->param('category') ? ' and category_code = '. $this->param('category') : '';
        $sql .= $this->param('term') ? ' and title like \'%'. $this->param('term'). '%\'' : '';
        $sql .= " order by reg_date desc limit " . ($this->param('limit') * ($this->param('page') ? $this->param('page') - 1 : 0)) . ", " . $this->param('limit');
        return $this->db->query($sql)->result();
    }

    private function getTableCount()
    {
        $sql = "SELECT count(*) cnt FROM news where reg_date > '2019-12-01'";
        $sql .= $this->param('category') ? ' and category_code = '. $this->param('category') : '';
        $sql .= $this->param('term') ? ' and title like \'%'. $this->param('term'). '%\'' : '';

        return $this->db->query($sql)->row()->cnt;
    }

    public function table()
    {
        $graces = $this->getTableRows();
        $graceTotalCount = $this->getTableCount();
        return array('total' => $graceTotalCount, 'rows' => $graces);
    }

    public function display()
    {
        $this->db->where('idx', $this->input->post('postid'))->update('news', array('is_display' => $this->input->post('is_display'), 'is_del' => 'N'));
    }

    public function delete()
    {
        $this->db->where_in('idx', explode('-', $this->input->get('list')))->update('news', array('is_del' => 'Y', 'is_display' => 'N'));
        go($this->input->server('HTTP_REFERER'), '삭제되었습니다.');
    }

    public function company()
    {
        $table = $this->tableCompany();
        $page = $this->input->get('page') ? $this->input->get('page') : 1;

        $config['base_url'] = '/adm/' . strtolower(__CLASS__) . '/company';
        $config['total_rows'] = $table['total'];
        $config['per_page'] = $this->param('limit');
        $this->pagination->initialize($config);
        $data = array(
            'lifeCategories' => $this->lifeCategories['result'],
            'graceEditors' => $this->editor_model->findByCategoryId($this->lifeCategories['ids'])->get()->result(),
            'paging' => $this->pagination->create_links(),
            'table' => $table,
            'page' => $page,
        );

        $this->load->view('adm/newscompany', $data);
    }

    private function getTableCompanyRows()
    {
        $sql = "SELECT * FROM press order by reg_date desc limit " . ($this->param('limit') * ($this->param('page') ? $this->param('page') - 1 : 0)) . ", " . $this->param('limit');
        return $this->db->query($sql)->result();
    }

    private function gettableCompanyCount()
    {
        $sql = "SELECT count(*) cnt FROM press";
        return $this->db->query($sql)->row()->cnt;
    }

    public function tableCompany()
    {
        $graces = $this->getTableCompanyRows();
        $graceTotalCount = $this->getTableCompanyCount();
        return array('total' => $graceTotalCount, 'rows' => $graces);
    }

    ///////////////////  category lsit /////////////////////

    public function category()
    {
        $table = $this->tableCategory();
        // print_r($table['rows']);die;
        $page = $this->input->get('page') ? $this->input->get('page') : 1;

        $config['base_url'] = '/adm/' . strtolower(__CLASS__) . '/category';
        $config['total_rows'] = $table['total'];
        $config['per_page'] = $this->param('limit');
        $this->pagination->initialize($config);

        foreach ($table['rows'] as $k => $v) {
            $table['rows'][$k]->category_fullpath = array('<a href="/adm/news/categoryedit/' . $v->idx . '">' . $v->category_name . '</a>');
            foreach ($this->categoryall as $c) {
                if ($v->p_category_code == $c->category_code && $v->category_code != $c->category_code) {
                    $table['rows'][$k]->category_fullpath[] = '<a href="/adm/news/categoryedit/' . $c->idx . '">' . $c->category_name . '</a>';
                }
            }
            $table['rows'][$k]->category_fullpath = implode(' > ', array_reverse($table['rows'][$k]->category_fullpath));
        }

        $data = array(
            'paging' => $this->pagination->create_links(),
            'table' => $table,
            'page' => $page,
        );

        $this->load->view('adm/newscategory', $data);
    }

    public function tableCategory()
    {
        $graces = $this->getTableCategoryRows();
        $graceTotalCount = $this->getTableCategoryCount();
        return array('total' => $graceTotalCount, 'rows' => $graces);
    }

    private function getTableCategoryCount()
    {
        $this->tableCategoryClause();
        $this->db->from('news_section l');
        $cnt = $this->db->count_all_results();

        $this->db->from('news_section l');
        $query = $this->db->where('l.is_del', 'N')->get();
        $this->categoryall = $query->result();
        return $cnt;
    }

    private function tableCategoryClause()
    {
        if ($this->param('term')) {
            $this->db->like('l.category_name', $this->param('term'));
        }
        $this->db->where('l.is_del', 'N');
    }

    private function getTableCategoryRows()
    {
        $this->tableCategoryClause();
        $this->db->from('news_section l')
            ->order_by('l.category_code')
            ->limit($this->param('limit'))
            ->offset($this->param('limit') * ($this->param('page') ? $this->param('page') - 1 : 0));
        $graces = $this->db->get()->result();
        return $graces;
    }

    public function categoryedit()
    {
        if ($this->input->post('idx')) {
            $data = array('p_category_code' => $this->input->post('parent'), 'category_code' => $this->input->post('parent').$this->input->post('idx'), 'category_name' => $this->input->post('category_name'));
            $this->db->where('idx', $this->input->post('idx'))->update('news_section', $data);
            go($this->input->post('redirect'), 'Success');
        } else if ($this->input->post('category_name')) {
            $data = array('p_category_code' => $this->input->post('parent'), 'category_name' => $this->input->post('category_name'));
            $this->db->insert('news_section', $data);
            $insertid = $this->db->insert_id();
            $data = array('category_code' => $this->input->post('parent').$insertid);
            $this->db->where('idx', $insertid)->update('news_section', $data);

            go($this->input->post('redirect'), 'Success');
        } else {
            $category = null;
            if ($this->uri->segment(4)) {
                $category = $this->db->where('idx', $this->uri->segment(4))->get('news_section')->row();
            }

            $data = array(
                'newsCategories' => $this->db->where('is_del', 'N')->where('idx !=', $category ? $category->idx : 0)->get('news_section')->result(),
                'category' => $category,
            );
            $this->load->view('adm/newscategoryedit', $data);
        }
    }

    public function categorydelete()
    {
        if ($this->input->get('list')) {
            $this->db->where_in('idx', explode('-', $this->input->get('list')))->update('news_section', array('is_del' => 'Y'));
            go($this->input->server('HTTP_REFERER'), 'Success');
        }
    }

}
