<?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
   
            // 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 actionLogin() {
        $form = new Users();
        $form->scenario = 'login';

        // Проверяем является ли пользователь гостем
        // ведь если он уже зарегистрирован - формы он не должен увидеть.
        if (!Yii::app()->user->isGuest) {
            $this->redirect(Yii::app()->homeUrl);
        } else {
            if (!empty($_POST['Users'])) {
                $form->attributes = $_POST['Users'];
                // Проверяем правильность данных
                if ($form->validate('login')) {
                    // если всё ок - кидаем на главную страницу
                    $this->redirect(Yii::app()->homeUrl);
                }
            }
            $this->render('login', array('form' => $form));
        }
    }

    public function actionIndex() {
        if (!Yii::app()->user->isGuest) {
            $this->redirect(Yii::app()->homeUrl);
        }
        $this->render('index');
    }

    /**
     * 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()) {
                $name = '=?UTF-8?B?' . base64_encode($model->name) . '?=';
                $subject = '=?UTF-8?B?' . base64_encode($model->subject) . '?=';
                $headers = "From: $name <{$model->email}>\r\n" .
                        "Reply-To: {$model->email}\r\n" .
                        "MIME-Version: 1.0\r\n" .
                        "Content-Type: text/plain; charset=UTF-8";

                mail(Yii::app()->params['adminEmail'], $subject, $model->body, $headers);
                Yii::app()->user->setFlash('contact', 'Thank you for contacting us. We will respond to you as soon as possible.');
                $this->refresh();
            }
        }
        $this->render('contact', array('model' => $model));
    }

    /**
     * Displays the login page
     */

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

    
     public function actionRegistration() {
        $form = new Users();
        $form->scenario = 'reg';
        if (!Yii::app()->user->isGuest) {
            $this->redirect(Yii::app()->homeUrl);
         } else {
            if (!empty($_POST['Users'])) {
                $form->attributes = $_POST['Users'];
                if ($form->validate('/site/registration')) {
                    if ($form->model()->count("login = :login", array(':login' => $form->login))) {
                        $form->addError('login', 'Имя уже занято');
                        $this->render("/site/registration", array('form' => $form));
                    } else {
                        if ($form->side != 1 && $form->side != 2) $form->side = 1;
                        $form->save();
                        $identity=new UserIdentity($_POST['Users']['login'], $_POST['Users']['password']);
                        $identity->authenticate();
                        Yii::app()->user->login($identity);
                        $this->redirect(array('main/index'));
                    }
                } else {
                    $this->render("registration", array('form' => $form));
                }
            } else {
                $this->render("registration", array('form' => $form, 'allert'=>'Необходимо заполнить все поля'));
            }
        }
    }
    
}
