<?php
if (!defined('IN_59MIAO'))
{
	exit('Access Defined');
}
//广告控制器
class AdAction extends Action {
	public function __construct(){
		parent::__construct();
	}
	
	public function index(){
		parent::page();
		$AllAd=$this->_model->findAll();
		if ($AllAd) {
				foreach ($AllAd as $_value){
					switch ($_value->type) {
						case 1 :
							$_value->type = '图片广告';
							break;
						case 2 :
							$_value->type = '文字广告';
							break;
					}				
			}
		}		
		$this->_tpl->assign('AllAd',$AllAd);
		$this->_tpl->display(SMARTY_ADMIN.'ad/show.tpl');
	}		
	public function add(){
		if (isset($_POST['send']))
		{
			if($this->_model->add()){
				$lastid=$this->_model->last_insert_id();			
				$LastOne=$this->_model->findLastOne($lastid[0]->maxid);					
				$this->savead($LastOne[0]);
				$this->_redirect->succ('?a=ad', '广告新增成功！');
			} 
			else{
				 $this->_redirect->error('广告新增失败！');
			}
		}		
		
		$this->_tpl->display(SMARTY_ADMIN.'ad/add.tpl');
	}	
	public function delete() {
		if (isset($_GET['id']))
		{
			$Onead=$this->_model->findOne();
			$js_file='./data/adjs/'.$Onead[0]->adindex.'.js';
			Tool::unlinkFile($js_file);
		 	$this->_model->delete() ? $this->_redirect->succ(Tool::getPrevPage(), '广告名称删除成功！') : $this->_redirect->error('广告名称删除失败！');
		}
	}	
	public function update() {
		if (isset($_POST['send']))
		{
			$id=$_POST['id'];
			if($this->_model->update()){
				$LastOne=$this->_model->findLastOne($id);	
				$this->savead($LastOne[0]);				
			 	$this->_redirect->succ('?a=ad', '广告名称修改成功！');
			}else{
				$this->_redirect->error('广告名称修改失败！');
			}
		}
		if (isset($_GET['id'])) {
			$this->_tpl->assign('OneAd', $this->_model->findOne());
			$this->_tpl->display(SMARTY_ADMIN.'ad/update.tpl');
		}
	}
	//执行生成广告js代码
	public function savead($_value){
		//图片广告
		$_js="var sidebar = [];";
		if($_value->type==1){
			$_js .= "sidebar[1] = {\r\n";
			$_js .= 	"\t'title' : '$_value->name',\r\n";
			$_js .= 	"\t'pic' : '$_value->site_logo',\r\n";
			$_js .= 	"\t'link' : '$_value->url'\r\n";
			$_js .= "};\r\n";	
			$_js .= "document.write('<a href=\"'+sidebar[1].link+'\" target=\"_blank\" title=\"'+sidebar[1].title+'\"><img border=\"0\" src=\"'+sidebar[1].pic+'\"></a>');";
			
			
		}
		else{
			$_js .= "sidebar[1] = {\r\n";
			$_js .= 	"\t'title' : '$_value->name',\r\n";	
			$_js .= 	"\t'link' : '$_value->url'\r\n";
			$_js .= "};\r\n";	
			$_js .= "document.write('<a href=\"'+sidebar[1].link+'\" target=\"_blank\" title=\"'+sidebar[1].title+'\">'+sidebar[1].title+'</a>');";	
		}
		//生成代码，保存文件
		if (!file_put_contents('./data/adjs/'.$_value->adindex.'.js', $_js)) {
			$this->_redirect->error('?a=ad', '广告新增成功,生成js失败，请修改广告重新生成');
		}
		
	}
	
}
?>