<?php

class Dataman extends MY_Controller
{

    private $parentCategoryName = 'grace-category';

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

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

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

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

    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();
        $sql = "SELECT yt.*, l.sync_date, l.contentCount FROM cm_ytchannel yt inner join (select count(idx) contentCount, max(reg_date) sync_date, category_idx, partner_idx from life l group by category_idx, partner_idx) as l on yt.CategoryId = l.category_idx and yt.editorId = l.partner_idx limit " . ($this->param('limit') * ($this->param('page') ? $this->param('page') - 1 : 0)) . ", " . $this->param('limit');
        return $this->db->query($sql)->result();
    }

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

        $sql = "SELECT count(*) cnt FROM cm_ytchannel";

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

    private function tableClause()
    {
        if ($this->param('term')) {
            $this->db->like('l.member_name', $this->param('term'));
        }
        $this->db->where('l.member_status !=', 2);
    }

    public function table()
    {
        $graces = $this->getTableRows();
        $graceTotalCount = $this->getTableCount();
        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')));
    }

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

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

    public function tablePodbbang()
    {
        $graces = $this->gettablePodbbangRows();
        $graceTotalCount = $this->gettablePodbbangCount();
        return array('total' => $graceTotalCount, 'rows' => $graces);
    }

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

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

        // $this->tablePodbbangClause();
        // $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();
        $sql = "SELECT * FROM cm_station limit " . ($this->param('limit') * ($this->param('page') ? $this->param('page') - 1 : 0)) . ", " . $this->param('limit');
        return $this->db->query($sql)->result();
    }

    private function gettablePodbbangCount()
    {
        // $this->tablePodbbangClause();
        // $this->editor_model->findAll();
        // return $this->db->count_all_results();
        $sql = "SELECT count(*) cnt FROM cm_station";

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

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

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

    private function getTableChurchRows()
    {
        // $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();
        $sql = "SELECT * FROM cm_naver_place limit " . ($this->param('limit') * ($this->param('page') ? $this->param('page') - 1 : 0)) . ", " . $this->param('limit');
        return $this->db->query($sql)->result();
    }

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

        $sql = "SELECT count(*) cnt FROM cm_naver_place";

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

    private function tableChurchClause()
    {
        if ($this->param('term')) {
            $this->db->like('l.member_name', $this->param('term'));
        }
        $this->db->where('l.member_status !=', 2);
    }

    public function tableChurch()
    {
        $graces = $this->getTableChurchRows();
        $graceTotalCount = $this->getTableChurchCount();
        return array('total' => $graceTotalCount, 'rows' => $graces);
    }

}
