<?php
ApplicationSettings::RegisterDefaultSetting("blog", "posts_per_page", 10);

class Blog {
	public function Index($params){
		if (!isset($params['page']) || $params['page']<1)
			$params['page']=1;
		
		$count=ApplicationSettings::GetSetting("blog", "posts_per_page");
		$offset=($params['page']-1)*$count;
		$total=BlogPost::GetCount();
		$maxPages=$total/$count;
		
		$posts=BlogPost::GetLatest($count,$offset);
		
		$vars=array(
			"posts"=>$posts,
			"page"=>$params['page'],
			"maxPages"=>$maxPages
		);
		return new View("Blog/index.view",$vars);
	}
	
	public function Page($params) {
		return $this->Index(array("page"=>$params[0]));
	}
	
	public function Create($params){
		Breadcrumbs::Add("Create", "/blog/create");
		$post=new BlogPost();
		if (isset($params['title']))
			$post->PostTitle=$params['title'];
		if (isset($params['draft']))
			$post->PostDraft=$params['draft'];
		if ($post->PostTitle!="" && $post->PostDraft!=""){
			$post->Save();
			header("location:/blog/manage");
			return;
		}
		return new View("Blog/create.view",array("post"=>$post));
	}
	
	public function Manage($params){
		Breadcrumbs::Add("Manage", "/blog/manage");
		if (isset($params['formSubmitted']) && $params['formSubmitted']==="yes"){
			if (isset($params['delete'])){
				$post=new BlogPost($params['delete']);
				$post->Delete();
			}
			if (isset($params['publish'])){
				$post=new BlogPost($params['publish']);
				$post->Publish();
			}
			header("location:/blog/manage");
			return;
		}
		
		$posts=BlogPost::GetAll();
		return new View("Blog/manage.view",array("posts"=>$posts));
	}
	
	public function Edit($params) {
		$post=new BlogPost($params[0]);
		Breadcrumbs::Add("Edit", "");
		if(isset($params['title']) && isset($params['draft'])){
			$post->PostTitle=$params['title'];
			$post->PostDraft=$params['draft'];
			$post->Save();
		}
		return new View("Blog/create.view",array("post"=>$post));
	}
	
	public function View($params){
		if (!isset($params[0])){
			header("location:/blog");
			return;
		}
		$post=new BlogPost($params[0]);
		if (!$post->PostId)
			return new View("E404/index.view");
		Breadcrumbs::Add(htmlspecialchars($post->PostTitle), "");
		return new View("Blog/view.view",array("content"=>$post->PostContent,"timestamp"=>$post->PostTimestamp));
	}
	
	public function ViewDraft($params){
		if (!isset($params[0])){
			header("location:/blog/manage");
			return;
		}
		$post=new BlogPost($params[0]);
		if (!$post->PostId)
			return new View("E404/index.view");
		Breadcrumbs::Add("Draft", "");
		Breadcrumbs::Add(htmlspecialchars($post->PostTitle), "");
		return new View("Blog/view.view",array("content"=>$post->PostDraft,"timestamp"=>$post->PostTimestamp));
	}
}
