<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * 인클루드 class
 *
 * cm_controller: 부모 Class(CI_Controller 확장한 custome class)
 */
include_once (APPPATH.'core/admin/cm_controller.php');

class advertisement extends cm_controller {

    var $ad_page_tb_name = 'ad_page'; // 광고 페이지 테이블 이름
    var $ad_code_tb_name = 'ad_detail'; // 광고 코드 테이블 이름

	/*
     title : 광고 페이지 관리 (목록)
     */
	public function fn_1($page=1) {
        $this->load->database();
        $query = $this->db->get($this->ad_page_tb_name);
        $i = 0;
        $return_data = array();
        foreach($query->result_array() as $row) {
            $return_data['row'][$i] = $row;
            $i++;
        }
        return $this->load->view('/admin/advertisement/ads', $return_data, true);

    }

    public function fn_ad_page_arr_del_proc() {
        $is_del = $this->input->post('is_del');
        foreach($is_del as $v) {
            if($v>0) {
                $where_in[] = $v;
            }
        }
        if(count($where_in)>0) { 
            $this->load->database();
            $this->db->where_in('idx',$where_in);
            $ret = $this->db->delete($this->ad_page_tb_name);
            if($ret==TRUE) {
                $message = '삭제되었습니다.';
            } else {
                $message = '삭제되지 않았습니다.(디비 에러) 서버 관리자에게 문의해 주십시오.';
            }
            echo "<script>alert('".$message."'); parent.location.reload();</script>";
        }
        exit;
    }

    public function fn_ad_page_edit() {
        $idx = $this->input->get('idx');

        if(is_numeric($idx)==TRUE) {
            $this->load->database();
            $query = $this->db->get_where($this->ad_page_tb_name, array('idx'=>$idx));
            $row = $query->row_array();
            $row['result'] = 'success';
        } else {
            $row['result'] = 'fail';
        }
        echo json_encode($row);
        exit;
    }

    /**
     * [ad_page_proc register ad page]
     * @return [boolean] 
     */
    public function fn_ad_page_proc() {
        $page_key = $this->input->post('page_key');
        $page_name = $this->input->post('page_name');
        $ad_pos_key = $this->input->post('ad_pos_key');
        $ad_pos_name = $this->input->post('ad_pos_name');
        $mode = $this->input->post('mode');
        $idx = $this->input->post('idx');

        $this->load->library('form_validation');
        $this->form_validation->set_rules('page_key','페이지 키',array('required','regex_match[/^[a-zA-Z]+$/]'));
        $this->form_validation->set_rules('page_name','페이지 이름',array('required'));
        $this->form_validation->set_rules('ad_pos_key','광고 위치 키',array('required','regex_match[/^[a-zA-Z]+$/]'));
        $this->form_validation->set_rules('ad_pos_name','광고 위치 이름',array('required'));
        if ($this->form_validation->run() == TRUE) {
            $this->load->database();
            $data = ['page_key'=>$page_key,
                     'page_name'=>$page_name,
                     'ad_pos_key'=>$ad_pos_key,
                     'ad_pos_name'=>$ad_pos_name];
            if($mode=='upt' && $idx>0) {
                $this->db->where('idx',$idx);
                $this->db->update($this->ad_page_tb_name,$data);
                $message = '수정되었습니다';
            } else {
                $this->db->insert($this->ad_page_tb_name,$data);
                $message = '등록되었습니다';
            }
            echo "<script>alert('".$message."'); parent.location.reload();</script>";
        } else {
            echo "<script>alert('적합한 데이터를 입력해 주십시오.');exit;</script>";
        }
        exit;
    }
    
    // 개별광고페이지
    public function fn_ad_detail(){
        $this->load->database();
        // $this->db->select('*');
        // $this->db->from($this->ad_code_tb_name);
        // $this->db->join($this->ad_page_tb_name, $this->ad_page_tb_name.'.idx = '.$this->ad_code_tb_name.'.ad_idx');
        // $query = $this->db->get();
        $query = $this->db->query("SELECT a.idx, b.page_name, b.ad_pos_name, a.ad_code, a.ad_file FROM $this->ad_code_tb_name AS a JOIN  $this->ad_page_tb_name AS b ON a.ad_idx = b.idx");
        $i = 0;
        $return_data = array();
        foreach($query->result_array() as $row) {
            $return_data['row'][$i] = $row;
            $i++;
        }
        return $this->load->view('/admin/advertisement/ad_detail',$return_data,true);
    }

    // 개별광고페이지 등록 및 수정 form
    public function fn_ad_register(){
        $this->load->database();
        //page_list 만들기
        $query = $this->db->get($this->ad_page_tb_name);
        $i=0;
        $return_data = array();
        $result=$query->result_array();
        foreach($result as $v){
            $page_list[]=$v['page_name'];
        }

        $return_data['page_name']=array_values(array_unique($page_list)); //page_name list

        //page_list array 에 광고 위치 push
        $x = count($return_data['page_name']);
        $return_data['ad_pos_name']=array();
        $y=0;
        foreach($return_data['page_name'] as $row2) {
            foreach($result as $row) {
                if($row['page_name']==$row2){
                    $return_data['ad_pos_name'][$y][]=$row['ad_pos_name'];
                }
            }
            $y++;
        }

        //수정btn으로 이동했을 시
        if($this->input->post('mode')=='modify'){
            $return_data['mode']='modify';
            $select ='a.*, b.page_name, b.ad_pos_name';
            $query = $this->db->query("SELECT $select FROM $this->ad_code_tb_name AS a JOIN $this->ad_page_tb_name AS b ON a.ad_idx = b.idx");
            foreach($query->result_array() as $row) {
                $return_data['edit_data'] = $row;
            }
        }else{
            $return_data['mode']='reg';
        }

        // row -> 전체 배열 
        // page_name -> page_name list
        // ad_pos_name -> ad_pos_name list
        // mode -> 수정 등록 구분
        // edit_data -> 수정일 때 data

        return $this->load->view('/admin/advertisement/ad_reg', $return_data , true);
    }

    //개별광고 등록 
    public function fn_ad_detail_reg(){
        $page_name = $this->input->post('page_title');
        $ad_pos_name = $this->input->post('ad_pos');

        $ad_option = $this->input->post('ad_option');         // $ad_option 0: 광고 파일 등록 1:광고 코드 등록
        $ad_lending = $this->input->post('ad_lending');
        $ad_code = htmlspecialchars($this->input->post('ad_code'));

        $where=array('page_name' => $page_name, 'ad_pos_name' => $ad_pos_name);

        $this->load->database();
        $query = $this->db->get_where($this->ad_page_tb_name, $where);
        $ad_idx; //ad_idx 찾기
        foreach ($query->result() as $row)
        {
              $ad_idx = $row->idx;
        }
        //이미지 업로드
        if($_FILES['ad_file']['name']!='') {
                $upload_path = './files/advertisement/'.date("Y")."/".date("m");
                if (!is_dir($upload_path)) {
                    umask(0);
                    mkdir($upload_path, 0777, TRUE);
                }
                $config['upload_path']      = $upload_path;
                $config['allowed_types']    = 'gif|jpg|png';
                $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('ad_file')) {
                    $error = array('error' => $this->upload->display_errors());
                    gf_alert("이미지 업로드에 실패했습니다.", 'back');
                    exit;
                }
                $arr_upload_data = $this->upload->data();
                $ad_file = str_replace($_SERVER['DOCUMENT_ROOT'], '', $arr_upload_data['full_path']);
        }

        // 이미 존재하는 데이터이면 수정 함
        $where=array('ad_idx' => $ad_idx);
        $query = $this->db->get_where($this->ad_code_tb_name, $where);
        $result = $query->result();
        empty($result[0]->idx)?$isdata=false:$isdata=true;

        if($isdata){
            if(!empty($ad_file)){
                $update_data = array(
                    'ad_idx' => $ad_idx,
                    'ad_option' => $ad_option,
                    'ad_file' => $ad_file,
                    'ad_lending' => $ad_lending,
                    'ad_code' => $ad_code,
                );
            }else{
                $update_data = array(
                    'ad_idx' => $ad_idx,
                    'ad_option' => $ad_option,
                    'ad_lending' => $ad_lending,
                    'ad_code' => $ad_code,
                );
            }
                $this->db->where('idx', $result[0]->idx);
                $this->db->update($this->ad_code_tb_name, $update_data);
        }else{
            if(!empty($ad_file)){
            $insert_data = array(
                'ad_idx' => $ad_idx,
                'ad_option' => $ad_option,
                'ad_file' => $ad_file,
                'ad_lending' => $ad_lending,
                'ad_code' => $ad_code,
            );
            }else{
                $insert_data = array(
                    'ad_idx' => $ad_idx,
                    'ad_option' => $ad_option,
                    'ad_lending' => $ad_lending,
                    'ad_code' => $ad_code,
                );
            }
            $this->db->insert($this->ad_code_tb_name, $insert_data); 
        }
        $this->config->load('filecache',TRUE);
        $file_cache_path = $this->config->item('file_cache_path','filecache');
        $params = array('file_cache_path'=>$file_cache_path);
        $this->load->library('advertisement_lib',$params);
        $this->advertisement_lib->create_ad_cache();
        $this->load->helper('url');
        redirect('https://crossmap.co.kr/admin/advertisement/ad_detail');
    }

    //광고 개별 관리 삭제
    public function fn_ad_detail_arr_del_proc() {
        $is_del = $this->input->post('is_del');
        foreach($is_del as $v) {
            if($v>0) {
                $where_in[] = $v;
            }
        }
        if(count($where_in)>0) { 
            $this->load->database();
            $this->db->where_in('idx',$where_in);
            $ret = $this->db->delete($this->ad_code_tb_name);
            if($ret==TRUE) {
                $message = '삭제되었습니다.';
            } else {
                $message = '삭제되지 않았습니다.(디비 에러) 서버 관리자에게 문의해 주십시오.';
            }
            echo "<script>alert('".$message."'); parent.location.reload();</script>";
        }
        $this->config->load('filecache',TRUE);
        $file_cache_path = $this->config->item('file_cache_path','filecache');
        $params = array('file_cache_path'=>$file_cache_path);
        $this->load->library('advertisement_lib',$params);
        $this->advertisement_lib->create_ad_cache();
        exit;
    }

    public function fn_ad_create_cache(){
        $this->load->database();
        $query = $this->db->query("SELECT a.idx, b.page_key, b.ad_pos_key, a.ad_option, a.ad_code, a.ad_file,a.ad_lending FROM $this->ad_code_tb_name AS a JOIN  $this->ad_page_tb_name AS b ON a.ad_idx = b.idx");
        $i=array();
        foreach($query->result_array() as $v){
            $i[$v['page_key']][$v['ad_pos_key']]=array('option'=>$v['ad_option'],'ad_code'=>$v['ad_code'],'ad_file'=>$v['ad_file'],'ad_lending'=>$v['ad_lending']);
        }
        
        $json_data=json_encode($i);
        
        print_r($i);

        $this->config->load('filecache',TRUE);
        $file_cache_path = $this->config->item('file_cache_path','filecache');
        $params = array('file_cache_path'=>$file_cache_path);
        $this->load->library('advertisement_lib',$params);

        if($json_data!=FALSE) {
            $this->advertisement_lib->write_ad_cache($json_data);	
        }
    }
    
}

