<?php

class SiteController extends Controller {

	/**
	 * Declares class-based actions.
	 */
	public function actions() {
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			),
			// page action renders "static" pages stored under 'protected/views/site/pages'
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page' => array(
				'class' => 'CViewAction',
			),
		);
	}

	/**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionIndex() {
		// renders the view file 'protected/views/site/index.php'
		// using the default layout 'protected/views/layouts/main.php'
		$this->render('index');
	}

	public function actionPageError() {
		$errorRecord = new ErrorRecord();
		if (isset($_POST['PageError'])) {
			$errorRecord->attributes = $_POST['PageError'];
			$errorRecord->linenumber = (int) $errorRecord->linenumber;
			$errorRecord->createdate = date('Y-m-d H:i:s');
			if ($errorRecord->validate()) {
				$errorRecord->save();
			}
			Yii::log($errorRecord->url . ':'. $errorRecord->linenumber . "\n" .  $errorRecord->message, CLogger::LEVEL_ERROR);
		}
		$this->renderPartial('ok');
	}

	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError() {
		if ($error = Yii::app()->errorHandler->error) {
			if (Yii::app()->request->isAjaxRequest)
				echo $error['message'];
			else
				$this->render('error', $error);
		}
	}

	/**
	 * Displays the contact page
	 */
	public function actionContact() {
		$model = new ContactForm();
		if (isset($_POST['ContactForm'])) {
			$model->attributes = $_POST['ContactForm'];
			if ($model->validate()) {
				$headers = "From: {$model->email}\r\nReply-To: {$model->email}\r\nContent-Type: text/plain; charset=UTF-8";
				mail(Yii::app()->params['adminEmail'], $model->subject, $model->body, $headers);
				Yii::app()->user->setFlash('contact', 'Aitäh kontakteerumast. Vastame esimesel võimalusel.');
				$this->refresh();
			}
		}
		$this->render('contact', array('model' => $model));
	}

	/**
	 * Displays the login page
	 */
	public function actionLogin() {
		$model = new LoginForm();
		$source = Yii::app()->request->getParam('source');
		if (isset($_POST['LoginForm']['source'])) {
			$source = $_POST['LoginForm']['source'];
		}
		if ($source) {
			$model->source = $source;
			// validate user input and redirect to the previous page if valid
			if ($model->validate()) {
				$this->redirect(array('keyWizard/index', 'source' => $source ));

			}
		}

		// display the login form
		$data = array('model' => $model);
		$this->render('login', $data);
	}

	/**
	 * Logs out the current user and redirect to homepage.
	 */
	public function actionLogout() {
		Yii::app()->user->logout();
		$this->redirect(Yii::app()->homeUrl);
	}

}
