<?php

class ContactController extends RestController
{
	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionShow($id)
	{
		$model= Contact::model()->findByPk($id);
		$this->sendResponse(200,CJSON::encode($model));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$data = CJSON::decode(file_get_contents('php://input'));

		$model = new Contact();
		if (isset($data['firstname']))
			$model->lastname = $data['lastname']; 
		if (isset($data['content']))
			$model->email = $data['email']; 
		
		if (!$model->save()) {
			$errors = array();
			foreach ($model->getErrors() as $e) $errors = array_merge($errors, $e);
			$this->sendResponse(500, implode("<br />", $errors));
		} 
		
		$this->sendResponse(200);
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionEdit($id)
	{
		$data = CJSON::decode(file_get_contents('php://input'));

		$model = Contact::model()->findByPk($id);
		
		$model->firstname   = $data['firstname'];
		$model->lastname = $data['lastname'];
		$model->email = $data['email'];

		if (!$model->save()) {
			$errors = array();
			foreach ($model->getErrors() as $e) $errors = array_merge($errors, $e);
			$this->sendResponse(500, implode("<br />", $errors));
		} 
		
		$this->sendResponse(200);
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$model = Contact::model()->findByPk($id);

		if (!$model->delete() && count($model->getErrors())) {
			$errors = array();
			foreach ($model->getErrors() as $e) {
				$errors = array_merge($errors, $e);
			}
			$this->sendResponse(500, implode("<br />", $errors));
		} 
		
		$this->sendResponse(200);
	}

	/**
	 * Lists all models.
	 */
	public function actionList()
	{
		$models=Contact::model()->findAll();
		$this->sendResponse(200,CJSON::encode($models));
	}

}