<?php defined('SYSPATH') OR die('No Direct Script Access');

Class Controller_Todo extends Controller_Website
{
    function action_index()
    {
		$plato_server = Kohana::config("site.plato_server");
		//$fid = file_get_contents($plato_server . "get_user"); //, "r");
		//$fid = file_get_contents("http://localhost/plato/api/get_user"); //, "r");
		//$user_id = stream_get_line($fid, 99999);
		
		$user_id = session::instance()->get("user_id");
		
		$tasks = ORM::factory('task')->where("user_id","=",$user_id)->find_all();
		
        $view = View::factory('tasks');
		$view->tasks = $tasks;
		$this->auto_render = false;
		$this->request->response= $view;
    }
	function action_by_me()
    {
		$plato_server = Kohana::config("site.plato_server");
		
		$user_id = plato::get_user();
		$tasks = ORM::factory('task')
						->where("assigner_id","=",$user_id)
						->where("user_id","!=",$user_id)
						->find_all();
        $view = View::factory('list');
		$view->tasks = $tasks;
		$this->template->content= $view;
    }
	
	function action_add($id=NULL)
	{
		$user = plato::get_user();
		if(Arr::get($_POST, 'save'))
		{
			$task = ORM::factory('task');
			$task->title = $_POST['title'];
			$task->description = $_POST['description'];
			$task->category_id = 1;
			$task->user_id = $user;
			$task->parent_id = $id;
			if($user_id=Arr::get($_POST, 'user_id'))
			{
				if($task->user_id != $user_id)//if its assigned to somebody else
					$task->parent_id = NULL;
				$task->user_id = $user_id;
			}
			$task->assigner_id = $user;
			$task->save();
			gen::re_back();
		}
		$view = View::factory('add_task');
		$roles = plato::get_user_roles();
		$admin_role_exists = in_array("admin",$roles);
		
		/* if($user->has("roles", ORM::factory("role",2)))
		{
			$view->users = ORM::factory("user")->find_all()->as_array("id","username");
		} */
		$this->template->content = $view; 
	}
	function action_done($id, $status=1)
	{
		$this->auto_render = false;
		$task = ORM::factory('task',$id);
		if(!$task->loaded())
		{
			echo 0;
			return;
		}
		$task->status = $status;
		$task->save();
		echo "1";
	}
	
	function action_edit($id)
	{
		$task = ORM::factory('task',$id);
		if(Arr::get($_POST, 'save'))
		{
			$task->title = $_POST['title'];
			$task->description = $_POST['description'];
			$task->save();
			gen::re_back();
		}
		$this->template->content = View::factory('edit_task');
		$this->template->content->task = $task;
	}
	
	function action_delete($id)
	{
		$this->auto_render = false;
		ORM::factory('task')->delete($id);
		gen::re_back();
	}
}