<?php

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

    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->graceCategories = $this->getSubCategoryId($this->parentCategoryName);
    }

    public function index()
    {
        $data = array(
            'graceCategories' => $this->category_model->findById($this->graceCategories)->result(),
            'graceEditors' => $this->editor_model->findByCategoryId($this->graceCategories)->get()->result(),
        );
        $this->load->view($this->adminViewFolder . 'grace', $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->graceCategories)
            ->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->graceCategories);
        $this->tableClause();
        $graceTotalCount = $this->db->count_all_results();
        $categories = array();
        foreach ($graces as $grace) {
            array_push($categories, $grace->categoryId);
        }
        $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();
        $this->response(array('updated' => $updated));        
    }

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

    public function category_table()
    {
        $sort = $this->param('sort');
        $order = $this->param('order');
        $sortColumns = array('comments' => 'comment_count', 'reg_date' => 'reg_date');
        
        $this->category_model->findById($this->graceCategories, true)
        ->join($this->editor_model->table . ' p', 'category.idx = p.category_idx', 'left')
        ->where('category.is_del', 'N')
        ->group_by('category.idx')->select('count(category_idx) editorCount, category.category_name categoryName, category.display_sort displayOrder, category.reg_date, category.idx categoryId');
        if ($this->param('term')) {
            $this->db->like('category.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->graceCategories)->group_by('l.category_idx')
            ->select('count(l.idx) postCount, sum(l.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));
            }
        }
    }

}
