<?php

class Content 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->load->model('member_model');
        $this->load->library('awsfileuploader');
        $this->lifeCategories['result'] = $this->category_model->findById()->result();
        foreach ($this->lifeCategories['result'] as $c) {
            array_push($this->lifeCategories['ids'], $c->idx);
        }
        $this->editors = $this->editor_model->findByCategoryId($this->lifeCategories['ids'])->order_by('partner_name')->get()->result();
    }

    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]->mainImg = imgSrc($table['rows'][$k]->mainImg);
            }
            $this->response($table);
        } else {
            $data = array(
                'lifeCategories' => $this->lifeCategories['result'],
                'graceEditors' => $this->editors,
                'paging' => $this->pagination->create_links(),
                'table' => $table,
                'page' => $page,
            );
            $this->load->view('adm/content', $data);
        }
    }

    private function tableClause()
    {
        if ($this->param('term')) {
            $this->db->like('l.title', $this->param('term'));
        }
        if ($this->param('category')) {
            $ccc = $this->param('category');
            if ($this->input->get('pageset') && strpos($this->param('category'), '-')) {
                $ccc = explode('-', $this->param('category'));
            }
            $this->db->where_in('l.category_idx', $ccc);
        }
        if ($this->param('editor')) {
            $this->db->like('l.partner_idx', $this->param('editor'));
        }
        $this->db->where('l.is_display !=', null);
        if ($this->input->get('pageset')) {$this->db->where('l.is_del', 'N');
            $this->db->where('l.is_display', 'Y');}
    }

    private function getTableRows()
    {
        $sort = $this->param('sort');
        $sortColumns = array('comments' => 'comment_count', 'reg_date' => 'reg_date');

        $this->tableClause();
        $this->life_model->findByCategoryId($this->lifeCategories['ids'])
            ->order_by('l.' . $sortColumns['reg_date'], $this->param('order'))
            ->select('l.display_date, l.is_display, l.is_del')
            ->limit($this->param('limit'))
            ->offset($this->param('limit') * ($this->param('page') ? $this->param('page') - 1 : 0));
        $graces = $this->db->get()->result();
        foreach ($graces as $k => $g) {
            if (strtotime($g->display_date) > time() && $g->is_display == 'N') {
                $graces[$k]->isSetDptime = 1;
            }
        }
        return $graces;
    }

    private function getTableCount()
    {
        $this->tableClause();
        $this->life_model->findByCategoryId($this->lifeCategories['ids']);
        return $this->db->count_all_results();
    }

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

    private function addCategoryNameToTableResponse(&$graces)
    {
        $categories = array();
        foreach ($graces as $grace) {
            array_push($categories, $grace->categoryId);
        }
        if (count($categories)) {
            $categories = $this->category_model->findById(implode(',', $categories))->result();
            foreach ($graces as $k => $g) {
                foreach ($categories as $c) {
                    if ($g->categoryId == $c->idx) {
                        $graces[$k]->categoryName = $c->category_name;
                    }
                }
            }
        }
    }

    private function getContentImages()
    {
        preg_match_all('/(..\/..\/..\/uploads\/[a-z0-9A-Z._]+)/',
            $this->input->post('content'), $matches);
        $contentImages = array(array(), array());		
        foreach ($matches[0] as $match) {
            $contentImages[0][] = $match;
            $contentImages[1][] = FCPATH . 'uploads' . DIRECTORY_SEPARATOR . basename($match);
        }
        return $contentImages;
    }

    private function uploadContentImage($insertId = 0)
    {
        if (!$insertId) {
            return null;
        }

        $contentImages = $this->getContentImages();
        if ($this->input->post('contentId')) {
            $contentUploadedImages = $this->db->where('content_idx', $this->input->post('contentId'))->get('cm_content_image')->result();
            if (count($contentUploadedImages)) {
                foreach ($contentUploadedImages as $img) {
                    $this->awsfileuploader->delete($img->url);
                }
                $this->db->where('content_idx', $this->input->post('contentId'))->delete('cm_content_image');
            }
        }
        
            foreach ($contentImages[1] as $k => $img) {
                $url = '/files/life/' . date('Y/m/') . basename($img);
                $this->awsfileuploader->upload($img, 'files/life/' . date('Y/m/') . basename($img));
                $this->db->insert('cm_content_image', array(
                    'content_idx' => $insertId,
                    'url' => substr($url, 1),
                ));
            }
        
    }

    public function write()
    {ini_set('display_errors', 1);
        if ($this->input->post('title')) {
            $categoryId = $this->input->post('category');
            $editorId = $this->input->post('editor');
            $title = str_replace('"', '\"', addslashes(convertEmoji($this->input->post('title'), 'ENCODE')));
            $mainImg = $this->input->post('main_img');

            $contentImages = $this->getContentImages();
            $content = $this->input->post('content');
            if(isset($contentImages[1]) && count($contentImages[1])) {
                foreach ($contentImages[1] as $k => $img) {
                    $url = '/files/life/' . date('Y/m/') . basename($img);
                    $content = str_replace($contentImages[0][$k], $url, $content);
                }
            }

            $content = str_replace('"', '\"', addslashes(convertEmoji($content, 'ENCODE')));
            $isDisplay = $this->input->post('is_display');
            $isDisplay = $isDisplay == 'R' ? 'N' : $isDisplay;
            $displayTime = $this->input->post('display_time');
            $now = date('Y-m-d H:i:s');

            if (isset($_FILES['uploadfile']) && is_uploaded_file($_FILES['uploadfile']['tmp_name'])) {
                $upload = $this->post->upload('uploadfile');
                $filePath = FCPATH . 'uploads/' . explode('uploads/', $upload['full_path'])[1];
                $keyPath = 'files/life/' . date('Y/m/') . basename($filePath);
                $mainImg = $this->awsfileuploader->upload($filePath, $keyPath);
            }
            if ($this->input->post('contentId')) {
                $sql = "UPDATE life
                SET
                    category_idx = $categoryId,
                    partner_idx = $editorId,
                    title = '$title',
                    main_img = '$mainImg',
                    content = '$content',
                    update_date = '$now',
                    display_date = '$displayTime',
                    is_display = '$isDisplay'
                WHERE
                    idx = " . $this->input->post('contentId');
            } else {
                $sql = "insert into
                life(category_idx, partner_idx, title, main_img, content, reg_date, display_date, is_display)
                values($categoryId, $editorId,'$title', '$mainImg', '$content', '$now', '$displayTime', '$isDisplay')";
            }
            if ($this->db->query($sql)) {
				if(isset($contentImages[1]) && count($contentImages[1])) {
                $this->uploadContentImage($this->input->post('contentId') ? $this->input->post('contentId') : $this->db->insert_id());
				}
                go($this->input->server('HTTP_REFERER'), '등록성공.');
            } else {
                echo 'error' . $this->db->last_query();
            }
        } else if ($this->uri->segment(4)) {
            $contentId = $this->uri->segment(4);

            $query = $this->db->query("SELECT
                `p`.`idx` `editorId`,
                `p`.`partner_img` `editorImg`,
                `p`.`main_img` `editorMainImg`,
                `p`.`partner_name` `editorName`,
                `p`.`partner_intro` `editorIntro`,
                `l`.`title`,
                `l`.`head_title`,
                `l`.`sub_title`,
                `l`.`content`,
                `l`.`category_idx` `categoryId`,
                `l`.`idx`,
                `l`.`main_img` `mainImg`,
                `l`.`hit_count` `views`,
                `l`.`like_count` `likes`,
                `l`.`comment_count` `comments`,
                `l`.*
            FROM
                `life` `l`
                    LEFT JOIN
                `partner` `p` ON `l`.`partner_idx` = `p`.`idx`
            WHERE
                `l`.`idx` IN ($contentId)");

            $post = $query->row();
            $data = array(
                'post' => $post,
                'lifeCategories' => $this->lifeCategories['result'],
                'graceEditors' => $this->editors,
            );
            $this->load->view('adm/contentwrite', $data);
        } else {
            $data = array(
                'lifeCategories' => $this->category_model->getCategories($this->lifeCategories['ids']),
                'graceEditors' => $this->editors,
            );
            $this->load->view('adm/contentwrite', $data);
        }
    }

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

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

    public function reserve()
    {
        $configType = 'dptime';
        $this->load->model('config_model');
        if ($this->input->post('title')) {
            $this->load->model('life_model');
            $this->db->where('idx', $this->input->post('postid'))->update($this->life_model->table, array('is_display' => 'N', 'display_date' => $this->input->post('dptime')));
            $config = $this->config_model->findByTypeAndPostId($configType, $this->input->post)->get()->row();
            if ($config) {
                if ($this->db->where('Id', $config->Id)->update($this->config_model->table, array(
                    'PostId' => $this->input->post('postid'),
                    'Type' => $configType,
                    'DpTime' => $this->input->post('dptime'),
                ))) {
                    go($this->input->post('redirect'), '예약설정 변경성공');
                } else {
                    go($this->input->post('redirect'), '예약설정 실패');
                }
            } else {
                if ($this->db->insert($this->config_model->table, array(
                    'PostId' => $this->input->post('postid'),
                    'Type' => $configType,
                    'DpTime' => $this->input->post('dptime'),
                ))) {
                    go($this->input->post('redirect'), '예약설정 등록성공');
                } else {
                    go($this->input->post('redirect'), '예약설정 실패');
                }
            }
        } else {
            $contentId = $this->input->get('list');
            $query = $this->db->query("SELECT
                `l`.*
            FROM
                `life` `l`
            WHERE
                `l`.`idx` IN ($contentId)");

            $post = $query->row();
            $post->reserve_time = date('Y-m-d H:i:s', time() + 3600 * 24);
            if ($config = $this->config_model->findByTypeAndPostId($configType, $contentId)->get()->row()) {
                $post->reserve_time = $config->DpTime;
            }
            $data = array(
                'post' => $post,
            );

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

    }

    public function config()
    {
        $this->load->model('config_model');
        if ($this->input->method() == 'post') {
            if ($this->param('id')) {
                $config = $this->config_model->findByTypeAndNameAndPageAndOrderNum($this->param('type'),
                    $this->param('name'), $this->param('page'), $this->param('order'))->get();
                if ($config->num_rows() && $config->row()->Id != $this->param('id')) {
                    $this->response(null, 401, '삭제먼저');
                } else if ($this->db->where('Id', $this->param('id'))->update($this->config_model->table, array(
                    'PostId' => $this->param('postid'),
                    'Type' => $this->param('type'),
                    'Name' => $this->param('name'),
                    'Page' => $this->param('page'),
                    'OrderNum' => $this->param('order'),
                    'Headline' => $this->param('headline'),
                    'Title' => $this->param('title'),
                    'Thumbnail' => $this->param('thumbnail'),
                ))) {
                    $this->response(array('inserted' => $this->db->insert_id()));
                } else {
                    $this->response(null, 402, 'failed to svae');
                }
            } else if ($this->config_model->findByTypeAndNameAndPageAndOrderNum($this->param('type'), $this->param('name'),
                $this->param('page'), $this->param('order'))->count_all_results()) {
                $this->response(null, 401, '삭제먼저');
            } else {
                if ($this->db->insert($this->config_model->table, array(
                    'PostId' => $this->param('postid'),
                    'Type' => $this->param('type'),
                    'Name' => $this->param('name'),
                    'Page' => $this->param('page'),
                    'OrderNum' => $this->param('order'),
                    'Headline' => $this->param('headline'),
                    'Title' => $this->param('title'),
                    'Thumbnail' => $this->param('thumbnail'),
                ))) {
                    $this->response(array('inserted' => $this->db->insert_id()));
                } else {
                    $this->response(null, 402, 'failed to svae');
                }
            }
        } else if ($this->input->method() == 'delete') {
            $this->db->where('Id', $this->param('id'))->delete($this->config_model->table);
            if ($this->db->affected_rows()) {
                $this->response(null, 200, '삭제성공');
            } else {
                $this->response(null, 401, '삭제실패');
            }
        } else {
            if ($configQuery = $this->config_model->findByTypeAndNameAndPage($this->param('type'), $this->param('name'), $this->param('page'))->order_by('OrderNum')->get()->result()) {
                $this->response($configQuery);
            } else {
                $this->response(array(), 200);
            }
        }
    }

    ///////////////////  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/content/categoryedit/' . $v->idx . '">' . $v->category_name . '</a>');
            foreach ($this->categoryall as $c) {
                if ($v->parent == $c->idx) {
                    $table['rows'][$k]->category_fullpath[] = '<a href="/adm/content/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/contentcategory', $data);
    }

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

    private function getTableCategoryCount()
    {
        $this->tableCategoryClause();
        $this->category_model->findAll();
        $cnt = $this->db->count_all_results();

        $this->category_model->findAll();
        $query = $this->db->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()
    {
        $sort = $this->param('sort');
        $sortColumns = array('comments' => 'comment_count', 'reg_date' => 'parent');

        $this->tableCategoryClause();
        $this->category_model->findAll()
            ->order_by('l.parent desc, reg_date desc')
            ->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('parent' => $this->input->post('parent'), 'category_name' => $this->input->post('category_name'), 'update_date' => date('Y-m-d H:i:s'), 'description' => $this->input->post('description'));
            $this->db->where('idx', $this->input->post('idx'))->update('category', $data);
            go($this->input->post('redirect'), 'Success');
        } else if ($this->input->post('category_name')) {
            $data = array('parent' => $this->input->post('parent'), 'category_name' => $this->input->post('category_name'), 'reg_date' => date('Y-m-d H:i:s'), 'description' => $this->input->post('description'));
            $this->db->insert('category', $data);
            go($this->input->post('redirect'), 'Success');
        } else {
            $category = null;
            if ($this->uri->segment(4)) {
                $category = $this->category_model->findById($this->uri->segment(4))->row();
            }

            $data = array(
                'lifeCategories' => $this->lifeCategories['result'],
                'category' => $category,
            );
            $this->load->view('adm/contentcategoryedit', $data);
        }
    }

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

}
