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

class Advertisement_lib {
    var $ad_page_tb_name = 'ad_page'; // 광고 페이지 테이블 이름
    var $ad_code_tb_name = 'ad_detail'; // 광고 코드 테이블 이름
	var $file_cache_path = '';
	var $CI = null;

	public function __construct($params) {
		if(isset($params['file_cache_path'])==TRUE && $params['file_cache_path']!='') {
			$this->file_cache_path = $params['file_cache_path'];
		}
		$this->CI = &get_instance();
	}


	public function create_ad_cache(){
		$this->CI->load->database();
        $query = $this->CI->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);

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

	/*
	write advertisement cache file
	@param (string) advertisement data
	@return (boolean)
	 */
	public function write_ad_cache($json_data) {
		$this->CI->load->helper('file');
		$fname = $this->get_ad_cache_name();
		if($fname!='') {
			return write_file($fname, $json_data, 'w');		
		} else {
			return FALSE;
		}
	}

	public function get_ad_data($page_key){
		$data=$this->get_ad_cache();
		$data=json_decode($data,TRUE);
		if(isset($data[$page_key])){
			
		}else{
			return FALSE;
		}
	}

	public function get_ad_cache() {
		$this->CI->load->helper('file');
		$fname = $this->get_ad_cache_name();
		if($fname!='') {
			return read_file($fname);
		} else {
			return FALSE;
		}
	}

	/*
	get category cache file name
	@param (numeric) maptoon category table idx
	@return (string | null)
	 */
	public function get_ad_cache_name() {
		$fname = $this->file_cache_path.'advertisement';
		return $fname;
	}
}