<?php

class Life extends MY_Controller
{
    private $parentCategoryName = 'grace-category';

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

    public function __construct()
    {
        parent::__construct();
        $this->load->library('Post', '', '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()
    {
        $data = array(
            'lifeCategories' => $this->lifeCategories['result'],
            'graceEditors' => $this->editor_model->findByCategoryId($this->lifeCategories['ids'])->get()->result(),
        );
        $this->load->view($this->adminViewFolder . 'life', $data);
    }

    private function tableClause()
    {
        if ($this->param('term')) {
            $this->db->like('l.title', $this->param('term'));
        }
        if ($this->param('category')) {
            $this->db->like('l.category_idx', $this->param('category'));
        }
        if ($this->param('editor')) {
            $this->db->like('p.idx', $this->param('editor'));
        }
    }

    public function table()
    {
        $request = $this->getRequest();
        $sort = $this->param('sort');
        $sortColumns = array('comments' => 'comment_count', 'reg_date' => 'reg_date');

        $this->life_model->findByCategoryId($this->lifeCategories['ids'])
            ->order_by('l.' . (empty($sortColumns[$sort]) ? $sortColumns['reg_date'] : $sortColumns[$sort]), $this->param('order'))
            ->where('l.is_display !=', null)
            ->select('l.display_date, l.is_display')
            ->limit($this->param('limit'))
            ->offset($this->param('offset'));
        $this->tableClause();
        $graces = $this->db->get()->result();

        foreach ($graces as $k => $g) {
            if (strtotime($g->display_date) > time() && $g->is_display == 'N') {
                $graces[$k]->isSetDptime = 1;
            }
        }

        $graceTotalCount = $this->life_model->findByCategoryId($this->lifeCategories['ids']);
        $this->tableClause();
        $graceTotalCount = $this->db->count_all_results();
        $categories = array();
        foreach ($graces as $grace) {
            array_push($categories, $grace->categoryId);
        }
        if (count($categories)) {
            $categories = $this->category_model->findById($categories)->result();
            foreach ($graces as $k => $g) {
                foreach ($categories as $c) {
                    if ($g->categoryId == $c->idx) {
                        $graces[$k]->categoryName = $c->category_name;
                    }
                }
            }
        }

        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode(array('total' => $graceTotalCount,
                'rows' => $graces)));
    }

    public function content_delete()
    {
        $this->life_model->findById(1)->reset_query()->where('idx', $this->param('contentId'))->delete($this->life_model->table);
        if ($deleted = $this->db->affected_rows()) {
            $this->response(array('deleted' => $deleted));
        }
    }

    public function content_category()
    {
        $data = array();
        if ($this->param('category')) {
            $data['category_idx'] = $this->param('category');
        }

        if ($this->param('editor')) {
            $data['partner_idx'] = $this->param('editor');
        }

        $this->life_model->findById($this->param('contentId'))->set($data)->update();
        if ($updated = $this->db->affected_rows()) {
            $this->response(array('updated' => $updated));
        }
    }

    public function category()
    {
        $this->load->view($this->adminViewFolder . 'life-category');
    }

    public function category_table()
    {
        $sort = $this->param('sort');
        $order = $this->param('order');
        $sortColumns = array('comments' => 'comment_count', 'reg_date' => 'reg_date');
        $this->editor_model->findByCategoryId(null)
            ->join($this->category_model->table . ' c', 'p.category_idx=c.idx', 'right')
            ->where_in('c.idx', $this->lifeCategories['ids'])
            ->where('c.is_del', 'N')
            ->group_by('c.idx')->select('count(category_idx) editorCount, c.category_name categoryName,
            c.display_sort displayOrder, c.reg_date, c.idx categoryId');
        if ($this->param('term')) {
            $this->db->like('c.category_name', $this->param('term'));
        }
        $categoryEditors = $this->db->get()->result();
        $categories = array();
        foreach ($categoryEditors as $grace) {
            array_push($categories, $grace->categoryId);
        }

        $posts = $this->life_model->findByCategoryId($this->lifeCategories['ids'])->group_by('p.category_idx')
            ->select('count(p.idx) postCount, sum(hit_count) views')->get()->result();
        foreach ($categoryEditors as $k => $g) {
            $categoryEditors[$k]->postCount = 0;
            $categoryEditors[$k]->views = 0;
            foreach ($posts as $p) {
                if ($g->categoryId == $p->categoryId) {
                    $categoryEditors[$k]->postCount += $p->postCount;
                    $categoryEditors[$k]->views += $p->views;
                }
            }
        }

        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode(array('total' => count($categoryEditors),
                'rows' => $categoryEditors)));
    }

    public function category_save()
    {
        $parentId = $this->category_model->getSubCategoryId($this->parentCategoryName)['parent'];
        if (!empty($this->param('id'))) {
            $this->db->where('idx', $this->param('id'))->update($this->category_model->table, array(
                'category_name' => $this->param('name'),
                'display_sort' => $this->param('order'),
                'parent' => $parentId,
                'update_id' => $this->session->userdata('Adm_Id'),
                'update_date' => date('Y-m-d H:i:s'),
            ));
            if ($updated = $this->db->affected_rows()) {
                $this->response(array('updated' => $updated));
            }
        } else {
            if ($inserted = $this->db->insert($this->category_model->table, array(
                'category_name' => $this->param('name'),
                'display_sort' => $this->param('order'),
                'parent' => $parentId,
                'reg_id' => $this->session->userdata('Adm_Id'),
                'reg_date' => date('Y-m-d H:i:s'),
            ))) {
                $this->response(array('inserted' => $this->db->insert_id()));
            }
        }
    }

    public function category_delete()
    {
        if (!empty($this->param('id'))) {
            $this->db->where('idx', $this->param('id'))->update($this->category_model->table, array(
                'is_del' => 'Y',
            ));
            if ($updated = $this->db->affected_rows()) {
                $this->response(array('updated' => $updated));
            }
        }
    }

}
