<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Welcome extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->permission->is_admin();
        //$this->output->enable_profiler(TRUE);
        $this->load->model('Area_model');
        $this->load->model('InfoStructures_model');
        $this->load->model('Information_model');
        $this->load->model('InfoContents_model');
        $this->load->model('Coupon_model');
        $this->load->model('Logs_model');
    }

    public function index() {
		$data=array();
        $data['countryList'] = $this->Area_model->get_country_list();
        $data['provinceList'] = $this->Area_model->get_province_list();
        $data['city_list'] = $this->Area_model->get_municipalities_list();
        $data['lastEditList'] = $this->Information_model->get_last_edit_list();
        $data['last_city_list'] = $this->Area_model->get_last_edit_city();
		
		$data['groupList']=$this->Information_model->group_list();
		
		if(is_mobile_first() ){
			
			$this->load->view('bootstrap3/header', $data);
			$this->load->view('bootstrap3/welcome');
			$this->load->view('bootstrap3/footer');
			return;
		}
		



        if ($this->config->item('site_code') == 'pgr') {
            $data['countryList'] = $this->Area_model->get_country_list_for_site("'589','645','632','517','31','28','609','630','9','708','709'");
        }

        $this->load->view('bootstrap/header', $data);
        $this->load->view('bootstrap/welcome');
        $this->load->view('bootstrap/footer');
    }
	
	


    public function search($isrecommend = false) {
        //先搜索url，如果找到唯一就跳走，多于一条的则列出来，一条没有的就去搜索信息
        $data['keywords'] = $this->input->post('keywords');
        $data['all_text_search'] = $this->input->post('all_text_search'); //全文搜索
        $search_url = str_replace($this->config->item('site_url'), "", $data['keywords']);
        $data['search_list'] = $this->Information_model->search_url($search_url);
        if (count($data['search_list']) === 0) {
            if (!empty($data['all_text_search']) && $data['all_text_search'] == 'true') {
                $data['search_list'] = $this->Information_model->search_all_text($data['keywords'],48);
            } else {
                $data['search_list'] = $this->Information_model->search($data['keywords']);
            }
        }

        if ($isrecommend) {
            $data['ic_id_list'] = $this->input->post('ic_id_list') == '' ? '0' : $this->input->post('ic_id_list');
            $this->load->view('bootstrap3/recommendlist', $data);
            return TRUE;
        } else if (count($data['search_list']) === 1) {
            redirect(site_url('information/edit/' . $data['search_list'][0]->is_id));
        }

        $data['countryList'] = $this->Area_model->get_country_list();
        $data['provinceList'] = $this->Area_model->get_province_list();
        $data['city_list'] = $this->Area_model->get_municipalities_list();

        $this->load->view('bootstrap/header', $data);
        $this->load->view('bootstrap/welcome');
        $this->load->view('bootstrap/footer');
    }

    //获取所有信息URL,用来批量静态化更新
    public function create_all_urls($view=false) {
        set_time_limit(0);
        $this->output->enable_profiler(false);
        $data['all_information'] = $this->Information_model->GetList('ic_status,ic_id,ic_url,ic_sitecode,is_id');
        if ($view == 'amp') {
            $this->load->view('bootstrap3/header', $data);
            $this->load->view('bootstrap3/refresh_amp_urls');
            $this->load->view('bootstrap3/footer');
        } else {
            $this->load->view('bootstrap/header', $data);
            $this->load->view('bootstrap/cache_url', $data);
            $this->load->view('bootstrap/footer');
        }
    }

    //获取某个信息节点和子节点url
    //$is_parent_id 结构id或者是url
    public function create_infomation_urls($is_parent_id, $view = false) {
        $ic_url=$this->input->get_post('ic_url');
        if(!empty($ic_url)){
            $structure = $this->Information_model->Detail($ic_url);
        }else{
            $structure = $this->InfoStructures_model->Detail($is_parent_id);
        }

        if (empty($structure)) {
            show_404();
            return false;
        }
        $data['all_information'] = $this->Information_model->get_list_by_path($structure->is_path,false,false,'is_id,ic_url,ic_id,ic_status');
        $this->load->view('bootstrap3/header', $data);
        switch ($view){
            case 'amp':
                $this->load->view('bootstrap3/refresh_amp_urls');
                break;
            case 'mobile-first':
                $this->load->view('bootstrap3/refresh_mobile_first_urls');
                break;
            default:
                $this->load->view('bootstrap/cache_url', $data);

        }
        $this->load->view('bootstrap/footer');
    }
	
	//根据信息节点ID获取信息，用于搜索结果的批量更新静态页面
	public function create_infomation_urls_by_ids($view = false){
		$is_ids=$this->input->get('key');
		if (empty($is_ids)) {
			show_404();
			return false;
		}
        $data['all_information'] = $this->Information_model->get_detail_by_ids($is_ids);
        if ($view == 'amp') {
            $this->load->view('bootstrap3/header', $data);
            $this->load->view('bootstrap3/refresh_amp_urls');
            $this->load->view('bootstrap3/footer');
        } else {
            $this->load->view('bootstrap/header', $data);
            $this->load->view('bootstrap/cache_url', $data);
            $this->load->view('bootstrap/footer');
        }
	}

    public function get_infomation_urls($is_parent_id) {
        $this->output->enable_profiler(FALSE);
        $structure = $this->InfoStructures_model->Detail($is_parent_id);
        if (empty($structure)) {
            show_404();
            return false;
        }
        $data['all_information'] = $this->Information_model->get_list_by_path($structure->is_path);

        $this->load->view('bootstrap/header', $data);
        $this->load->view('bootstrap/static_url', $data);
        $this->load->view('bootstrap/footer');
    }

    public function get_info_backup_id($info_id) {
        $last_backup = $this->Logs_model->get_last_backup($info_id);
        if (empty($last_backup)) {
            $this->echo_json(array(
                'status' => 'error',
                'logId' => 0,
                'datetime' => 0,
                'username' => 0
            ));
        } else {
            $this->echo_json(array(
                'status' => 'success',
                'logId' => $last_backup->log_id,
                'datetime' => $last_backup->log_datetime,
                'username' => $last_backup->log_ht_username
            ));
        }
    }

    public function change_static_url($info_id) {
        $information = $this->Information_model->Detail($info_id);
        $htm_doc = new DOMDocument();
        $htm_doc->encoding = 'UTF-8';
        libxml_use_internal_errors(true);
        $htm_doc->strictErrorChecking = false;
        if (empty($information->ic_content)) {
            $this->echo_json(array(
                'status' => 'error',
                'infoId' => $info_id,
                'message' => 'info content is empty'
            ));
            return;
        }
        $htm_doc->loadHTML(
                mb_convert_encoding($information->ic_content, 'HTML-ENTITIES', 'UTF-8'));
        $htm_doc->normalizeDocument();
        $img_list = $htm_doc->getElementsByTagName('img');
        foreach ($img_list as $img) {
            $img_src = $img->getAttribute('src');
            $img_src = $this->check_url($img_src);
            $img->setAttribute('src', $img_src);
        }

        $anchor_list = $htm_doc->getElementsByTagName('a');
        foreach ($anchor_list as $anchor) {
            $a_href = $anchor->getAttribute('href');
            echo 'a.href: ' . $a_href . '<br>';

            $match_result = array();
            preg_match('/^http:\/\/www.chinahighlights.com(.*)/', $a_href, $match_result);
            $result_count = count($match_result);
            if ($result_count == 2) {
                $result = '//www.chinahighlights.com' . $match_result[1];
                $anchor->setAttribute('href', $result);
                echo $result . '<br>';
            }
        }

    }

    public function count_redirect_nofollow() {
        $include_redirece_info = $this->Information_model->search_all_text('&t=78002', 2000);
        echo 'redirect count: ' . count($include_redirece_info) . '<br/>';
        $redirect_nofollow_list = array();
        $htm_doc = new DOMDocument();
        $htm_doc->encoding = 'UTF-8';
        libxml_use_internal_errors(true);
        $htm_doc->strictErrorChecking = false;
        foreach ($include_redirece_info as $info) {
            $htm_doc->loadHTML(
                    mb_convert_encoding($info->ic_content, 'HTML-ENTITIES', 'UTF-8'));
            $htm_doc->normalizeDocument();
            $anchor_list = $htm_doc->getElementsByTagName('a');
            foreach ($anchor_list as $anchor) {
                $a_href = $anchor->getAttribute('href');
                $a_rel = $anchor->getAttribute('rel');

                $match_result = array();
                preg_match('/.*&t=78002$/', $a_href, $match_result);
                $result_count = count($match_result);
                if ($result_count > 0 && $a_rel != 'nofollow') {
                    echo $info->ic_url . ' | ' . '(' . $info->ic_id . ',' . $info->is_id . ')' . '<br/>';
                    echo 'a.href: ' . $a_href . '; rel: ' . $a_rel . '<br>';
                    $redirect_nofollow_list[] = $info;
                }
            }
        }
        echo 'nofollow_count: ' . count($redirect_nofollow_list) . '<br/>';
        return $redirect_nofollow_list;
    }

    public function transform_redirect_nofollow() {
        $redirect_nofollow_list = $this->count_redirect_nofollow();
        $htm_doc = new DOMDocument();
        $htm_doc->encoding = 'UTF-8';
        libxml_use_internal_errors(true);
        $htm_doc->strictErrorChecking = false;

        foreach ($redirect_nofollow_list as $info) {
            $htm_doc->loadHTML(
                    mb_convert_encoding($info->ic_content, 'HTML-ENTITIES', 'UTF-8'));
            $htm_doc->normalizeDocument();
            $anchor_list = $htm_doc->getElementsByTagName('a');
            foreach ($anchor_list as $anchor) {
                $a_rel = $anchor->getAttribute('rel');
                $anchor->setAttribute('rel', 'nofollow');
                $this->Logs_model->backup($info->is_id, $info->ic_content);
                $info->ic_content = $htm_doc->saveHTML();
                $this->InfoContents_model->Update(
                        $info->ic_id, $info->ic_url, $info->ic_url_title, $info->ic_type, $info->ic_title, $info->ic_content, $info->ic_summary, $info->ic_seo_title, $info->ic_seo_description, $info->ic_seo_keywords, $info->ic_show_bread_crumbs, $info->ic_status, $info->ic_template, $info->ic_photo, $info->ic_photo_width, $info->ic_photo_height, $info->ic_recommend_tours, $info->ic_recommend_packages, $info->ic_ht_area_id, $info->ic_ht_area_type, $info->ic_ht_product_id, $info->ic_ht_product_type, $info->ic_author);
            }
        }

        echo 'update_nofollow_count: ' . count($redirect_nofollow_list) . '<br/>';
    }

    public function count_http_of_href() {
        $data['all_information'] = $this->Information_model->search_all_text('http://www.chinahighlights.com/', 2000);
        echo 'count: ' . count($data['all_information']) . '<br/>';
        var_dump($data['all_information']);
    }

    public function transform_href_to_https() {
        $http_host = 'http://www.chinahighlights.com/';
        $https_host = 'https://www.chinahighlights.com/';
        $data['all_information'] = $this->Information_model->search_all_text($http_host, 200);
        echo 'count: ' . count($data['all_information']) . '<br/>';
        if (empty($data['all_information'])) {
            echo 'nothing transform to https';
        } else {
            foreach ($data['all_information'] as $item) {

                if (empty($item->ic_url)) {
                    echo '<span style="color: red;">[' . $item->ic_title . '] [' . $item->ic_url . ']</span> <br/>';
                    continue;
                } else {
                    echo $item->ic_url . ' | ' . $item->ic_title . '<br/>';
                }

                $this->Logs_model->backup($item->is_id, $item->ic_content);
                $item->ic_content = str_replace($http_host, $https_host, $item->ic_content);
                $this->InfoContents_model->Update(
                        $item->ic_id, $item->ic_url, $item->ic_url_title, $item->ic_type, $item->ic_title, $item->ic_content, $item->ic_summary, $item->ic_seo_title, $item->ic_seo_description, $item->ic_seo_keywords, $item->ic_show_bread_crumbs, $item->ic_status, $item->ic_template, $item->ic_photo, $item->ic_photo_width, $item->ic_photo_height, $item->ic_recommend_tours, $item->ic_recommend_packages, $item->ic_ht_area_id, $item->ic_ht_area_type, $item->ic_ht_product_id, $item->ic_ht_product_type, $item->ic_author
                );
            }
        }
    }

    private function echo_json($obj) {
        $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode($obj));
    }

    //批量替换二级域名，如图片或者data域名
    function replace_hostname($topnum) {
        $data = array();
        $find_host = 'http://data.chinarundreisen.com/';  //http://bilder.chinarundreisen.com/
        $new_host = '//data.chinarundreisen.com/';
        $data['all_information'] = $this->Information_model->search_all_text($find_host, $topnum);
        if ($data['all_information']) {
            foreach ($data['all_information'] as $item) {
                echo $item->ic_url . '<br/>';
                $item->ic_content = str_replace($find_host, $new_host, $item->ic_content);
                $this->InfoContents_model->Update(
                        $item->ic_id, $item->ic_url, $item->ic_url_title, $item->ic_type, $item->ic_title, $item->ic_content, $item->ic_summary, $item->ic_seo_title, $item->ic_seo_description, $item->ic_seo_keywords, $item->ic_show_bread_crumbs, $item->ic_status, $item->ic_template, $item->ic_photo, $item->ic_photo_width, $item->ic_photo_height, $item->ic_recommend_tours, $item->ic_recommend_packages, $item->ic_ht_area_id, $item->ic_ht_area_type, $item->ic_ht_product_id, $item->ic_ht_product_type, $item->ic_author
                );
            }
        } else {
            echo 'all done';
        }
    }

    private function check_url($subject) {
        $result = $subject;
        $check_rules = array(
            '/^\/image\/(.*)/' => '//data.chinahighlights.com/image/',
            '/^\/pic\/(.*)/' => '//data.chinahighlights.com/pic/',
            '/^\/allpicture\/(.*)/' => '//data.chinahighlights.com/allpicture/',
            '/^http:\/\/images.chinahighlights.com(.*)/' => '//images.chinahighlights.com',
            '/^http:\/\/data.chinahighlights.com(.*)/' => '//data.chinahighlights.com',
            '/^http:\/\/www.chinahighlights.com(.*)/' => '//www.chinahighlights.com');

        foreach ($check_rules as $pattern => $replace) {
            $result = $this->replace_url($pattern, $replace, $result);
        }
        return $result;
    }

    private function replace_url($pattern, $replace, $subject) {
        $result = $subject;
        $match_result = array();
        preg_match($pattern, $subject, $match_result);
        $result_count = count($match_result);
        if ($result_count == 2) {
            $result = $replace . $match_result[1];
        }
        return $result;
    }

    //生肖促销订单查询
    public function coupon() {
        $data['countryList'] = $this->Area_model->get_country_list();
        $data['provinceList'] = $this->Area_model->get_province_list();
        $data['city_list'] = $this->Area_model->get_municipalities_list();
        $data['coupon'] = $this->Coupon_model->getlist();

        $this->load->view('bootstrap/header', $data);
        $this->load->view('bootstrap/welcome');
        $this->load->view('bootstrap/footer');
    }

    public function set_path($is_id, $parent_path = '') {
        $parent_path = str_replace('-', ',', $parent_path);
        $parent_path = trim($parent_path, ',');
        if ($parent_path != '')
            $parent_path .= ',';
        $this->load->model('Import_model');
        $this->Import_model->set_path($is_id, $parent_path);
        echo 'ok';
    }

    public function search_by_icid() {
        $ic_id_list = $this->input->post('ic_id_list');
        $ic_id_list = rtrim(trim($ic_id_list), ',') . ',';
        $this->load->model('InfoContents_model');
        $data['search_list'] = $this->InfoContents_model->get_ic_contents_by_list($ic_id_list);
        $data['search_type'] = 'recommended';
        $this->load->view('bootstrap3/recommendlist', $data);
    }

    /**
     * @description: 用于生成一个特殊的根结点is_level和is_sort都为0，CT移动优先项目用
     * @param {type} 
     * @return: 
     * @Date Changed: 
     */
    public function AddRootNote(){
        $this->InfoContents_model->Add('', 'NewRootNote', 'root', 'NewRootNote', '', '', '', '', '', 0, 0, '', '', 0, 0, '', '', '', '', 0,
        '','');
        $this->InfoStructures_model->AddRootNote($this->InfoContents_model->insert_id);
        $is_id = $this->InfoStructures_model->insert_id;
        redirect(site_url('information/edit/' . $is_id));
    }

}
