<?php

class SiteController extends Controller {

    public function accessRules() {
        return array(
            array('allow',
                'actions' => array('index', 'error', 'logout'),
                'users' => array('*'),
            ),
            array('deny',
                'roles' => array('banned'),
                'deniedCallback' => array(Yii::app()->controller, 'redirectToHome'),
            ),
            array('allow',
                'actions' => array('registration', 'login', 'start', 'remind', 'remindPassword'),
                'users' => array('?'),
            ),
            array('allow',
                'actions' => array('online', 'returnToBattle', 'support', 'ajaxReadNews', 'actions', 'bonus'),
                'users' => array('@'),
            ),
            array('deny',
                'users' => array('*'),
                'deniedCallback' => array(Yii::app()->controller, 'redirectToHome'),
            )
        );
    }

    public function actionRemind() {
        $model = new RemindForm;
        if (isset($_POST['RemindForm'])) {
            $model->attributes = $_POST['RemindForm'];
            if ($model->validate()) {
                $user = Users::model()->findByAttributes(array('login' => $model->login));
                $hash = rand(1111, 9999) . $user->email . rand(1111, 9999);
                $user->email_remind = md5(md5($hash));
                $user->email_remind_time = time();
                if (!$user->save(false)) {
                    throw new CHttpException(500, Yii::t('layout', 'Ошибка при сохранении пользователя!'));
                }
                $email = Yii::app()->email;
                $email->to = $user->email;
                $email->from = 'Битва за Средиземье <support@mland.mobi>';
                $email->subject = 'Восстановление пароля';
                $email->message = 'Вы получили данное сообщение так как запрашивали восстановление пароля в мобильной'
                        . ' онлайн игре "Битва за Средиземье" для персонажа под логином <i>' . $user->login . '</i><br /><br />'
                        . 'Если же Вы не запрашивали восстановление пароля - просто проигнорируйте письмо.<br /><br />'
                        . 'Если же именно Вы запрашивали восстановление пароля, тогда перейдите по следующей ссылке для смены пароля:<br /><br />'
                        . 'http://mland.mobi/remindPassword/?code=' . $user->email_remind . '<br /><br />'
                        . 'И следуйте инструкциям указанным на странице.<br /><br />'
                        . 'Приятной игры. С уважением команда mland.mobi';
                $email->send();
                Yii::app()->user->setFlash('info', 'Сообщение с инструкциями отправленно на Ваш Email!');
                $this->redirect('/');
                Yii::app()->end();
            }
        }
        $this->render('remind', array('model' => $model));
    }

    public function actionRemindPassword($code) {
        $user = Users::model()->findByAttributes(array('email_remind' => $code));
        if (!$user) {
            throw new CHttpException(404, Yii::t('layout', 'Данный код не верный!'));
        } else {
            $model = new OptionsForm();
            $model->setScenario('changePassword');
            if (isset($_POST['OptionsForm'])) {
                $model->attributes = $_POST['OptionsForm'];
                if ($model->validate()) {
                    $user->password = md5(md5($model->password_new));
                    $user->email_remind = $user->email_remind_time = null;
                    if (!$user->save(false)) {
                        throw new CHttpException(500, Yii::t('layout', 'Ошибка при сохранении пользователя!'));
                    }
                    Yii::app()->user->setFlash('info', 'Ваш новый пароль установлен.');
                    $this->redirect('/login/');
                    Yii::app()->end();
                }
            }
        }
        $this->render('remindPassword', array('model' => $model));
    }

    public function actionReturnToBattle($type = null) {
        if ($type == 1) {
            $this->redirect('/battles/');
        } elseif ($type == 2) {
            $this->redirect('/dungeons/');
        } elseif ($type == 3) {
            $this->redirect('/training/');
        } else {
            $this->redirect('/site/');
        }
    }

    public function actionActions() {
        $criteria = new CDbCriteria();
        $criteria->addCondition('t.time >= ' . time());
        $models = Actions::model()->findAll($criteria);
        $this->render('actions', ['models' => $models]);
    }

    public function actionBonus() {
        $user = Users::findUser();
        if (isset($_GET['action']) && !UserDaily::check('bonus') && $user->level >= 15) {
            $bonuses = [
                'money' => [
                    'value' => 10,
                    'name' => '10 серебра'
                ],
                'xp' => [
                    'name' => '5% личного опыта'
                ],
                'item' => [
                    'value' => 10,
                    'name' => 'Добротная вещь'
                ],
                'iron' => [
                    'value' => 150,
                    'name' => '150 железа'
                ],
                'bottles' => [
                    'value' => 5,
                    'name' => '5 эликсиров'
                ],
            ];
            $bonus = array_rand($bonuses, 1);
            if ($bonus == 'item') {
                $id_set = rand(2, 5);
                $item = ShopItems::getRandomItemInDungeons($id_set);
                $drop = ShopItems::getNewItem($item->id_item, 3, Yii::app()->user->id, false, false, true);
            } elseif ($bonus == 'xp') {
                $min = BattleHelper::maxXP($user->level - 1);
                $max = BattleHelper::maxXP($user->level);
                $xp = round((($max - $min) / 100) * 5);
                $user->xp += $xp;
                if ($user->xp >= $max && $user->level < 34) {
                    $user->level += 1;
                    $params = Users::calcParam($user->id_user);
                    $user->health_now = $params->totalHealth * 2;
                    $user->energy_now = $params->totalEnergy * 2;
                }
            } else {
                $user->$bonus += $bonuses[$bonus]['value'];
            }
            if (!$user->save(false)) {
                throw new CHttpException(500, Yii::t('layout', 'Ошибка при сохранении данных пользователя!'));
            }
            UserDaily::addToDaily('bonus');
            Yii::app()->user->setFlash('info', 'Вы выиграли "' . $bonuses[$bonus]['name'] . '"');
            $this->redirect('/bonus/');
            Yii::app()->end();
        }
        $this->render('bonus', ['user' => $user]);
    }

    public function actionIndex() {
        if (Yii::app()->user->role == 'guest') {
            if (Yii::app()->request->getParam('user')) {
                $_SESSION['id_ref'] = (int) Yii::app()->request->getParam('user');
            }
            $this->render('main');
        } else {
            $user = Users::findUser();
            $columns = array('dungeons', 'logs', 'dungeon_id', 'battle_id', 'battle_type', 'battle_target', 'ip', 'ua');
            $user->dungeons = null;
            $user->logs = null;
            if ($user->battle_type == 2) {
                $dungeon = BattlesDungeons::model()->findByPk($user->battle_id);
                if ($dungeon) {
                    $users_ids = CHtml::listData($dungeon->users, 'id_user', 'id_user');
                    $log = new BattleLog();
                    $log->battle_type = $user->battle_type;
                    $log->battle_id = $user->battle_id;
                    $log->id_user = $user->id_user;
                    $log->type = 8;
                    $log->info = 2;
                    $log->users = $users_ids;
                    $log->save(false);
                }
            }
            $user->dungeon_id = null;
            $user->battle_id = null;
            $user->battle_type = null;
            $user->battle_target = null;
            $user->ip = ip2long(Yii::app()->request->getUserHostAddress());
            $user->ua = Yii::app()->request->getUserAgent();
            if (!$user->health_now) {
                $params = Users::calcParam($user->id_user);
                $user->health_now = $params->totalHealth;
                $user->energy_now = $params->totalEnergy;
                $columns[] = 'health_now';
                $columns[] = 'energy_now';
            }
            if (!$user->update($columns)) {
                throw new CHttpException(500, Yii::t('layout', 'Ошибка при сохранении пользователя!'));
            }
            $criteria = new CDbCriteria();
            $criteria->select = 'short_name_action';
            $criteria->addCondition('t.time >= ' . time());
            $actions = Actions::model()->findAll($criteria);
            $this->render('index', ['actions' => $actions, 'user' => $user]);
        }
    }

    public function actionStart($side) {
        $side = ($side < 1 || $side > 2 ? 1 : $side);
        if (isset($_GET['class'])) {
            $class = ((int) $_GET['class'] < 1 || (int) $_GET['class'] > 2 ? 1 : (int) $_GET['class']);
            $last = Users::model()->count();
            $user = new Users();
            $user->id_role = 8;
            $user->side = $side;
            $user->class = $class;
            $user->avatar = 1;
            $user->iron = 50;
            $user->money = 5;
            $user->login = ($class < 2 ? 'Воин' : 'Медик') . ' ' . ($side < 2 ? 'Краллов' : 'Элийцев') . ' ' . $last;
            if (isset($_SERVER['HTTP_X_HOST']) && isset($_SESSION['pumpit_id'])) {
                $user->pumpit_id = $_SESSION['pumpit_id'];
                $password = md5('pumpit' . $_SESSION['pumpit_id']);
            } else {
                $password = md5(rand(111111, 999999));
            }
            $user->password = $password;
            if (isset($_SESSION['id_ref'])) {
                $user->id_ref = (int) $_SESSION['id_ref'];
            }
            if ($user->save(false)) {
                $items = ShopItems::findAllBySet(1);
                foreach ($items as $item) {
                    ShopItems::getNewItem($item->id_item, 1, $user->id_user, false, true);
                }
                $health = Users::calcParam($user->id_user, 'health');
                $energy = Users::calcParam($user->id_user, 'energy');
                $user->health_now = round($health * 2);
                $user->energy_now = round($energy * 2);
                if (!$user->save(false)) {
                    throw new CHttpException(500, Yii::t('layout', 'Ошибка при сохранении бота!'));
                }
                $login = new LoginForm;
                $login->login = $user->login;
                $login->password = $password;
                $login->login();
            }
            $this->redirect('/training/');
        }
        $this->render('start', array('side' => $side));
    }

    public function actionLogin() {
        $model = new LoginForm;
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'login-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
        if (isset($_POST['LoginForm'])) {
            $model->attributes = $_POST['LoginForm'];
            if ($model->validate() && $model->login()) {
                $this->redirect('/');
                Yii::app()->end();
            }
        }
        $this->render('login', array('model' => $model));
    }

    public function actionOnline() {
        $model = new Users('online');
        $this->render('online', array('model' => $model));
    }

    public function actionError() {
        if ($error = Yii::app()->errorHandler->error) {
            if (Yii::app()->request->isAjaxRequest)
                echo $error['message'];
            else
                $this->render('error', $error);
        }
    }

    public function actionLogout() {
        Yii::app()->user->logout();
        if (isset($_SERVER['HTTP_X_HOST'])) {
            // Если пользователь хочет вернуться в Pumpit
            $pumpit = new Pumpit(Yii::app()->params->pumpit_params);
            $p_sid = (isset($_SESSION['p_sid']) ? $_SESSION['p_sid'] : '');
            $url = $pumpit->doPumpitBack($p_sid);
            $this->redirect($url);
            Yii::app()->end();
        }
        $this->redirect(Yii::app()->homeUrl);
    }

    public function actionRegistration() {
        $model = new RegistrationForm;
        if (Users::countUsers(1, null) > Users::countUsers(2, null))
            $model->side = 2;
        else
            $model->side = 1;
        if (Users::countUsers($model->side, 1) > Users::countUsers($model->side, 2))
            $model->class = 2;
        else
            $model->class = 1;
        if (isset($_POST['RegistrationForm'])) {
            $model->attributes = $_POST['RegistrationForm'];
            if (!in_array($model->side, array(1, 2)))
                $model->side = rand(1, 2);
            if (!in_array($model->class, array(1, 2)))
                $model->class = rand(1, 2);
            if ($model->validate()) {
                $user = new Users();
                $user->attributes = $model->attributes;
                $user->id_role = 1;
                if ($user->side == 1 && $user->sex == 0)
                    $user->avatar = 1;
                elseif ($user->side == 2 && $user->sex == 0)
                    $user->avatar = 2;
                elseif ($user->side == 1 && $user->sex == 1)
                    $user->avatar = 3;
                else
                    $user->avatar = 4;
                if ($user->save(false)) {
                    $items = ShopItems::findAllBySet(1);
                    foreach ($items as $item) {
                        ShopItems::getNewItem($item->id_item, 1, $user->id_user, false, true, true);
                    }
                    $health = Users::calcParam($user->id_user, 'health');
                    $energy = Users::calcParam($user->id_user, 'energy');
                    $user->health_now = round($health * 2);
                    $user->energy_now = round($energy * 2);
                    if (!$user->save(false)) {
                        throw new CHttpException(500, Yii::t('layout', 'Ошибка при сохранении бота!'));
                    }
                    $login = new LoginForm;
                    $login->login = $model->login;
                    $login->password = $model->password;
                    if ($login->login()) {
                        $this->redirect(Yii::app()->user->returnUrl);
                    }
                }
                $this->redirect('/');
            }
        }
        $this->render('registration', array('model' => $model));
    }

    public function actionSupport() {
        $model = new SupportMessages();
        if (isset($_POST['SupportMessages'])) {
            $model->attributes = $_POST['SupportMessages'];
            if ($model->validate()) {
                if (!$model->save(false)) {
                    throw new CHttpException(500, Yii::t('layout', 'Ошибка при создании запроса!'));
                }
                Yii::app()->user->setFlash('info', 'Ваш запрос отправлен. Ожидайте ответ');
                $this->redirect('/');
                Yii::app()->end();
            }
        }
        $this->render('support', array(
            'model' => $model,
        ));
    }

}
