<?php

class BattlesController extends Controller {

    public function accessRules() {
        return array(
            array('deny',
                'roles' => array('banned'),
                'deniedCallback' => array(Yii::app()->controller, 'redirectToHome'),
            ),
            array('allow',
                'actions' => array('rise', 'index', 'captureTerritory', 'damageLastTarget', 'damageRandomEnemy', 'energyDamageLastTarget', 'energyDamageRandomEnemy', 'healLastTarget', 'healRandomFriend', 'healSelf', 'nearLocation', 'usePotion', 'maps', 'useAbility'),
                'users' => array('@'),
            ),
            array('deny',
                'users' => array('*'),
                'deniedCallback' => array(Yii::app()->controller, 'redirectToHome'),
            )
        );
    }

    public function actionIndex() {
        $user = Users::findUser();
        $criteria = new CDbCriteria();
        if (!$user->battle_type) {
            $user->battle_type = 1;
            $criteria->compare('type_location', 1);
            $criteria->compare('side_default', $user->side);
            $current = BattlesLocations::model()->find($criteria);
            $user->battle_id = $current->id_location;
			Users::model()->updateByPk($user->id_user, ['battle_type' => 1, 'battle_id' => $current->id_location]);
        } elseif ($user->battle_type == 1) {
            $current = BattlesLocations::model()->findByPk($user->battle_id);
            if ($user->level < $current->level_min || $user->level > $current->level_max) {
                Users::model()->updateByPk($user->id_user, ['battle_type' => null, 'battle_id' => null]);
                Yii::app()->user->setFlash('error', 'У Вас слишком большой уровень для этой территории');
                $this->redirect($this->createUrl('battles/index'));
                Yii::app()->end();
            }
        } else {
            $this->redirect(Yii::app()->user->returnUrl);
            Yii::app()->end();
        }
        $locations = BattlesNavigator::getNearLocations($user->battle_id, $user);
		$ability = UsersAbilities::model()->findByAttributes(['id_user' => Yii::app()->user->id], ['condition' => 'chosen = 3']);
        $this->render('index', array(
            'user' => $user,
            'locations' => $locations,
            'current' => $current,
			'ability' => $ability
        ));
    }

    public function actionRise() {
        $user = Users::findUser();
        if ($user->battle_type == 1 && $user->health_now < 1) {
            $criteria = new CDbCriteria();
            $criteria->compare('type_location', 1);
            $criteria->compare('side_default', $user->side);
            $criteria->compare('status', 1);
            $current = BattlesLocations::model()->find($criteria);
            $user->battle_id = $current->id_location;
            $params = Users::calcParam($user->id_user);
            $user->health_now = $params->totalHealth;
            $user->energy_now = $params->totalEnergy;
            if (!$user->save(false)) {
                throw new CHttpException(500, Yii::t('layout', 'Ошибка при сохранении пользователя!'));
            }
        }
        $this->redirect(array('/battles/index'));
        Yii::app()->end();
    }
    
    public function actionMaps($id = null) {
        $user = Users::findUser();
        $criteria = new CDbCriteria();
        $criteria->addCondition('side_default = 0 OR side_default = ' . $user->side);
        $criteria->compare('type_location', 2);
        $criteria->compare('status', 1);
        $all = BattlesLocations::model()->findAll($criteria);
        $maps = array();
        foreach ($all as $one) {
            $maps[$one->id_location] = $one;
        }
        $this->render('maps', array(
            'maps' => $maps,
        ));
    }

    public function actionNearLocation($id) {
        $user = Users::model()->findByPk(Yii::app()->user->id);
        if ($user->battle_type != 1) {
            $this->redirect(Yii::app()->user->returnUrl);
            Yii::app()->end();
        }
        /* Если поле под контролем стороны игрока - продолжаем */
        if (BattlesNavigator::checkAccessToLocation($id, $user)) {
            $user->battle_id = $id;
            $user->battle_target = null;
            if (!$user->save(false)) {
                throw new CHttpException(500, Yii::t('layout', 'Ошибка при сохранении пользователя!'));
            }
            $this->redirect($this->createUrl('battles/index'));
            Yii::app()->end();
        }
        /* Если контроль перешел на другую сторону */ elseif ($user->battle_type == 1) {
            Yii::app()->user->setFlash('error', 'Для перехода сначала захватите территорию');
            $this->redirect($this->createUrl('battles/index'));
            Yii::app()->end();
        }
        /* Скорее всего ввели не тот ID */ else {
            $this->redirect(Yii::app()->user->returnUrl);
            Yii::app()->end();
        }
    }

    public function actionUsePotion() {
        $user = Users::model()->findByPk(Yii::app()->user->id);
        if ($user->battle_type != 1) {
            $this->redirect(Yii::app()->user->returnUrl);
            Yii::app()->end();
        }
        if ($user->health_now > 0) {
            BattleHelper::usePotion($user);
            if ($user->class == 1) {
                $this->actionDamageRandomEnemy();
            } else {
                $this->actionHealRandomFriend();
            }
            Yii::app()->end();
        }
        $this->redirect($this->createUrl('battles/index'));
        Yii::app()->end();
    }
	
    public function actionUseAbility($chosen) {
        $user = Users::findUser();
        if ($user->battle_type != 1) {
            $this->redirect(Yii::app()->user->returnUrl);
            Yii::app()->end();
        }
        if ($user->health_now > 0) {
			$ability = UsersAbilities::model()->findByAttributes(['id_user' => Yii::app()->user->id], ['condition' => 'chosen = 3 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('/battles/');
        Yii::app()->end();
    }

    public function actionCaptureTerritory() {
        $user = Users::model()->findByPk(Yii::app()->user->id);
        if ($user->battle_type != 1 || $user->class != 1) {
            $this->redirect(Yii::app()->user->returnUrl);
            Yii::app()->end();
        }
        if ($user->health_now > 0) {
            /* Если есть кого бить - бьем */
            if ($user->idLocation->side_now != $user->side) {
                $result = BattleHelper::captureTerritory($user);
                /* Если было удар - идет кол-во в участие */
                if ($result) {
                    BattleHelper::participation($user->battle_id, $result['value']);
                    $log = new BattleLog();
                    $log->battle_type = $user->battle_type;
                    $log->battle_id = $user->battle_id;
                    $log->id_user = $user->id_user;
                    $log->type = $user->class;
                    $log->value = $result['value'];
                    $log->info = ($result['isCritical'] ? 'крит' : '');
                    $log->users = $user->id_user;
                    $log->save(false);
                }
            }
        }
        $this->redirect($this->createUrl('battles/index'));
        Yii::app()->end();
    }

    public function actionDamageRandomEnemy() {
        $user = Users::model()->findByPk(Yii::app()->user->id);
        if ($user->battle_type != 1) {
            $this->redirect(Yii::app()->user->returnUrl);
            Yii::app()->end();
        }
        if ($user->health_now > 0 && $user->class == 1) {
            $enemy = Users::getRandomEnemyForBattles($user->battle_id, $user->side);
            /* Если есть кого бить - бьем */
            if ($enemy) {
                $result = BattleHelper::damageUser($user, $enemy);
                /* Если был удар - идет кол-во в участие */
                if ($result) {
                    BattleHelper::participation($user->battle_id, $result['damage']);
                    $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('battles/index'));
        Yii::app()->end();
    }

    public function actionDamageLastTarget() {
        $user = Users::model()->findByPk(Yii::app()->user->id);
        if ($user->battle_type != 1) {
            $this->redirect(Yii::app()->user->returnUrl);
            Yii::app()->end();
        }
        if ($user->health_now > 0 && $user->class == 1) {
            $enemy = Users::getLastTargetForBattles($user);
            /* Если есть кого бить - бьем */
            if ($enemy) {
                $result = BattleHelper::damageUser($user, $enemy);
                /* Если был удар - идет кол-во в участие */
                if ($result) {
                    BattleHelper::participation($user->battle_id, $result['damage']);
                    $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 {
                $user->battle_target = null;
                if (!$user->save(false)) {
                    throw new CHttpException(500, Yii::t('layout', 'Ошибка при сохранении данных пользователя!'));
                }
                $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('battles/index'));
        Yii::app()->end();
    }

    public function actionEnergyDamageRandomEnemy() {
        $user = Users::model()->findByPk(Yii::app()->user->id);
        if ($user->battle_type != 1) {
            $this->redirect(Yii::app()->user->returnUrl);
            Yii::app()->end();
        }
        if ($user->health_now > 0 && $user->class == 2) {
            $enemy = Users::getRandomEnemyForBattles($user->battle_id, $user->side, false, true);
            /* Если есть у кого выжигать- выжигаем */
            if ($enemy) {
                $result = BattleHelper::damageUser($user, $enemy, true);
                /* Если было выжигание - идет кол-во в участие */
                if ($result) {
                    BattleHelper::participation($user->battle_id, $result['damage']);
                    $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 = 3;
                    $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('battles/index'));
        Yii::app()->end();
    }

    public function actionEnergyDamageLastTarget() {
        $user = Users::model()->findByPk(Yii::app()->user->id);
        if ($user->battle_type != 1) {
            $this->redirect(Yii::app()->user->returnUrl);
            Yii::app()->end();
        }
        if ($user->health_now > 0 && $user->class == 2) {
            $enemy = Users::getLastTargetForBattles($user, true);
            /* Если есть у кого выжигать- выжигаем */
            if ($enemy) {
                $result = BattleHelper::damageUser($user, $enemy, true);
                /* Если было выжигание - идет кол-во в участие */
                if ($result) {
                    BattleHelper::participation($user->battle_id, $result['damage'], true);
                    $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 = 3;
                    $log->value = $result['damage'];
                    $log->info = ($result['isCritical'] ? 'крит' : '');
                    $log->users = Users::getUsersForLog($enemy->id_user);
                    $log->save(false);
                }
            } else {
                $user->battle_target = null;
                if (!$user->save(false)) {
                    throw new CHttpException(500, Yii::t('layout', 'Ошибка при сохранении данных пользователя!'));
                }
                $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('battles/index'));
        Yii::app()->end();
    }

    public function actionHealRandomFriend() {
        $user = Users::findUser();
        if ($user->battle_type != 1) {
            $this->redirect(Yii::app()->user->returnUrl);
            Yii::app()->end();
        }
        if ($user->health_now > 0 && $user->class == 2) {
            $friend = Users::getRandomFriendForBattles($user->battle_id, $user->side);
            /* Если есть кого лечить - лечим */
            if ($friend && $friend->health_now > 0 && $friend->health_now < Users::calcParam($friend->id_user, 'health')*2) {
                $result = BattleHelper::healUser($user, $friend);
                /* Если было лечение - идет кол-во в участие */
                if ($result) {
                    BattleHelper::participation($user->battle_id, $result['value']);
                    $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('battles/index'));
        Yii::app()->end();
    }

    public function actionHealSelf() {
        $user = Users::findUser();
        if ($user->battle_type != 1) {
            $this->redirect(Yii::app()->user->returnUrl);
            Yii::app()->end();
        }
        if ($user->health_now > 0 && $user->class == 2 && ($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) {
                BattleHelper::participation($user->battle_id, $result['value']);
                $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('battles/index'));
        Yii::app()->end();
    }

    public function actionHealLastTarget() {
        $user = Users::findUser();
        if ($user->battle_type != 1) {
            $this->redirect(Yii::app()->user->returnUrl);
            Yii::app()->end();
        }
        if ($user->health_now > 0 && $user->class == 2) {
            $friend = Users::getLastHealTargetForBattles($user);
            /* Если есть кого лечить - лечим */
            if ($friend && $friend->health_now > 0 && $friend->health_now < Users::calcParam($friend->id_user, 'health') * 2) {
                $result = BattleHelper::healUser($user, $friend);
                /* Если было лечение - идет кол-во в участие */
                if ($result) {
                    BattleHelper::participation($user->battle_id, $result['value']);
                    $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 {
                $user->battle_target = null;
                if (!$user->update('battle_target')) {
                    throw new CHttpException(500, Yii::t('layout', 'Ошибка при сохранении данных пользователя!'));
                }
                $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('battles/index'));
        Yii::app()->end();
    }

}
