<?php

class Member 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('member_model');
        $this->load->model('life_model');
        $this->load->model('comment_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);
        }
    }

    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);
        $data = array(
            'paging' => $this->pagination->create_links(),
            'table' => $table,
            'page' => $page,
        );

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

    public function active()
    {
        $this->db->where('idx', $this->input->post('postid'))->update('member', array('member_status' => $this->input->post('is_display')));
    }

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

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

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

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

    public function editoredit()
    {
        if ($this->input->post('partner_name')) {
            $mainImg = $this->input->post('main_img');
            $partner_img = $this->input->post('partner_img');
            $is_del = $this->input->post('is_del');
            $partner_id = $this->input->post('partner_id');
            $partner_real_name = $this->input->post('partner_real_name');
            $partner_name = $this->input->post('partner_name');
            $partner_intro = $this->input->post('partner_intro');
            $partner_homepage = $this->input->post('partner_homepage');

            if (isset($_FILES['uploadfile']) && is_uploaded_file($_FILES['uploadfile']['tmp_name'])) {
                if ($mainImg) {
                    $this->awsfileuploader->upload(substr($mainImg, 1));
                }
                $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 (isset($_FILES['uploadfile2']) && is_uploaded_file($_FILES['uploadfile2']['tmp_name'])) {
                if ($partner_img) {
                    $this->awsfileuploader->upload(substr($partner_img, 1));
                }
                $upload = $this->post->upload('uploadfile2');
                $filePath = FCPATH . 'uploads/' . explode('uploads/', $upload['full_path'])[1];
                $keyPath = 'files/life/' . date('Y/m/') . basename($filePath);
                $partner_img = $this->awsfileuploader->upload($filePath, $keyPath);
            }

            $now = date('Y-m-d H:i:s');
            if ($this->input->post('contentId')) {
                $sql = "UPDATE partner
                SET
                    partner_real_name = '$partner_real_name',
                    partner_id = '$partner_id',
                    partner_name = '$partner_name',
                    main_img = '$mainImg',
                    partner_img = '$partner_img',
                    update_date = '$now',
                    is_del = '$is_del',
                    partner_intro='$partner_intro',
                    partner_homepage='$partner_homepage'
                WHERE
                    idx = " . $this->input->post('contentId');
            } else {
                $sql = "insert into
                partner(partner_id, partner_name, partner_real_name, main_img, partner_img, reg_date, is_del,partner_intro,partner_homepage)
                values('$partner_id', '$partner_name','$partner_real_name', '$mainImg', '$partner_img', '$now', '$is_del', '$partner_intro','$partner_homepage')";
            }
            if ($this->db->query($sql)) {
                go($this->input->server('HTTP_REFERER'), '등록성공.');
            } else {
                echo 'error' . $this->db->last_query();
            }
        } else if ($this->uri->segment(4)) {

            $this->load->view('adm/membereditoredit', array('post' => $this->db->where('idx', $this->uri->segment(4))->get('partner')->row()));
        } else {

            $this->load->view('adm/membereditoredit');
        }
    }

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

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

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

        $config['base_url'] = '/adm/' . strtolower(__CLASS__) . '/comment';
        $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/comment', $data);
    }

    private function tableCommentClause()
    {
        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('l.partner_idx', $this->param('editor'));
        }
        $this->db->where('l.is_display !=', null);
    }

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

        $this->tableCommentClause();
        $this->life_model->findByCategoryId($this->lifeCategories['ids'])
            ->order_by('l.' . $sortColumns['reg_date'], $this->param('order'))
            ->select('l.display_date, l.is_display, c.comment, c.idx commentId')
            ->join('comment c', 'c.content_idx=l.idx', 'inner')
            ->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 getTableCommentCount()
    {
        $this->tableCommentClause();
        $this->life_model->findByCategoryId($this->lifeCategories['ids'])->join('comment c', 'c.content_idx=l.idx', 'inner');
        return $this->db->count_all_results();
    }

    public function tableComment()
    {
        $graces = $this->getTableCommentRows();
        $graceTotalCount = $this->getTableCommentCount();
        $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 tableClause()
    {
        if ($this->param('term')) {
            $this->db->like('l.member_name', $this->param('term'));
            $this->db->or_like('l.member_id', $this->param('term'));
        }
        // $this->db->where('l.member_status !=', 2);
    }

    private function tableEditorClause()
    {
        if ($this->param('term')) {
            $this->db->like('l.partner_name', $this->param('term'));
            $this->db->or_like('l.partner_id', $this->param('term'));
        }
    }

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

        $this->tableClause();
        $this->member_model->findAll()
            ->order_by('l.' . $sortColumns['reg_date'], $this->param('order'))
            ->limit($this->param('limit'))
            ->offset($this->param('limit') * ($this->param('page') ? $this->param('page') - 1 : 0));
        $graces = $this->db->get()->result();
        return $graces;
    }

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

        $this->tableEditorClause();
        $this->editor_model->findAll()
            ->order_by('l.' . $sortColumns['reg_date'], $this->param('order'))
            ->limit($this->param('limit'))
            ->offset($this->param('limit') * ($this->param('page') ? $this->param('page') - 1 : 0));
        $graces = $this->db->get()->result();
        return $graces;
    }

    private function getTableCount()
    {
        $this->tableClause();
        $this->member_model->findAll();
        return $this->db->count_all_results();
    }

    private function getTableEditorCount()
    {
        $this->tableEditorClause();
        $this->editor_model->findAll();
        return $this->db->count_all_results();
    }

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

    public function tableEditor()
    {
        $graces = $this->getTableEditorRows();
        $graceTotalCount = $this->getTableEditorCount();
        return array('total' => $graceTotalCount, 'rows' => $graces);
    }

    public function reg()
    {
        if ($this->input->post('title')) {
            $categoryId = $this->input->post('category');
            $editorId = $this->input->post('editor');
            $title = str_replace('"', '\"', addslashes($this->input->post('title')));
            $mainImg = $this->input->post('main_img');
            $content = str_replace('"', '\"', addslashes($this->input->post('content')));
            $now = date('Y-m-d H:i:s');
            if (isset($_FILES['uploadfile']) && is_uploaded_file($_FILES['uploadfile']['tmp_name'])) {
                $upload = $this->post->upload('uploadfile');
                $this->load->library('awsfileuploader');
                $mainImg = $this->awsfileuploader->upload('uploads/' . explode('uploads/', $upload['full_path'])[1]);
            }
            if ($this->input->post('contentId')) {
                $sql = "UPDATE life
                SET
                    is_display = 'N',
                    category_idx = $categoryId,
                    partner_idx = $editorId,
                    title = '$title',
                    main_img = '$mainImg',
                    content = '$content',
                    update_date = '$now'
                WHERE
                    idx = " . $this->input->post('contentId');
            } else {
                $sql = "insert into
                life(is_display, category_idx, partner_idx, title, main_img, content, reg_date)
                values('N', $categoryId, $editorId,'$title', '$mainImg', '$content', '$now')";
            }
            if ($this->db->query($sql)) {
                header('location:' . $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->editor_model->findByCategoryId($this->lifeCategories['ids'])->get()->result(),
            );
            $this->load->view('adm/content_write', $data);
        } else {
            $data = array(
                'lifeCategories' => $this->lifeCategories['result'],
                'graceEditors' => $this->editor_model->findByCategoryId($this->lifeCategories['ids'])->get()->result(),
            );
            $this->load->view('adm/content_write', $data);
        }
    }

    public function delete()
    {
        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')));
    }

}
