<?php
defined('BASEPATH') or exit('No direct script access allowed');

class Webtoons extends CI_Controller
{
    public $tb_name_category = 'wt_categories';
    public $tb_name_episode = 'mt_episodes';
    public $tb_name_webtoon_list = 'wt_list';
    public $tb_name_notice = 'wt_announcement';
    public $tb_name_cartoonist = 'wt_cartoonists';
    public $tb_name_post = 'cm_post';
    public $display_limit = 15; // total # of list
    public $list_limit = 10; // total # of pages

    public function __construct()
    {
        parent::__construct();
        // $this->load->library('util');
        define("HOOSK_ADMIN", 1);
        $this->load->language('webtoon');
        $this->load->model('Hoosk_model');
        $this->load->model('wtoon_model');
        $this->load->helper(array('admincontrol', 'url', 'form'));
        $this->load->library('session');
        define('LANG', $this->Hoosk_model->getLang());
        $this->lang->load('admin', LANG);
        //Define what page we are on for nav
        $this->data['current'] = $this->uri->segment(2);
        define('SITE_NAME', $this->Hoosk_model->getSiteName());
        define('THEME', $this->Hoosk_model->getTheme());
        define('THEME_FOLDER', BASE_URL.'/theme/'.THEME);
        //check session exists
        Admincontrol_helper::is_logged_in($this->session->userdata('userName'));
    }

    /*
    @desc : list all maptoons
     */
    public function index()
    {
        $this->load->library('pagination');
        $result_per_page = $this->display_limit;  // the number of result per page
        $config['base_url'] = BASE_URL. '/admin/webtoons/';
        $config['total_rows'] = $this->wtoon_model->countWebtoon();
        $config['per_page'] = $result_per_page;
    
        $this->pagination->initialize($config);
    
        //Get webtoons from database
        $this->data['webtoons'] = $this->wtoon_model->getWebtoons($arr='', $result_per_page, $this->uri->segment(3));
        $this->data['posts'] = $this->Hoosk_model->getPosts($result_per_page, $this->uri->segment(3));
        //Load the view
        $this->data['header'] = $this->load->view('admin/header', $this->data, true);
        $this->data['footer'] = $this->load->view('admin/footer', '', true);
        
        // $query_string = ['status'=>1, 'wt_cartoonists_idx'=>1];
        $query_string = [];
        $arr_cartoonist = $this->wtoon_model->get_cartoonist_list();
        $this->data['cartoonists'] = $arr_cartoonist;

        $this->load->view('/admin/webtoon/webtoon', $this->data);
    }

    /*
    @desc : register webtoon
     */
    public function webtoon_proc()
    {
        $idx = $this->input->post('idx');
        $mode = $this->input->post('mode');
        $wt_cartoonists_idx = $this->input->post('wt_cartoonists_idx');	//
        $name = $this->input->post('name');	//
        $status = $this->input->post('status');
        $date_sun = ($this->input->post('date_sun')=='') ? 0 : $this->input->post('date_sun');
        $date_mon = ($this->input->post('date_mon')=='') ? 0 : $this->input->post('date_mon');
        $date_tue = ($this->input->post('date_tue')=='') ? 0 : $this->input->post('date_tue');
        $date_wed = ($this->input->post('date_wed')=='') ? 0 : $this->input->post('date_wed');
        $date_thu = ($this->input->post('date_thu')=='') ? 0 : $this->input->post('date_thu');
        $date_fri = ($this->input->post('date_fri')=='') ? 0 : $this->input->post('date_fri');
        $date_sat = ($this->input->post('date_sat')=='') ? 0 : $this->input->post('date_sat');
        $description = $this->input->post('description');

        if ($name=='') {
            // $this->util->js_alert_back('맵툰명을 입력해주십시오');
            exit;
        }
        if ($wt_cartoonists_idx=='') {
            // $this->util->js_alert_back('맵툰작가를 선택해주세요');
            exit;
        }

        $this->load->model('m_webtoon');
        if ($idx!=0) {
            $maptoon_info = $this->wtoon_model->getWebtoons(['idx' => $idx]);
        }
        
        
        //이미지 업로드
        if ($_FILES['main_img']['name']!='') {
            $mid_url_path = date("Y")."/".date("m");
            $upload_path = WEBTOON_DIR_BACK.$mid_url_path;
            if (!is_dir($upload_path)) {
                umask(0);
                mkdir($upload_path, 0777, true);
            }
            $config['max_size'] = 20*1024;
            $config['upload_path'] = $upload_path;
            $config['allowed_types'] = 'gif|jpg|png|jpeg';
            $config['encrypt_name'] = true;

            $this->load->library('upload');
            $this->upload->initialize($config);
            
            $file_name= date("H").date("i").date("s");
            
            if (! $this->upload->do_upload('main_img')) {
                $error = array('error' => $this->upload->display_errors());
                gf_alert("이미지 업로드에 실패했습니다.", 'back');
            }
            $arr_upload_data = $this->upload->data();
            $img_data = (isset($arr_upload_data['file_name'])==true) ? WEBTOON_DIR_FRONT.$mid_url_path.'/'.$arr_upload_data['file_name'] : '';

            //remove previous image
            if (isset($maptoon_info[0])==true && $img_data!='') {
                $main_img = $maptoon_info[0]['main_img'];
                if ($main_img!='') {
                    unlink($_SERVER['DOCUMENT_ROOT'].$main_img);
                }
            }
        } else {
            $img_data = (isset($maptoon_info[0]['main_img'])==true) ? $maptoon_info[0]['main_img'] : '';
        }

        $data = ['main_img' => $img_data,
                'name' => $name,
                'status' => $status,
                'date_sun' => $date_sun,
                'date_mon' => $date_mon,
                'date_tue' => $date_tue,
                'date_wed' => $date_wed,
                'date_thu' => $date_thu,
                'date_fri' => $date_fri,
                'date_sat' => $date_sat,
                'description' => $description,
                'reg_date' => date("Y-m-d H:i:s"),
                'wt_cartoonists_idx' => $wt_cartoonists_idx];

        if (is_numeric($idx)==true && $idx>0) {	// update data
            $ret = $this->wtoon_model->updateWebtoon($idx, $data);
            if ($ret==true) {
                $result['status'] = 1;
                $result['message'] ='수정되었습니다.';
                echo json_encode($result);
                exit;
            } else {
                $result['status'] = 0;
                $result['message'] = '등록되지 않았습니다. 다시 시도해 주세요';
                echo json_encode($result);
                exit;
            }
        } else {	// insert data
            $ret = $this->wtoon_model->insertWebtoon($data);
            if ($ret==true) {
                $result['status'] = 1;
                $result['message'] = '등록되었습니다.';
                echo json_encode($result);
                exit;
            } else {
                $result['status'] = 0;
                $result['message'] = '등록되지 않았습니다. 다시 시도해 주세요';
                echo json_encode($result);
                exit;
            }
        }
    }

    /*
    @desc : delete webtoon info
     */
    public function webtoon_delete()
    {
        if ($this->input->post('deleteid')):
            $this->wtoon_model->removeWebtoon($this->input->post('deleteid'));
        redirect(BASE_URL.'/admin/webtoons'); else:
            $this->data['form']=$this->wtoon_model->getWebtoon($this->uri->segment(4));
        $this->load->view('admin/webtoon/webtoon_delete.php', $this->data);
        endif;
    }

    /*
    @desc : list all cartoonists
     */
    public function cartoonist()
    {
        //Load the view
        $this->data['header'] = $this->load->view('admin/header', $this->data, true);
        $this->data['footer'] = $this->load->view('admin/footer', '', true);

        $idx = $this->input->get('idx');

        if (is_numeric($idx)==true && $idx>0) {
            $query = $this->db->get_where($this->tb_name_cartoonist, ['idx'=>$idx]);
            $row = $query->row_array();
            if ($row!=false) {
                $row['result'] = 'success';
            }
            echo json_encode($row);
            exit;
        } else {
            $query = $this->db->get($this->tb_name_cartoonist);
            $i = 0;
            
            $this->data['cartoonists']= array();
            foreach ($query->result_array() as $row) {
                $this->data['cartoonists'][$i] = $row;
                $i++;
            }
            $this->load->view('/admin/webtoon/cartoonist', $this->data);
        }
    }

    /*
    @desc : register & modify cartoonist info
     */
    public function cartoonist_proc()
    {
        $name = $this->input->post('name');
        $website = $this->input->post('website');
        $mode = $this->input->post('mode');
        $idx  = $this->input->post('idx');
        $name = trim($name);
        $website = trim($website);
        if ($name!='' && $website!='') {
            if (isset($idx) && $idx!='0' && $idx!='') {
                $data = ['name' => $name,
                            'website' => $website];
                $this->db->where('idx', $idx);
                $ret = $this->db->update($this->tb_name_cartoonist, $data);
                if ($ret==true) {
                    $result['status'] = 1;
                    $result['message'] = "수정성공";
                } else {
                    $result['status'] = 0;
                    $result['message'] = '수정 실패 관리자에게 문의';
                }
            } else {
                $data = [
                    'name' => $name,
                    'website' => $website
                ];
                $ret = $this->db->insert($this->tb_name_cartoonist, $data);
                if ($ret==true) {
                    $result['status'] = 1;
                    $result['message'] = "등록성공";
                } else {
                    $result['status'] = 0;
                    $result['message'] = "등록 실패";
                }
            }
        } else {
            $result['status'] = 0;
            $result['message'] = 'All fields are required';
        }
        echo json_encode($result);
        exit;
    }

    /*
    @desc : delete cartoonist info
     */
    public function cartoonist_delete()
    {
        if ($this->input->post('deleteid')):
            $this->wtoon_model->removeCartoonist($this->input->post('deleteid'));
        redirect(BASE_URL.'/admin/webtoons/cartoonist'); else:
            $this->data['form']=$this->wtoon_model->getCartoonist($this->uri->segment(5));
        $this->load->view('admin/webtoon/cartoonist_delete.php', $this->data);
        endif;
    }

    /*
    @desc : show list of maptoon announcement
    @param: numeric; idx of announcement table
     */
    public function announcement()
    {

        //Load the view
        $this->data['header'] = $this->load->view('admin/header', $this->data, true);
        $this->data['footer'] = $this->load->view('admin/footer', '', true);
        //Get Webtoons
        $this->data['webtoons'] = $this->wtoon_model->getWebtoons($arr='', 0, 0);

        $this->data['announcements']=$this->wtoon_model->getAnnouncements();

        $this->load->view('/admin/webtoon/announcement', $this->data);
    }

    /*
    @desc : register announcement
     */
    public function announcement_proc()
    {
        $idx = $this->input->post('idx');
        $wt_list_idx = $this->input->post('wt_list_idx');
        $idx  = $this->input->post('idx');
        $contents  = $this->input->post('contents');
        $s_date  = $this->input->post('s_date');
        $e_date  = $this->input->post('e_date');

        if (isset($idx) && $idx!='0' && $idx!='') {
            $data = [
                            'contents'     => $contents,
                            's_date'       => $s_date,
                            'e_date'       => $e_date
                        ];
            $this->db->where('idx', $idx);
            $ret = $this->db->update($this->tb_name_notice, $data);
            if ($ret==true) {
                $result['status'] = 1;
                $result['message'] = '수정되었습니다.';
            } else {
                $result['status'] = 0;
                $result['message'] = '수정 실패 관리자에게 문의';
            }
        } else {
            $data=[
                'wt_list_idx'  => $wt_list_idx,
                'contents'     => $contents,
                's_date'       => $s_date,
                'e_date'       => $e_date,
                'reg_date'     => date("Y-m-d H:i:s")
                ];
            $ret = $this->db->insert($this->tb_name_notice, $data);
            if ($ret==true) {
                $result['status'] = 1;
                $result['message'] = '등록되었습니다.';
            } else {
                $result['status'] = 0;
                $result['message'] = '등록 실패 관리자에게 문의';
            }
        }
        echo json_encode($result);
        exit;
    }

    /*
    @desc : delete maptoon announcement
     */
    public function announcement_delete()
    {
        if ($this->input->post('deleteid')):
            $this->wtoon_model->removeAnnouncement($this->input->post('deleteid'));
        redirect(BASE_URL.'/admin/webtoons/announcement'); else:
            $this->data['form']=$this->wtoon_model->getAnnouncements($this->uri->segment(5));
        $this->load->view('admin/webtoon/announcement_delete.php', $this->data);
        endif;
    }

    /*
    @desc : show list of maptoon episodes
     */
    public function episode()
    {
        $this->load->library('pagination');
        $result_per_page = $this->display_limit;  // the number of result per page
        $config['base_url'] = BASE_URL. '/admin/webtoons/episode/';
        $config['total_rows'] = $this->wtoon_model->countEpisodes(0);
        $config['per_page'] = $result_per_page;
        
        $this->pagination->initialize($config);

        $return_data['list'] = $result = array();

        $arr_cartoonist = $this->wtoon_model->get_cartoonist_list();  //작가 이름

        //Load the view
        $this->data['header'] = $this->load->view('admin/header', $this->data, true);
        $this->data['footer'] = $this->load->view('admin/footer', '', true);

        $arr_webtoon = $this->wtoon_model->getWebtoons(); //맵툰 이름 리스트
        $req_data['limit'] = $result_per_page;
        $req_data['offset'] = $this->uri->segment(4);
        $episode = $this->wtoon_model->getEpisode($req_data);

        $this->data['episode'] = $episode;
        $this->data['arr_cartoonist'] = $arr_cartoonist;
        $this->data['arr_webtoon'] = $arr_webtoon;

        $this->load->view('/admin/webtoon/episode', $this->data);
    }

    public function addEpisode()
    {
        $return_data['list'] = $result = array();

        //Load the view
        $this->data['header'] = $this->load->view('admin/header', $this->data, true);
        $this->data['footer'] = $this->load->view('admin/footer', '', true);

        $arr_webtoon = $this->wtoon_model->getWebtoons(); // 맵툰 이름 리스트

        $this->data['arr_webtoon'] = $arr_webtoon;

        $this->load->view('/admin/webtoon/episode_new', $this->data);
    }

    public function confirmEpisode()
    {
        $postID = ($this->wtoon_model->getInsertPostID()[0]['postID'])+1;
        $postTitle = $this->input->post('postTitle');
        $wt_list_idx = $this->input->post('wt_list_idx');
        $unixStamp = time();
        $datePosted = $this->input->post('datePosted');
        $postContentHTML = $this->input->post('contents');
        strtotime($datePosted)>$unixStamp? $published = 0 : $published = 1;
        $ep_no = $this->input->post('ep_no');

        //이미지 업로드
        if ($_FILES['postImage']['name']!='') {
            $mid_url_path = date("Y")."/".date("m");
            $upload_path = WEBTOON_DIR_BACK.$mid_url_path;
            if (!is_dir($upload_path)) {
                umask(0);
                mkdir($upload_path, 0777, true);
            }
            $config['max_size'] = 20*1024;
            $config['upload_path'] = $upload_path;
            $config['allowed_types'] = 'gif|jpg|png|jpeg';
            $config['encrypt_name'] = true;

            $this->load->library('upload');
            $this->upload->initialize($config);
            
            $file_name= date("H").date("i").date("s");
            
            if (! $this->upload->do_upload('postImage')) {
                $error = array('error' => $this->upload->display_errors());
                echo "이미지 업로드 실패";
            }
            $arr_upload_data = $this->upload->data();
            $postImage = (isset($arr_upload_data['file_name'])==true) ? WEBTOON_DIR_FRONT.$mid_url_path.'/'.$arr_upload_data['file_name'] : '';

            //remove previous image
            if (isset($webtoon_info[0])==true && $postImage!='') {
                $postImage = $webtoon_info[0]['postImage'];
                if ($main_img!='') {
                    unlink($_SERVER['DOCUMENT_ROOT'].$main_img);
                }
            }
        } else {
            $postImage = (isset($webtoon_info[0]['postImage'])==true) ? $webtoon_info[0]['postImage'] : '';
        }

        
        $data = [
                'postID'    => $postID,
                'postURL'    => $postID,
                'postTitle' => htmlspecialchars($postTitle),
                'postExcerpt' => "",
                'postContentHTML' => htmlspecialchars($postContentHTML),
                'postContent' => "",
                'postImage' => $postImage,
                'categoryID' => 20000,
                'published' => $published,
                'datePosted' => $datePosted,
                'dateUpdated' => date("Y-m-d h:i:s", $unixStamp),
                'unixStamp' => $unixStamp
            ];

        $this->wtoon_model->insertWebtoonPost($data);

        $data = [
            'postID'    => $postID,
            'wt_list_idx' => $wt_list_idx,
            'recommend_count' => 0,
            'view_count' => 0,
            'grade' => 0,
            'grade_total' => 0,
            'ep_no' => $ep_no
        ];

        $this->wtoon_model->insertEpisode($data);

        //Return to post list
        redirect(BASE_URL.'/admin/webtoons/episode', 'refresh');
    }

    public function add_episode_image()
    {
        $this->load->view('/admin/webtoon/add_episode_image');
    }

    public function add_episode_image_upload()
    {
        if ($_FILES['uploadInputBox']['name']!='') {
            $mid_url_path = date("Y")."/".date("m");
            $upload_path = WEBTOON_DIR_BACK.$mid_url_path;
            if (!is_dir($upload_path)) {
                umask(0);
                mkdir($upload_path, 0777, true);
            }
            $config['max_size'] = 20*1024;
            $config['upload_path'] = $upload_path;
            $config['allowed_types'] = 'gif|jpg|png|jpeg';
            $config['encrypt_name'] = true;

            $this->load->library('upload');
            $this->upload->initialize($config);
            
            $file_name= date("H").date("i").date("s");
            
            if (! $this->upload->do_upload('uploadInputBox')) {
                $error = array('error' => $this->upload->display_errors());
            }
            $arr_upload_data = $this->upload->data();
            
            /*echo ('<script language=\"javascript\">
                var tempImg = \'<div class="center-align"><img src="'.WEBTOON_DIR_FRONT.$mid_url_path.'/'.$arr_upload_data['file_name'].'" title="" alt="comic content"></div>\';
                opener.tinymce.activeEditor.execCommand("mceInsertContent","false",tempImg);
                </script>
                ');*/
            echo WEBTOON_DIR_FRONT.$mid_url_path.'/'.$arr_upload_data['file_name'];
        }
    }

    public function editEpisode()
    {
        //Load the view
        $this->data['header'] = $this->load->view('admin/header', $this->data, true);
        $this->data['footer'] = $this->load->view('admin/footer', '', true);
        
        $arr_webtoon = $this->wtoon_model->getWebtoons(); // 맵툰 이름 리스트
        $this->data['arr_webtoon'] = $arr_webtoon;

        $postID=$this->uri->segment(5);
        $req_data['postID']= $postID;
        $episode = $this->wtoon_model->getEpisode($req_data);
        $this->data['episode'] = $episode;
        $this->load->view('/admin/webtoon/episode_edit', $this->data);
    }

    public function editedEpisode()
    {
        $postID = $this->input->post('postID');
        $postTitle = $this->input->post('postTitle');
        $wt_list_idx = $this->input->post('wt_list_idx');
        $unixStamp = time();
        $datePosted = $this->input->post('datePosted');
        $postContentHTML = $this->input->post('contents');
        strtotime($datePosted)>$unixStamp? $published = 0 : $published = 1;
        $ep_no = $this->input->post('ep_no');

        $req_data['postID']= $postID;
        $webtoon_info = $this->wtoon_model->getEpisode($req_data);

        //이미지 업로드
        if ($_FILES['postImage']['name']!='') {
            $mid_url_path = date("Y")."/".date("m");
            $upload_path = WEBTOON_DIR_BACK.$mid_url_path;
            if (!is_dir($upload_path)) {
                umask(0);
                mkdir($upload_path, 0777, true);
            }
            $config['max_size'] = 20*1024;
            $config['upload_path'] = $upload_path;
            $config['allowed_types'] = 'gif|jpg|png|jpeg';
            $config['encrypt_name'] = true;

            $this->load->library('upload');
            $this->upload->initialize($config);
            
            $file_name= date("H").date("i").date("s");
            
            if (! $this->upload->do_upload('postImage')) {
                $error = array('error' => $this->upload->display_errors());
                echo "이미지 업로드 실패";
            }
            $arr_upload_data = $this->upload->data();
            $postImage = (isset($arr_upload_data['file_name'])==true) ? WEBTOON_DIR_FRONT.$mid_url_path.'/'.$arr_upload_data['file_name'] : '';

            //remove previous image
            if (isset($webtoon_info[0])==true && $postImage!='') {
                $postImage = $webtoon_info[0]['postImage'];
                if ($postImage!='') {
                    unlink($_SERVER['DOCUMENT_ROOT'].$postImage);
                }
            }
        } else {
            $postImage = (isset($webtoon_info[0]['postImage'])==true) ? $webtoon_info[0]['postImage'] : '';
        }
        
        $data = [
                'postID'    => $postID,
                'postURL'    => $postID,
                'postTitle' => htmlspecialchars($postTitle),
                'postExcerpt' => "",
                'postContentHTML' => htmlspecialchars($postContentHTML),
                'postContent' => "",
                'postImage' => $postImage,
                'categoryID' => 20000,
                'published' => $published,
                'datePosted' => $datePosted,
                'dateUpdated' => date("Y-m-d h:i:s", $unixStamp),
            ];

        $this->wtoon_model->updateWebtoonPost($data);

        $data = [
            'postID'    => $postID,
            'wt_list_idx' => $wt_list_idx,
            'recommend_count' => 0,
            'view_count' => 0,
            'grade' => 0,
            'grade_total' => 0,
            'ep_no' => $ep_no
        ];

        $this->wtoon_model->updateEpisode($data);

        //Return to post list
        redirect(BASE_URL.'/admin/webtoons/episode', 'refresh');
    }

    /*
    @desc : delete maptoon announcement
     */
    public function episode_delete()
    {
        if ($this->input->post('deleteid')):
            $this->wtoon_model->removeEpisode($this->input->post('deleteid'));
        redirect(BASE_URL.'/admin/webtoons/episode'); else:
            $req_data['postID'] = $this->uri->segment(5);
        $this->data['form']=$this->wtoon_model->getEpisode($req_data);
        $this->load->view('admin/webtoon/episode_delete.php', $this->data);
        endif;
    }

    /*
    @desc : list all the maptoon categories
     */
    public function category()
    {

        //Load the view
        $this->data['header'] = $this->load->view('admin/header', $this->data, true);
        $this->data['footer'] = $this->load->view('admin/footer', '', true);

        $idx = $this->input->get('idx');
        
        $categories = $this->wtoon_model->getCategory();
        $this->data['categories']=$categories;
            
        $this->load->view('/admin/webtoon/category', $this->data);
    }
    

    public function editCategory()
    {
        //Load the view
        $this->data['header'] = $this->load->view('admin/header', $this->data, true);
        $this->data['footer'] = $this->load->view('admin/footer', '', true);

        $categoryID = $this->uri->segment(5);
        
        $data_category = $this->wtoon_model->getCategory($categoryID);

        $this->data['categoryTitle'] = $data_category['categoryTitle'];

        $data_episodes = $this->wtoon_model->get_episodes_by_category($categoryID);


        if ($data_episodes!=false) {
            $this->data['list'] = $data_episodes;
        } else {
            $this->data['list'] = '';
        }
        
        $this->data['categoryID'] = $categoryID;
        $this->load->view('/admin/webtoon/category_edit', $this->data);
    }

    /*
    get list of maptoon episodes
    @return json string
     */
    public function get_episodes_by_search_keyword()
    {
        $keyword = $this->input->get('keyword');
        if ($keyword!='') {
            $row = $this->wtoon_model->get_episodes_by_search_keyword($keyword);
            // $row = array(['idx'=>2, 'main_img'=>'/files/maptoon/2019/03/efe2b7b7f5d738ffc4ff288ef3a5b055.png','title'=>htmlspecialchars('김"집사')],
            // 	['idx'=>3, 'main_img'=>'/files/maptoon/2019/03/efe2b7b7f5d738ffc4ff288ef3a5b055.png','title'=>'김집사']);
            echo json_encode($row);
            exit;
        }
    }
    
    public function register_episode_in_category()
    {
        $postID = $this->input->post('postID');
        $categoryID = $this->input->post('categoryID');
        // $len = count($postID);
        $ret = $this->wtoon_model->update_episodes_by_category($categoryID, $postID);

        redirect(BASE_URL.'/admin/webtoons/category');
    }
    
    public function get_next_ep_no()
    {
        $wt_list_idx = $this->input->post('wt_list_idx');
        $res_data = $this->wtoon_model->get_next_ep_no($wt_list_idx);
        echo $res_data->ep_no+1;
    }
}
