<?php

class BattleHelper extends CWidget {

    /**
     * Массив со значениями максимально опыта
     * @param type $level уровень, для которого вывести макс. опыт
     * @return int|boolean
     */
    public static function maxXP($level = 1) {
        $array = array(
            0,
            100,
            250,
            475,
            812,
            1300,
            2000,
            3200,
            4900,
            7400,
            11300,
            17000,
            25700,
            38700,
            58100,
            /*15+*/
            83400,
            116300,
            159000,
            214600,
            286800,
            380700,
            502800,
            661500,
            867800,
            1130000,
            /*25+*/
            1510000,
            2030000,
            2770000,
            3800000,
            5240000,
            7260000,
            10090000,
            14050000,
            19590000,
            27350000,
            38210000,
            /*36+*/
//            53410000,
//            74700000,
//            10450000,
//            146230000,
//            196290000,
//            256380000,
//            328480000,
//            414990000,
//            518820000,
//            643400000,
//            792910000,
//            972310000,
//            1187600000,
//            1445940000,
//            1750000000,
//            2120000000,
//            2570000000,
//            3110000000,
//            3750000000,
//            4460000000,
//            5230000000,
//            6090000000,
//            7030000000,
//            8060000000,
//            10140000000,
//            13240000000,
//            18420000000,
//            26700000000,
//            40160000000,
//            61900000000,
//            97100000000,
//            154040000000,
//            246180000000,
//            395270000000
        );
        if ($level) {
            return $array[$level];
        }
        return true;
    }
    
    /**
     * Массив со значениями максимально опыта для клана
     * @param type $level уровень, для которого вывести макс. опыт
     * @return int|boolean
     */
    public static function maxGuildXP($level = 1) {
        $array = array(
            0,
            1000000,
            2500000,
            4750000,
            8120000,
            13180000,
            20780000,
            32170000,
            49250000,
            74280000,
            /*10+*/
//            113330000,
//            179900000,
//            257490000,
//            387230000,
//            581850000,
//            873780000,
//            1310000000,
//            1960000000,
//            2950000000,
//            4430000000,
        );
        if ($level) {
            return $array[$level];
        }
        return true;
    }

    /**
     * Удар по врагу
     * @param type $user бьющий
     * @param type $enemy враг
     * @return mixed
     */
    public static function damageUser($user, $enemy = null, $energyDamage = false) {
        $enemy_killed = false;
        if (!$enemy) {
            $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);
            return false;
        }
        /* Высчитываем удар по врагу */
        if ($energyDamage)
            $attack = self::actionToUser($user, true);
        else
            $attack = self::actionToUser($user);
        /* Высчитываем поглощение урона у врага */
        if ($enemy->id_role == 6) {
            if ($enemy->armor)
                $defense = round(($attack['value']/100)*$enemy->armor);
            else
                $defense = 0;
        }
        else
            $defense = self::blockAttack($enemy, $attack['value']);
        /* Разбираем последствия удара */
        $attack['damage'] = $attack['value'] - $defense;
        if (!$energyDamage) {
            if ($enemy->health_now < $attack['damage']) {
                $attack['damage'] = $enemy->health_now;
            }
        }
        else {
            if ($enemy->energy_now < $attack['damage']) {
                $attack['damage'] = $enemy->energy_now;
            }
        }
        /* Если у ударившего Премиум, даем х2 опыт */
        if ($user->premium_time > time()) {
            $user_xp = $attack['damage'] * 2;
        } else {
            $user_xp = $attack['damage'];
        }
        $bonus = Actions::getBonusValue(2);
        if ($bonus > 0) {
            $user_xp = round($user_xp + ($user_xp/100)*$bonus);
        }
        /* Записываем все в базу */
        $user_params = [
            'xp' => $user->xp + $user_xp,
            'battle_target' => $enemy->id_user,
            'battle_output' => $attack['damage'],
            'battle_time_out' => time(),
            'energy_now' => $user->energy_now - $attack['energy']
        ];

        if ($user->id_role == 5 || $user->id_role == 6) {
            $user_params['participation'] = $user->participation + round($attack['damage']*1.2); 
        }
        else {
           $user_params['participation'] = $user->participation + $attack['damage']; 
           $user_params = self::checkXP($user, $user_params);
        }
        
        if ($user->guild_id) {
            $user_guild_xp = round($user_xp/sqrt(count($user->idGuild->users)));
            $bonus = Actions::getBonusValue(3);
            if ($bonus > 0) {
                $user_guild_xp = round($user_guild_xp + ($user_guild_xp/100)*$bonus);
            }
            self::checkGuildXP($user->guild_id, $user_guild_xp);
            $user_params['guild_xp'] = $user->guild_xp + $user_guild_xp;
        }
        
        if (!$energyDamage && $enemy->health_now - $attack['damage'] <= 0) {
            $enemy_killed = true;
        }

        /* Если у врага Премиум, даем х2 опыт */
        if ($enemy->premium_time > time()) {
            $enemy_xp = $defense * 2;
        } else {
            $enemy_xp = $defense;
        }
        $bonus = Actions::getBonusValue(2);
        if ($bonus > 0) {
            $enemy_xp = round($enemy_xp + ($enemy_xp/100)*$bonus);
        }
        $enemy_params = [
            'xp' => $enemy->xp + $enemy_xp,
            'battle_income' => $attack['damage'],
            'battle_time_in' => time(),
        ];
        if (!$energyDamage) {
            $enemy_params['health_now'] = $enemy->health_now - $attack['damage'];
        }
        else {
            $enemy_params['energy_now'] = $enemy->energy_now - $attack['damage'];
        }

        if ($enemy->id_role == 5 || $enemy->id_role == 6) {
            $enemy_params['participation'] = $enemy->participation + round($defense*1.2); 
        }
        else {
           $enemy_params['participation'] = $enemy->participation + $defense; 
           $enemy_params = self::checkXP($enemy, $enemy_params);
        }
        
        if ($enemy->guild_id) {
            $enemy_guild_xp = round($enemy_xp/sqrt(count($enemy->idGuild->users)));
            $bonus = Actions::getBonusValue(3);
            if ($bonus > 0) {
                $enemy_guild_xp = round($enemy_guild_xp + ($enemy_guild_xp/100)*$bonus);
            }
            self::checkGuildXP($enemy->guild_id, $enemy_guild_xp);
            $enemy_params['guild_xp'] = $enemy->guild_xp + $enemy_guild_xp;
        }

        if ($enemy_killed) {
            $criteria = new CDbCriteria();
            $criteria->select = array('id_user');
            $criteria->compare('battle_target', $enemy->id_user);
            $ids = CHtml::listData(Users::model()->findAll($criteria), 'id_user', 'id_user');
            if (!empty($ids)) {
                Users::model()->updateByPk($ids, array('battle_target'=>0));
            }

            $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 = 4;
            if ($enemy->id_role == 6) {
                $log->users = Users::getUsersForLog($enemy->id_user, $user->battle_id);  
            }
            else {
                $log->users = Users::getUsersForLog($enemy->id_user);
            }
            $log->save(false);
            if ($enemy->premium_time < time() && $enemy->idRole->id_cat_role != 5) {
                $item = UserItems::getRandomItem($enemy->id_user);
                if ($item && $item->idItem->id_set > 1) {
                    $percent = round($item->hardness_max * 15 / 100);
                    $item->hardness -= $percent;
                    if (!$item->save(false)) {
                        throw new CHttpException(500, Yii::t('layout', 'Ошибка при сохранении данных о предмете!'));
                    }
                }
            }
        }
        Users::model()->updateByPk($user->id_user, $user_params);
        Users::model()->updateByPk($enemy->id_user, $enemy_params);

        /* Если был убит зверь - проверяем убили ли всех и выдаем лут*/
        if ($enemy_killed && $enemy->id_role == 6) {
            UserStatistic::addToStatistic(UserStatistic::KM);
            self::dungeonController($user);
        }
        elseif ($enemy_killed && $enemy->id_role == 5) {
            UserStatistic::addToStatistic(UserStatistic::KB);
        }
        elseif ($enemy_killed) {
            UserStatistic::addToStatistic(UserStatistic::KU);
        }
        return $attack;
    }

    /**
     * Лечение игрока
     * @param type $user хилер
     * @param type $friend цель
     * @return mixed
     */
    public static function healUser($user, $friend) {
        /* Высчитываем лечение по союзнику */
        $heal = self::actionToUser($user);
        $max_health = Users::calcParam($friend->id_user, 'health')*2;
        /* Записываем все в базу */
        $user_params = [
            'battle_target' => $friend->id_user,
            'battle_output' => $heal['value'],
            'battle_time_out' => time(),
            'participation' => $user->participation + $heal['value'],
            'energy_now' => $user->energy_now - $heal['energy']
        ];

        /* Если хилер себя лечит, значит пишем все только в 1 переменную */
        if ($user->id_user == $friend->id_user) {
            if ($max_health <= ($user->health_now + $heal['value'])) {
                $heal['value'] = $max_health - $user->health_now;
                $user_params['health_now'] = $max_health;
            } else {
                $user_params['health_now'] = $user->health_now + $heal['value'];
            }
            $user_params['battle_heal'] = $heal['value'];
        }
        /* Если хилер лечит союзника, сохраняем и его тоже */ 
        else {
            $friend_params = [];
            if ($max_health <= ($friend->health_now + $heal['value'])) {
                $heal['value'] = $max_health - $friend->health_now;
                $friend_params['health_now'] = $max_health;
            } else {
                $friend->health_now += $heal['value'];
                $friend_params['health_now'] = $friend->health_now + $heal['value'];
            }
            $friend_params['battle_heal'] = $heal['value'];
            Users::model()->updateByPk($friend->id_user, $friend_params);

            /* Если у хилящего Премиум, даем х2 опыт */
            if ($user->premium_time > time()) {
                $user_xp = $heal['value'] * 2;
            } else {
                $user_xp = $heal['value'];
            }
            $bonus = Actions::getBonusValue(2);
            if ($bonus > 0) {
                $user_xp = round($user_xp + ($user_xp/100)*$bonus);
            }
            $user_params['xp'] = $user->xp + $user_xp;
            if ($user->idRole->id_cat_role != 5) {
                $user_params = self::checkXP($user, $user_params);
            }
            if ($user->guild_id) {
                $user_guild_xp = round($user_xp/sqrt(count($user->idGuild->users)));
                $bonus = Actions::getBonusValue(3);
                if ($bonus > 0) {
                    $user_guild_xp = round($user_guild_xp + ($user_guild_xp/100)*$bonus);
                }
                $user->guild_xp += $user_guild_xp;
                self::checkGuildXP($user->guild_id, $user_guild_xp);
                $user_params['guild_xp'] = $user->guild_xp + $user_guild_xp;
            }
        }
        Users::model()->updateByPk($user->id_user, $user_params);
        return $heal;
    }

    /**
     * Выпиваем бутылочку
     * @param type $user
     */
    public static function usePotion($user) {
        if ($user->bottles && $user->battle_bottles_time < time()) {
            $params = Users::calcParam($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 = 6;
            $log->info = 1;
            $log->users = Users::getUsersForLog($user->id_user);
            $log->save(false);
            $user_params = [
                'bottles' => $user->bottles - 1,
                'battle_bottles_time' => time() + 90,
                'health_now' => $params->totalHealth*2,
                'energy_now' => $params->totalEnergy*2
            ];
            Users::model()->updateByPk($user->id_user, $user_params);
            UserStatistic::addToStatistic(UserStatistic::UP);
            return true;
        }
        return false;
    }

    /**
     * Захват территории в Битвах
     * @param type $user пользователь
     * @return type
     * @throws CHttpException
     */
    public static function captureTerritory($user) {
        /* Высчитываем удар по башне */
        $attack = self::actionToUser($user);
        $attack['value'] = round($attack['value'] / 2);
        $location = BattlesLocations::model()->findByPk($user->battle_id);
        $location->health_now -= $attack['value'];
        if ($location->health_now <= 0) {
            $location->side_now = $user->side;
            $location->health_now = $location->health_default;
        }
        if (!$location->save(false)) {
            throw new CHttpException(500, Yii::t('layout', 'Ошибка при сохранении локации!'));
        }

        /* Если у ударившего Премиум, даем х2 опыт */
        $user_params = [
            'battle_output' => $attack['value'],
            'battle_time_out' => time(),
            'participation' => $user->participation + $attack['value'],
            'energy_now' => $user->energy_now - $attack['energy']
        ];
        if ($user->premium_time > time()) {
            $user_xp = $attack['value'] * 2;
        } else {
            $user_xp = $attack['value'];
        }
        $bonus = Actions::getBonusValue(2);
        if ($bonus > 0) {
            $user_xp = round($user_xp + ($user_xp/100)*$bonus);
        }
        $user_params['xp'] = $user->xp + $user_xp;
        if ($user->idRole->id_cat_role != 5) {
           $user_params = self::checkXP($user, $user_params); 
        }
        if ($user->guild_id) {
            $user_guild_xp = round($user_xp/sqrt(count($user->idGuild->users)));
            $bonus = Actions::getBonusValue(3);
            if ($bonus > 0) {
                $user_guild_xp = round($user_guild_xp + ($user_guild_xp/100)*$bonus);
            }
            $user->guild_xp += $user_guild_xp;
            self::checkGuildXP($user->guild_id, $user_guild_xp);
            $user_params['guild_xp'] = $user->guild_xp + $user_guild_xp;
        }
        Users::model()->updateByPk($user->id_user, $user_params);
        return $attack;
    }

    /**
     * Действие в боях, применимое к игрокам, ударить для воина, лечить для медика
     * @param type $id_user массив игрока
     * @return type
     */
    public static function actionToUser($user, $energyDamage = false) {
        $result = array();
        $result['isCritical'] = false;
        $result['energy'] = self::countEnergyToAttack($user);
        $params = Users::calcParam($user->id_user);
        /* Если это зверь, значит делим его урон на всех кто в пещере */

        if ($user->id_role == 6) {
            $count = count($user->idDungeon->warriors) + count($user->idDungeon->healers);
            $attack = round($user->strength / $count);
            if ($user->password > 1 && $user->idDungeon->time_start + 5 * 60 < time()) {
                if ($user->password == 2) {
                    Users::model()->updateByPk($user->id_user, array('password'=>3));
                    $log = new BattleLog();
                    $log->battle_type = $user->battle_type;
                    $log->battle_id = $user->battle_id;
                    $log->id_user = $user->id_user;
                    $log->info = '<img src="/images/icons/dragon.png" alt="*"/> ' . $user->login . ' буйствует';
                    $log->type = 9;
                    $log->value = 2;
                    $log->users = Users::getUsersForLog($user->id_user, $user->battle_id);  
                    $log->save(false);
                }
                $percent = floor((time() - ($user->idDungeon->time_start + 5 * 60))/60);
                $attack += 5 * $percent * ($attack/100) ;
            }
        }
        else
            $attack = $params->totalStrength;
        /* Урезаем силу для удара/лечения */
        if ($user->class > 1 && !$energyDamage)
            $attack = round($attack / 2);
        else
            $attack = round($attack / 3);
		/* Проверяем на навык Ярость (урон) */
		$ability = UsersAbilities::model()->findByAttributes(['id_user' => $user->id_user], ['condition' => '`id_ability` = 1 AND `time_active` >= unix_timestamp(NOW())']);
		if ($ability) {
			$attack = round($attack * 0.01 * $ability->idType->value);
		}
        /* Проверяем достаточно ли энергии */
        if ($user->idRole->id_cat_role != 5) {
            if ($user->energy_now < $result['energy']) {
                $attack = round($attack * 0.75);
            }
        }
        /* Проверяем на крит удар/лечение */
        $rand = rand(1,100);
		/* Проверяем на навык Закалка (криты) */
		$ability = UsersAbilities::model()->findByAttributes(['id_user' => $user->id_user], ['condition' => '`id_ability` = 3 AND `time_active` >= unix_timestamp(NOW())']);
		if ($ability) {
			$rand = 0;
		}
        if (Users::getUserCritValue($params->totalEnergy) >= $rand) {
            $critBoost = rand(13, 17) / 10;
            $attack = round($attack * $critBoost);
            $result['isCritical'] = true;
        }
        if ($user->idRole->id_cat_role != 5) {
            if ($user->battle_time_out < (time() - 5)) {
                $percent = 100;
                if ($user->bottles < 100 && rand(1, 100) > 99) {
                    Users::model()->updateByPk($user->id_user, array('bottles'=>$user->bottles + 1));
                    $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);
                }
            } elseif ($user->battle_time_out < (time() - 3)) {
                $percent = rand(60, 80);
            } elseif ($user->battle_time_out < (time() - 2)) {
                $percent = rand(40, 60);
            } else {
                $percent = 0;
            }
            $result['value'] = round(($attack / 100) * $percent);
        } else
            $result['value'] = $attack;
        return $result;
    }

    /**
     * Высчитывает кол-во поглощаемого урона, уменьшает прочность у предмета
     * @param type $id_user массив пользователя, по кому ударили
     * @param type $attack кол-во урона
     * @return type
     */
    public static function blockAttack($user, $attack) {
        $block = Users::getUserBlockValue(Users::calcParam($user->id_user, 'armor'));
        $result = round(($attack / 100) * $block);
        if ($user->premium_time < time() && $user->idRole->id_cat_role != 5) {
            $item = UserItems::getRandomItem($user->id_user);
            if ($item && $item->idItem->id_set > 1) {
                $item->hardness -= rand(1, 2);
                if (!$item->save(false)) {
                    throw new CHttpException(500, Yii::t('layout', 'Ошибка при сохранении данных о предмете!'));
                }
            }
        }
        return $result;
    }

    /**
     * Возвращает кол-во энергии необходимое для удара/лечения
     * @param type $user массив с данными юзера
     * @return int кол-во энергии
     */
    public static function countEnergyToAttack($user) {
        $result = 0;
        if ($user->level <= 20) {
            $result = round($user->level * 3.3);
        } elseif ($user->level > 20 && $user->level <= 25) {
            $result = round($user->level * 4);
        } elseif ($user->level > 25 && $user->level <= 30) {
            $result = round($user->level * 5);
        } else {
            $result = sqrt(Users::calcParam($user->id_user, 'strength')) * 4.5;
        }
        return $result;
    }

    public static function participation($id_location, $damage) {
        $location = BattlesLocations::model()->findByPk($id_location);
        if ($location->participation_now + $damage >= $location->participation_default) {
            $location->participation_now = 0;

            $winner = Users::getParticipationLeaderForBattles($id_location);
            $percent = BattlesLocations::getDomination($winner->side, $location->level_max);
            $winner->participation = round($winner->participation / 2);
            if (!$winner->save(false)) {
                throw new CHttpException(500, Yii::t('layout', 'Ошибка при сохранении данных пользователя!'));
            }
            /* Качество выпадающей вещи */
            if ($percent >= 70)
                $type = rand(2, 5);
            elseif ($percent >= 50)
                $type = rand(2, 4);
            else
                $type = rand(1, 3);
            /* Если выпала хорошая, рандомим еще раз :) */
            if ($type > 5)
                $type = rand(3, 6);
            if ($type > 4)
                $type = rand(3, 5);

            $item = ShopItems::getRandomItemInBattles($winner->idLocation);
            if ($item->id_set == 4 && $type > 4)
                $type = 4;
            elseif ($item->id_set < 4 && $type > 3)
                $type = 3;
            $drop = ShopItems::getNewItem($item->id_item, $type, $winner->id_user, false);

            $log = new BattleLog();
            $log->battle_type = $winner->battle_type;
            $log->battle_id = $winner->battle_id;
            $log->id_user = $winner->id_user;
            $log->type = 5;
            $log->value = $drop;
            $log->users = Users::getUsersForLog($winner->id_user, $winner->battle_id);
            $log->save(false);
        } else {
            $location->participation_now += $damage;
        }
        if (!$location->save(false)) {
            throw new CHttpException(500, Yii::t('layout', 'Ошибка при сохранении участия!'));
        }
        return true;
    }

    /**
     * Проверяет апнулся ли юзер, и возвращает обьект уже с новыми данными
     * @param type $user
     * @param type $user_params
     * @return boolean
     * @throws CHttpException
     */
    public static function checkXP($user, $user_params) {
        $max_xp = self::maxXP($user->level);
        if ($user_params['xp'] >= $max_xp && $user->level < 15) {
            $user_params['level'] += 1;
            $params = Users::calcParam($user->id_user);
            $user_params['health_now'] = $params->totalHealth*2;
            $user_params['energy_now'] = $params->totalEnergy*2;
            $log = new BattleLog();
            $log->battle_type = $user->battle_type;
            $log->battle_id = $user->battle_id;
            $log->id_user = $user->id_user;
            $log->type = 6;
            $log->info = 2;
            $log->users = Users::getUsersForLog($user->id_user);
            $log->save(false);
        }
        elseif ($user_params['xp'] >= $max_xp && $user->level == 15) {
            $user_params['xp'] = $max_xp - 1;
        }
        return $user_params;
    }
    
    /**
     * Проверяет апнулся ли клан
     * @param type $id_guild
     * @return boolean
     * @throws CHttpException
     */
    public static function checkGuildXP($id_guild, $user_guild_xp) {
        $guild = Guilds::model()->findByPk($id_guild);
        if ($guild) {
            $guild->xp += $user_guild_xp;
            if ($guild->xp >= self::maxGuildXP($guild->level) && $guild->level < 9) {
                $guild->level += 1;
            }
            $guild->save(false);
        }
        return true;
    }
    
    /**
     * Вызов функции происходит при смерти зверя, проверяет на наличие других, если таковых нет, значит данж пройден
     * @param type $user
     * @return boolean
     */
    public static function dungeonController($user) {
        /* Если все звери мертвы завершаем данж */
        if (BattlesDungeons::model()->with('bots')->count(array('condition' => 'bots.health_now>0 AND t.id_battle='.$user->battle_id)) < 1) {
            $dungeon = BattlesDungeons::model()->findByPk($user->battle_id);
            if (!empty($dungeon) && !$dungeon->time_end) {
                $dungeon->time_end = time();
                if (!$dungeon->save(false)) {
                    throw new CHttpException(500, Yii::t('layout', 'Ошибка при сохранении данных боя!'));
                }

                $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->type = 9;
                $log->info = 'Ваш отряд прошел пещеру (время '.FuncHelper::timeToCount(time()-$dungeon->time_start).')';
                $log->users = $users_ids;
                $log->save(false);

                /*Запишем участие в лог*/
                foreach ($dungeon->users as $dungeon_user) {
                    $log = new BattleLog();
                    $log->battle_type = $user->battle_type;
                    $log->battle_id = $user->battle_id;
                    $log->id_user = $dungeon_user->id_user;
                    $log->type = 8;
                    $log->value = $dungeon_user->participation;
                    $log->info = 1;
                    $log->users = $users_ids;
                    $log->save(false);
                    UserDungeons::checkHistory($dungeon_user->id_user, $dungeon);
//                    $dungeon_user->battle_id = null;
//                    $dungeon_user->battle_type = null;
//                    $dungeon_user->battle_target = null;
//                    if (!$dungeon_user->save(false)) {
//                        throw new CHttpException(500, Yii::t('layout', 'Ошибка при сохранении данных пользователя!'));
//                    }
//                    unset($dungeon_user);
                }

                /*Выдаем лут*/
                if ($dungeon->id_dungeon == 1) {
                    $id_set = 3;
                    $quality = 3;
                    $items[] = array(
                        'id_set' => 3,
                        'quality' => 3
                    );
                    $winners_ids[] = array_rand($users_ids);
                }
                elseif ($dungeon->id_dungeon == 2) {
                    if (rand(1,100) >= 75) {
                        $items[] = array(
                            'id_set' => 5,
                            'quality' => 4
                        );
                        $items[] = array(
                            'id_set' => 5,
                            'quality' => 5
                        );
                        if (count($users_ids) > 1) {
                            $winners_ids = array_rand($users_ids, 2);
                        } 
                        else {
                            $winners_ids = $users_ids;
                        }
                    }
                    else {
                        $items[] = array(
                            'id_set' => 5,
                            'quality' => 4
                        );
                        $winners_ids[] = array_rand($users_ids);
                    }
                }
                elseif ($dungeon->id_dungeon == 3) {
                    if (rand(1,100) >= 75) {
                        $items[] = array(
                            'id_set' => rand(6,8),
                            'quality' => 4
                        );
                        $items[] = array(
                            'id_set' => rand(6,8),
                            'quality' => 5
                        );
                        if (count($users_ids) > 1) {
                            $winners_ids = array_rand($users_ids, 2);
                        } 
                        else {
                            $winners_ids = $users_ids;
                        }
                    }
                    else {
                        $items[] = array(
                            'id_set' => rand(6,8),
                            'quality' => 4
                        );
                        $winners_ids[] = array_rand($users_ids);
                    }
                }
                elseif ($dungeon->id_dungeon == 4) {
                    if (rand(1,100) >= 90) {
                        $items[] = array(
                            'id_set' => 9,
                            'quality' => 6
                        );
                        $items[] = array(
                            'id_set' => 9,
                            'quality' => 6
                        );
                        if (count($users_ids) > 1) {
                            $winners_ids = array_rand($users_ids, 2);
                        } 
                        else {
                            $winners_ids = $users_ids;
                        }
                    }
                    else {
                        $items[] = array(
                            'id_set' => 9,
                            'quality' => 6
                        );
                        $winners_ids[] = array_rand($users_ids);
                    }
                }
                elseif ($dungeon->id_dungeon == 6) {
                    $items[] = array(
                        'id_set' => rand(6,8),
                        'quality' => 4
                    );
                    $items[] = array(
                        'id_set' => rand(6,8),
                        'quality' => 5
                    );
                    $users = CHtml::listData($dungeon->users, 'guild_rank', 'id_user');
                    krsort($users);
                    $winners_ids = array(array_values($users)[0], array_values($users)[0]);
                }
                elseif ($dungeon->id_dungeon == 7) {
                    $items[] = array(
                        'id_set' => rand(6,8),
                        'quality' => 5
                    );
                    $items[] = array(
                        'id_set' => rand(6,8),
                        'quality' => 6
                    );
                    $users = CHtml::listData($dungeon->users, 'guild_rank', 'id_user');
                    krsort($users);
                    $winners_ids = array(array_values($users)[0], array_values($users)[0]);
                }
                $i=0;
                foreach ($winners_ids as $winner_id) {
                    $item = ShopItems::getRandomItemInDungeons($items[$i]['id_set']);
                    $drop = ShopItems::getNewItem($item->id_item, $items[$i]['quality'], $winner_id, false, false);

                    $log = new BattleLog();
                    $log->battle_type = $user->battle_type;
                    $log->battle_id = $user->battle_id;
                    $log->id_user = $winner_id;
                    $log->type = 5;
                    $log->value = $drop;
                    $log->users = $users_ids;
                    $log->save(false); 
                    $i++;
                }
                return true;
            }
        }
        return false;
    }

    public static function battleLog($user, $user_battle) {
        $result = '';
        $count = 0;
        foreach ($user->logs as $log) {
            if ($log->battle_type == $user_battle) {
                $count++;
                if ($log->type == 1) {
//                    if ($log->value < 1)
//                        $result .= Users::getLoginWithLink($log->id_user) . ' промахнулся<br />';
                    if (!$log->id_target)
                        $result .= Users::getLoginWithLink($log->id_user) . ' ударил по укреплению на ' . $log->value . '<br />';
                    elseif ($log->id_target != Yii::app()->user->id) {
                        if ($user_battle == 3) {
                            $result .= Users::getLoginWithLink($log->id_user) . ' ударил ' . Users::getLogin($log->id_target) . ' на ' . $log->value . ' ' . $log->info . '<br />';
                        }
                        else {
                            $result .= Users::getLoginWithLink($log->id_user) . ' ударил ' . Users::getLoginWithLink($log->id_target) . ' на ' . $log->value . ' ' . $log->info . '<br />';
                        }
                    }
                    else {
                        $result .= Users::getLoginWithLink($log->id_user) . '<span class="red"> ударил Вас на ' . $log->value . ' ' . $log->info . '</span><br />';
                    }
                        
                }
                elseif ($log->type == 2) {
//                    if ($log->value < 1)
//                        $result .= Users::getLoginWithLink($log->id_user) . ' промахнулся<br />';
                    if ($log->id_user == $log->id_target)
                        $result .= Users::getLoginWithLink($log->id_user) . '<span class="green"> полечил себя на ' . $log->value . ' ' . $log->info . '</span><br />';
                    elseif ($log->id_target != Yii::app()->user->id) {
                        if ($user_battle == 3) {
                            $result .= Users::getLoginWithLink($log->id_user) . ' полечил ' . Users::getLogin($log->id_target) . ' на ' . $log->value . ' ' . $log->info . '<br />';
                        }
                        else {
                            $result .= Users::getLoginWithLink($log->id_user) . ' полечил ' . Users::getLoginWithLink($log->id_target) . ' на ' . $log->value . ' ' . $log->info . '<br />';
                        }
                    }
                    elseif ($log->id_target == Yii::app()->user->id)
                        $result .= Users::getLoginWithLink($log->id_user) . ' <span class="green">полечил Вас на ' . $log->value . ' ' . $log->info . '</span><br />';
                }
                elseif ($log->type == 3) {
//                    if ($log->value < 1)
//                        $result.=Users::getLoginWithLink($log->id_user) . ' промахнулся<br />';
                    if ($log->id_target == $log->id_target)
                        $result.=Users::getLoginWithLink($log->id_user) . ' сжёг у ' . Users::getLoginWithLink($log->id_target) . ' ' . $log->value . ' энергии ' . $log->info . '<br />';
                    elseif ($log->id_target != Yii::app()->user->id) {
                        if ($user_battle == 3) {
                            $result .= Users::getLoginWithLink($log->id_user) . ' сжёг у ' . Users::getLogin($log->id_target) . ' ' . $log->value . ' энергии ' . $log->info . '<br />';
                        }
                        else {
                            $result .= Users::getLoginWithLink($log->id_user) . ' сжёг у ' . Users::getLoginWithLink($log->id_target) . ' ' . $log->value . ' энергии ' . $log->info . '<br />';
                        }
                    }
                    elseif ($log->id_target == Yii::app()->user->id)
                        $result.=Users::getLoginWithLink($log->id_user) . '<span class="red"> сжёг у Вас ' . $log->value . ' энергии ' . $log->info . '</span><br />';
                }
                elseif ($log->type == 4) {
                    if ($log->id_target != Yii::app()->user->id) {
                        if ($user_battle == 3) {
                            $result.=Users::getLoginWithLink($log->id_user) . ' убил ' . Users::getLogin($log->id_target) . '<br />';
                        }
                        else {
                            $result.=Users::getLoginWithLink($log->id_user) . ' убил ' . Users::getLoginWithLink($log->id_target) . '<br />';
                        }
                    }
                    else {
                        if ($user_battle == 3) {
                            $result.=Users::getLogin($log->id_user) . '<span class="red"> убил Вас</span><br />'; 
                        }
                        else {
                            $result.=Users::getLoginWithLink($log->id_user) . '<span class="red"> убил Вас</span><br />'; 
                        }
                    } 
                }
                elseif ($log->type == 5) {
                    if ($log->id_user != Yii::app()->user->id)
                        $result.=Users::getLoginWithLink($log->id_user) . ' получил ' . UserItems::itemName($log->value, 1) . '<br />';
                    else
                        $result.='<span class="green">Вы получили ' . UserItems::itemName($log->value, 1) . '</span><br />';
                }
                elseif ($log->type == 6) {
                    if ($log->info == 1) {
                        if ($log->id_user != Yii::app()->user->id)
                            $result.=Users::getLoginWithLink($log->id_user) . ' выпил эликсир<br />';
                        else
                            $result.='<span class="green">Вы выпили эликсир</span><br />';
                    }
                    else {
                        if ($log->id_user != Yii::app()->user->id)
                            $result.=Users::getLoginWithLink($log->id_user) . ' получил новый уровень<br />';
                        else
                            $result.='<span class="green">Вы получили новый уровень!</span><br />';
                    }
                }
                elseif ($log->type == 7) {
                    if ($log->id_user != Yii::app()->user->id)
                        $result.=Users::getLoginWithLink($log->id_user) . ' использовал навык <span class="green">' . $log->info . '</span><br />';
                    else
                        $result.='<span class="green">Вы использовали навык ' . $log->info . '</span><br />';
                }
                elseif ($log->type == 8) {
                    if ($log->info == 1)
                        $result .= Users::getLoginWithLink($log->id_user) . ' участие <span class="green">' . $log->value . '</span><br />';
                    elseif ($log->info == 2)
                        $result .= Users::getLoginWithLink($log->id_user) . ' покинул пещеру<br />';
                    else
                        $result.='<span class="green">' . $log->info . '</span><br />';
                }
                elseif ($log->type == 9) {
                    if ($log->value == 1) {
                        $result.='<span class="text-success">' . $log->info . '</span><br />';
                    }
                    elseif ($log->value == 2) {
                        $result.='<span class="text-danger">' . $log->info . '</span><br />';
                    }
                    else {
                        $result.=$log->info.'<br />';
                    }
                } else
                    $result.='<span class="red">Бой начался!</span><br />';
                if ($count > 9)
                    break;
            }
        }
        return $result;
    }

}

?>