<?php 
class Myad_Controller extends Base_Controller{
	function __construct(){
		parent::__construct();
		$this->myAd	=	new Myad_Model();
	}
	function index(){
		$this->view			=	new View("myad/list");
		$this->view->myads	=	$this->myAd->getAds()->result_array();
		$this->display();
	}
	function add(){
		if($this->input->post()){
			$myad			=	$this->input->post("myad");
			$myad['time']	=	time();
			$adid			=	$this->myAd->addMyad($myad);
			if($myad['code']){
				$code		=	explode("\n",$myad['code']);
				$script		=	'';
				foreach ($code as $c){
					$script.="document.writeln(\"".preg_replace("#[\"]{1,1}#","\\\"",$c)."\");\r\n";
				}
			}
			file_put_contents("data/cache/ad$adid.js",$script);
			unset($_POST);
			$this->index();
		}
		else{
			$this->view		=	new View("myad/form");
			$this->main->formAction="myad/add";
			$this->main->is_validator=true;
			$this->display();
		}
	}
	function delete($adid=0){
		if($this->input->post()){
			$myadids	=	$this->input->post("select_id");
		}
		else{
			$myadids[]	=	$adid;
		}
		foreach ($myadids as $id){
			@unlink("data/cache/ad$id.js");
		}
		$this->myAd->delete($myadids);
		unset($_POST);
		$this->index();
	}
	function edit($myid=false){
		if($this->input->post()){
			$id		=	$this->input->post("myadid");
			$myad	=	$this->input->post("myad");
			$code		=	explode("\n",$myad['code']);
			$script		=	'';
			foreach ($code as $c){
				$script.="document.writeln(\"".preg_replace("#[\"]{1,1}#","\\\"",$c)."\");\r\n";
			}
			file_put_contents("data/cache/ad$id.js",$script);
			$this->myAd->updateMyad($id,$myad);
			unset($_POST);
			$this->index();
		}
		else{
			$this->view			=	new View("myad/form");
			$this->view->myads	=	$this->myAd->getAds($myid)->current();
			$this->main->formAction	=	"myad/edit";
			$this->display();
		}

	}
}



