<?php
class DungeonsController extends Controller {
    public function accessRules() {
        return array(
            array('deny',
                'roles' => array('banned'),
                'deniedCallback' => array(Yii::app()->controller, 'redirectToHome'),
            ),
            array('allow',
                'actions' => array('index', 'battle', 'damageLastTarget', 'damageRandomEnemy', 'healLastTarget', 'healRandomFriend', 'healSelf', 'usePotion', 'order', 'startCombat', 'view', 'useAbility'),
                'users' => array('@'),
            ),
            array('deny',
                'users' => array('*'),
                'deniedCallback' => array(Yii::app()->controller, 'redirectToHome'),
            )
        );
    }
    
    public function actionIndex($type = null) {
        $user = Users::findUser();
        if (!$user->battle_id) {
            if (!$type) {
                $dungeons = DungeonsList::model()->findAllByAttributes(['type'=>1], ['condition' => 'id_dungeon < 3']);
                $this->render('index', array(
                    'dungeons' => $dungeons,
                    'user' => $user,
                )); 
            }
            else {
                $dungeons = DungeonsList::model()->findAllByAttributes(['type'=>2], ['condition' => 'id_dungeon < 7']);
                $this->render('guild_index', array(
                    'dungeons' => $dungeons,
                    'user' => $user,
                ));
            }
        } elseif ($user->battle_type == 2 && isset($user->idDungeon)) {
            $id = $user->idDungeon->id_dungeon;
            if ($user->idDungeon->time_end > 0) {
                $user->battle_id = null;
                $user->battle_type = null;
                $user->battle_target = null;
                if (!$user->save(false)) {
                    throw new CHttpException(500, Yii::t('layout', 'Ошибка при сохранении данных пользователя!'));
                }
                $this->redirect($this->createUrl('dungeons/view', array('id'=>$id)));
                Yii::app()->end();
            }
            else {
                $this->redirect($this->createUrl('dungeons/battle'));
                Yii::app()->end();
            }
        } else {
            $user->battle_id = null;
            $user->battle_type = null;
            $user->battle_target = null;
            if (!$user->save(false)) {
                throw new CHttpException(500, Yii::t('layout', 'Ошибка при сохранении данных пользователя!'));
            }
            $this->redirect($this->createUrl('dungeons/index'));
            Yii::app()->end();
        }
    }

    public function actionBattle() {
        $user = Users::findUser();
        if ($user->battle_type == 2 && isset($user->idDungeon)) {
            $id = $user->idDungeon->id_dungeon;
            if ($user->idDungeon->time_end > 0) {
				Users::model()->updateByPk($user->id_user, ['battle_type' => null, 'battle_id' => null, 'battle_target' => null]);
                $this->redirect($this->createUrl('dungeons/view', array('id'=>$id)));
                Yii::app()->end();
            }
            else {
                if ($user->dungeon_id > 5) {
                    $criteria = new CDbCriteria;
                    $criteria->compare('type', $user->guild_id);
                    $criteria->addCondition('`time` > '.(time()-60*60*5));
                    $criteria->order = '`time` DESC';
                    $criteria->limit = 2;
                    $chat = Chat::model()->findAll($criteria);
                    $message = new Chat();
                    if (isset($_POST['Chat']) && $user->guild_id) {
                        $message->message = $_POST['Chat']['message'];
                        if ($message->validate()) {
                            $message->type = $user->guild_id;
                            $message->save(false);
                            $this->redirect($this->createUrl('dungeons/view', array('id'=>$id)));
                            Yii::app()->end();
                         }
                    }
                }
                else {
                    $chat = array();
                    $message = array();
                }
				$abilities = UsersAbilities::model()->findAllByAttributes(['id_user' => Yii::app()->user->id], ['condition' => 'chosen > 0']);
                $this->render('battle', array(
                    'battle' => $user->idDungeon,
                    'user' => $user,
                    'chat' => $chat,
                    'message' => $message,
					'abilities' => $abilities
                ));
            }
        } else {
			Users::model()->updateByPk($user->id_user, ['battle_type' => null, 'battle_id' => null, 'battle_target' => null]);
            $this->redirect($this->createUrl('dungeons/index'));
            Yii::app()->end();
        }
    }
    
    public function actionView($id) {
        $user = Users::findUser();
        if ($user->battle_type == 2 && isset($user->idDungeon)) {
            if ($user->idDungeon->time_end == 0) {
                $this->redirect($this->createUrl('dungeons/battle'));
                Yii::app()->end();
            }
            else {
                $user->battle_id = null;
                $user->battle_type = null;
                $user->battle_target = null;
				Users::model()->updateByPk($user->id_user, ['battle_type' => null, 'battle_id' => null, 'battle_target' => null]);
            }
        }
        $model = DungeonsList::model()->findByPk($id);
        if ($id > 5 && !$user->guild_id || ($id>4 && $id<6)) {
            Yii::app()->user->setFlash('error', 'Вы не состоите в гильдии');
            $this->redirect($this->createUrl('dungeons/index'));
            Yii::app()->end();
        }
        if (!$model || $model->level > ($id < 6 ? Yii::app()->user->level : $user->idGuild->level)) {
            throw new CHttpException(404, Yii::t('layout', 'Страница не найдена!'));
        }
        $history = array();
        $history = UserDungeons::model()->findByPk(array('id_user'=>Yii::app()->user->id, 'id_dungeon'=>$id));
        if ($model->type == 1) {
            $users_array = CHtml::listData($model->users, 'id_user', 'id_user');
            $this->render('view', array(
                'model' => $model,
                'user' => $user,
                'users_array' => $users_array,
                'history' => $history
            )); 
        }
        else {
            $user->dungeons = $id;
            if (!$user->save(false)) {
                throw new CHttpException(500, Yii::t('layout', 'Ошибка при сохранении данных пользователя!'));
            }
            $criteria = new CDbCriteria;
            $criteria->compare('type', $user->guild_id);
            $criteria->addCondition('`time` > '.(time()-60*60*5));
            $criteria->order = '`time` DESC';
            $criteria->limit = 5;
            $chat = Chat::model()->findAll($criteria);
            $message = new Chat();
            if (isset($_POST['Chat']) && $user->guild_id) {
                $message->message = $_POST['Chat']['message'];
                if ($message->validate()) {
                    $message->type = $user->guild_id;
                    $message->save(false);
                    $this->redirect($this->createUrl('dungeons/view', array('id'=>$id)));
                    Yii::app()->end();
                 }
            }
            $members = DungeonsWaiters::findUsersInDungeon($id, null, $user->guild_id);
            $users_count['warriors'] = $users_count['healers'] = 0;
            foreach ($members as $member) {
                if ($member->class == 1)
                    $users_count['warriors']++;
                else
                    $users_count['healers']++;
            }
            $this->render('guildview', array(
                'model' => $model,
                'user' => $user,
                'members' => $members,
                'users_count' => $users_count,
                'history' => $history,
                'chat' => $chat,
                'message' => $message,
            )); 
        }
    }

    public function actionOrder($id) {
        $user = Users::findUser();
        if (!$user->dungeon_id) {
            $model = DungeonsList::model()->findByPk($id);
            $history = UserDungeons::model()->findByPk(array('id_user'=>Yii::app()->user->id, 'id_dungeon'=>$id));
            if (!$model || $model->level > Yii::app()->user->level || ($history && $history->time_last>time())) {
                throw new CHttpException(404, Yii::t('layout', 'Страница не найдена!'));
            }
            $users_array = CHtml::listData($model->users, 'id_user', 'id_user');

            if (in_array(Yii::app()->user->id, $users_array)) {
                $user->dungeons = null;
                if (!$user->save(false)) {
                    throw new CHttpException(500, Yii::t('layout', 'Ошибка при сохранении данных пользователя!'));
                }
                $this->redirect($this->createUrl('dungeons/view', array('id'=>$id)));
                Yii::app()->end();
            } else {
                $user->dungeons = $id;
                if (!$user->save(false)) {
                    throw new CHttpException(500, Yii::t('layout', 'Ошибка при сохранении данных пользователя!'));
                }
                $model = DungeonsList::model()->findByPk($id);
                $warriors = count($model->warriors);
                $healers = count($model->healers);
                if ($warriors >= $model->warriors_need && $healers >= $model->healers_need || $warriors >= $model->all_need) {
                    //Если игроки набрались сохраняем все и вызываем новую модель
                    $battle = new BattlesDungeons();
                    $battle->id_dungeon = $id;
                    if (!$battle->save(false)) {
                        throw new CHttpException(500, Yii::t('layout', 'Ошибка при создании боя!'));
                    }
                    //началось
                    if ($warriors >= $model->warriors_need && $healers >= $model->healers_need) {
                        //Сначала отбираем воинов
                        $criteria = new CDbCriteria();
                        $criteria->with = array('dungeons');
                        $criteria->together = true;
                        $criteria->condition = 't.last_visit > ' . (time() - 60 * 5);
                        $criteria->compare('dungeons.id_dungeon', $id);
                        $criteria->order = 'RAND()';
                        $criteria->compare('class', 1);
                        $criteria->limit = $model->warriors_need;
                        $warriors = Users::model()->findAll($criteria);
                        foreach ($warriors as $warrior) {
                            $warrior->participation = 0;
                            $warrior->battle_type = 2;
                            $warrior->dungeon_id = $id;
                            $warrior->battle_id = $battle->id_battle;
                            $params = Users::calcParam($warrior->id_user);
                            if ($warrior->health_now < $params->totalHealth)
                                $warrior->health_now = $params->totalHealth;
                            if ($warrior->energy_now < $params->totalEnergy)
                                $warrior->energy_now = $params->totalEnergy;
                            $warrior->logs = null;
                            $warrior->dungeons = null;
                            if (!$warrior->save(false)) {
                                throw new CHttpException(500, Yii::t('layout', 'Ошибка при создании бота!'));
                            }
                        }
                        $criteria = new CDbCriteria();
                        $criteria->with = array('dungeons');
                        $criteria->together = true;
                        $criteria->condition = 't.last_visit > ' . (time() - 60 * 5);
                        $criteria->compare('dungeons.id_dungeon', $id);
                        $criteria->order = 'RAND()';
                        $criteria->compare('class', 2);
                        $criteria->limit = $model->healers_need;
                        $healers = Users::model()->findAll($criteria);
                        foreach ($healers as $healer) {
                            $healer->participation = 0;
                            $healer->battle_type = 2;
                            $healer->dungeon_id = $id;
                            $healer->battle_id = $battle->id_battle;
                            $params = Users::calcParam($healer->id_user);
                            if ($healer->health_now < $params->totalHealth)
                                $healer->health_now = $params->totalHealth;
                            if ($healer->energy_now < $params->totalEnergy)
                                $healer->energy_now = $params->totalEnergy;
                            $healer->logs = null;
                            $healer->dungeons = null;
                            if (!$healer->save(false)) {
                                throw new CHttpException(500, Yii::t('layout', 'Ошибка при создании бота!'));
                            }
                        }
                    } else {
                        $criteria = new CDbCriteria();
                        $criteria->with = array('dungeons');
                        $criteria->together = true;
                        $criteria->condition = 't.last_visit > ' . (time() - 60 * 5);
                        $criteria->compare('dungeons.id_dungeon', $id);
                        $criteria->order = 'RAND()';
                        $criteria->compare('class', 1);
                        $criteria->limit = $model->all_need;
                        $warriors = Users::model()->findAll($criteria);
                        foreach ($warriors as $warrior) {
                            $warrior->participation = 0;
                            $warrior->battle_type = 2;
                            $warrior->dungeon_id = $id;
                            $warrior->battle_id = $battle->id_battle;
                            $params = Users::calcParam($warrior->id_user);
                            if ($warrior->health_now < $params->totalHealth)
                                $warrior->health_now = $params->totalHealth;
                            if ($warrior->energy_now < $params->totalEnergy)
                                $warrior->energy_now = $params->totalEnergy;
                            $warrior->logs = null;
                            $warrior->dungeons = null;
                            if (!$warrior->save(false)) {
                                throw new CHttpException(500, Yii::t('layout', 'Ошибка при создании бота!'));
                            }
                        }
                    }
                    //Теперь запускаем зверей
                    $bots = DungeonsBots::findByDangeon($id);
                    foreach ($bots as $bot) {
                        $new_bot = new Users();
                        $new_bot->attributes = $bot->attributes;
                        $new_bot->health_now = $new_bot->health;
                        $new_bot->energy_now = $new_bot->energy;
                        $new_bot->password = 1;
                        $new_bot->battle_type = 2;
                        $new_bot->battle_id = $battle->id_battle;
                        $new_bot->id_role = 6;
                        if (!$new_bot->save(false)) {
                            throw new CHttpException(500, Yii::t('layout', 'Ошибка при создании бота!'));
                        }
                        ShopItems::getNewItem(2, 1, $new_bot->id_user, false, true);
                    }
                    $this->redirect($this->createUrl('dungeons/battle'));
                    Yii::app()->end();
                }
                $this->redirect($this->createUrl('dungeons/view', array('id'=>$id)));
                Yii::app()->end();
            }
        }
        $this->redirect($this->createUrl('dungeons/index'));
        Yii::app()->end();
    }
    
    public function actionStartCombat($id) {
        $user = Users::findUser();
        if (!$user->battle_type) {
            $history = UserDungeons::model()->findByPk(array('id_user'=>Yii::app()->user->id, 'id_dungeon'=>$id));
            $model = DungeonsList::model()->findByPk($id);
            if (!$model || $model->level > $user->idGuild->level || ($history && $history->time_last>time())) {
                throw new CHttpException(404, Yii::t('layout', 'Страница не найдена!'));
            }
            $battle = new BattlesDungeons();
            $battle->id_dungeon = $id;
            if (!$battle->save(false)) {
                throw new CHttpException(500, Yii::t('layout', 'Ошибка при создании боя!'));
            }
            $members = DungeonsWaiters::findUsersInDungeon($id, null, $user->guild_id);
            foreach ($members as $member) {
                $member->participation = 0;
                $member->battle_type = 2;
                $member->dungeon_id = $id;
                $member->battle_id = $battle->id_battle;
                $params = Users::calcParam($member->id_user);
                if ($member->health_now < $params->totalHealth)
                        $member->health_now = $params->totalHealth;
                if ($member->energy_now < $params->totalEnergy)
                        $member->energy_now = $params->totalEnergy;
                $member->logs = null;
                $member->dungeons = null;
                if (!$member->save(false)) {
                    throw new CHttpException(500, Yii::t('layout', 'Ошибка при создании бота!'));
                }
            }
            //Теперь запускаем зверей
            $bots = DungeonsBots::findByDangeon($id);
            foreach ($bots as $bot) {
                $new_bot = new Users();
                $new_bot->attributes = $bot->attributes;
                $params = Users::calcParam($bot->id_bot);
                $new_bot->health_now = $new_bot->health;
                $new_bot->energy_now = $new_bot->energy;
                $new_bot->password = 2;
                $new_bot->battle_type = 2;
                $new_bot->battle_id = $battle->id_battle;
                $new_bot->id_role = 6;
                if (!$new_bot->save(false)) {
                    throw new CHttpException(500, Yii::t('layout', 'Ошибка при создании бота!'));
                }
                ShopItems::getNewItem(2, 1, $new_bot->id_user, false, true);
            }
        }
        $this->redirect($this->createUrl('dungeons/battle'));
        Yii::app()->end();
    }

    public function actionUsePotion() {
        $user = Users::findUser();
        if ($user->battle_type == 2 && isset($user->idDungeon) && $user->idDungeon->time_end == 0 && $user->health_now > 0) {
            BattleHelper::usePotion($user);
            if ($user->class == 1) {
                $this->actionDamageRandomEnemy();
            }
            else {
                $this->actionHealRandomFriend();
            }
            Yii::app()->end();
        }
        $this->redirect('/dungeons/battle');
        Yii::app()->end();
    }
	
    public function actionUseAbility($chosen) {
        $user = Users::findUser();
        if ($user->battle_type != 2) {
            $this->redirect(Yii::app()->user->returnUrl);
            Yii::app()->end();
        }
        if ($user->health_now > 0) {
			if ($chosen > 0) {
				$ability = UsersAbilities::model()->findByAttributes(['id_user' => Yii::app()->user->id], ['condition' => 'chosen = '.(int)$chosen.' AND `time_cooldown` < unix_timestamp(NOW())']);
				if (!empty($ability)) {
					$ability->time_active = time() + $ability->idType->time_active;
					$ability->time_cooldown = time() + $ability->idType->time_cooldown;
					$ability->save(false);
					
					/* Проверяем на навык Уворот */
					if ($ability->id_ability == 2) {
						Users::model()->updateAll(['battle_target' => null], 'battle_target = '.$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 = 7;
					$log->info = $ability->idAbility->name_ability;
					$log->users = Users::getUsersForLog($user->id_user);
					$log->save(false);
					
					if ($user->class == 1) {
						$this->actionDamageRandomEnemy();
					} else {
						$this->actionHealRandomFriend();
					}
					Yii::app()->end();
				}
				Yii::app()->user->setFlash('error', 'Навык ещё не готов');
			}
        }
        $this->redirect('/dungeons/battle');
        Yii::app()->end();
    }
	
    public function actionDamageRandomEnemy() {
        $user = Users::findUser();
        if ($user->battle_type == 2 && isset($user->idDungeon) && $user->idDungeon->time_end == 0 && $user->health_now > 0) {
            $enemy = Users::getRandomBeastInDungeons($user->battle_id);
            /* Если есть кого бить - бьем */
            if ($enemy) {
                $result = BattleHelper::damageUser($user, $enemy);
                if ($result) {
                    $log = new BattleLog();
                    $log->battle_type = $user->battle_type;
                    $log->battle_id = $user->battle_id;
                    $log->id_user = $user->id_user;
                    $log->id_target = $enemy->id_user;
                    $log->type = $user->class;
                    $log->value = $result['damage'];
                    $log->info = ($result['isCritical'] ? 'крит' : '');
                    $log->users = Users::getUsersForLog($enemy->id_user);
                    $log->save(false);
                }
            } else {
                $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 = 'Бить некого';
                $log->users = $user->id_user;
                $log->save(false);
            }
        }
        $this->redirect($this->createUrl('dungeons/battle'));
        Yii::app()->end();
    }

    public function actionDamageLastTarget() {
        $user = Users::findUser();
        if ($user->battle_type == 2 && isset($user->idDungeon) && $user->idDungeon->time_end == 0 && $user->health_now > 0) {
            $enemy = Users::model()->findByPk($user->battle_target);
            /* Если есть кого бить - бьем */
            if ($enemy && $enemy->health_now > 0) {
                $result = BattleHelper::damageUser($user, $enemy);
                if ($result) {
                    $log = new BattleLog();
                    $log->battle_type = $user->battle_type;
                    $log->battle_id = $user->battle_id;
                    $log->id_user = $user->id_user;
                    $log->id_target = $enemy->id_user;
                    $log->type = $user->class;
                    $log->value = $result['damage'];
                    $log->info = ($result['isCritical'] ? 'крит' : '');
                    $log->users = Users::getUsersForLog($enemy->id_user);
                    $log->save(false);
                }
            } else {
                $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 = 'Бить некого';
                $log->users = $user->id_user;
                $log->save(false);
            }
        }
        $this->redirect($this->createUrl('dungeons/battle'));
        Yii::app()->end();
    }

    public function actionHealRandomFriend() {
        $user = Users::findUser();
        if ($user->battle_type == 2 && isset($user->idDungeon) && $user->idDungeon->time_end == 0 && $user->health_now > 0) {
            $friend = Users::getRandomFriendForDungeons($user->battle_id);
            /* Если есть кого лечить - лечим */
            if ($friend && $friend->health_now > 0 && $friend->health_now < Users::calcParam($friend->id_user, 'health') * 2) {
                $result = BattleHelper::healUser($user, $friend);
                if ($result) {
                    $log = new BattleLog();
                    $log->battle_type = $user->battle_type;
                    $log->battle_id = $user->battle_id;
                    $log->id_user = $user->id_user;
                    $log->id_target = $friend->id_user;
                    $log->type = $user->class;
                    $log->value = $result['value'];
                    $log->info = ($result['isCritical'] ? 'крит' : '');
                    $log->users = Users::getUsersForLog($friend->id_user);
                    $log->save(false);
                }
            } else {
                $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 = 'Лечить некого';
                $log->users = $user->id_user;
                $log->save(false);
            }
        }
        $this->redirect($this->createUrl('dungeons/battle'));
        Yii::app()->end();
    }

    public function actionHealSelf() {
        $user = Users::findUser();
        if ($user->battle_type == 2 && isset($user->idDungeon) && $user->idDungeon->time_end == 0 && $user->health_now > 0) {
            if ($user->battle_target == Yii::app()->user->id && $user->health_now < Users::calcParam($user->id_user, 'health')*2 || $user->health_now < Users::calcParam($user->id_user, 'health')) {
                $result = BattleHelper::healUser($user, $user);
                if ($result) {
                    $log = new BattleLog();
                    $log->battle_type = $user->battle_type;
                    $log->battle_id = $user->battle_id;
                    $log->id_user = $user->id_user;
                    $log->id_target = $user->id_user;
                    $log->type = $user->class;
                    $log->value = $result['value'];
                    $log->info = ($result['isCritical'] ? 'крит' : '');
                    $log->users = Users::getUsersForLog($user->id_user);
                    $log->save(false);
                }
            } else {
                $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 = 'Лечить некого';
                $log->users = $user->id_user;
                $log->save(false);
            }
        }
        $this->redirect($this->createUrl('dungeons/battle'));
        Yii::app()->end();
    }

    public function actionHealLastTarget() {
        $user = Users::findUser();
        if ($user->battle_type == 2 && isset($user->idDungeon) && $user->idDungeon->time_end == 0 && $user->health_now > 0) {
            $friend = Users::model()->findByPk($user->battle_target);
            /* Если есть кого лечить - лечим */
            if ($friend && $friend->health_now > 0 && $friend->health_now < Users::calcParam($friend->id_user, 'health') * 2) {
                $result = BattleHelper::healUser($user, $friend);
                if ($result) {
                    $log = new BattleLog();
                    $log->battle_type = $user->battle_type;
                    $log->battle_id = $user->battle_id;
                    $log->id_user = $user->id_user;
                    $log->id_target = $friend->id_user;
                    $log->type = $user->class;
                    $log->value = $result['value'];
                    $log->info = ($result['isCritical'] ? 'крит' : '');
                    $log->users = Users::getUsersForLog($friend->id_user);
                    $log->save(false);
                }
            } else {
                $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 = 'Лечить некого';
                $log->users = $user->id_user;
                $log->save(false);
            }
        }
        $this->redirect($this->createUrl('dungeons/battle'));
        Yii::app()->end();
    }

}
