<?php
class BattlesController extends AdminBaseController {
    public function accessRules() {
        return array(
            array('allow',
                'actions' => array('index', 'update'),
                'roles' => array('moder'),
            ),
            array('deny',
                'users' => array('*'),
                'deniedCallback' => array(Yii::app()->controller, 'redirectToHome'),
            )
        );
    }
    
    public function actionIndex() {
        $model = new BattlesLocations('search');
        $model->unsetAttributes();  // clear any default values
        //AdminFuncHelper::setupPageCountToSession();
        if (isset($_GET['BattlesLocations']))
            $model->attributes = $_GET['BattlesLocations'];

        $this->render('index', array(
            'model' => $model,
        ));
    }

    public function actionUpdate($id) {
        $battle = $this->loadModel($id);
        $model = new BattlesBotsForm();
        $model->attributes = $battle->attributes;
        if (isset($_POST['BattlesBotsForm'])) {
            $model->attributes = $_POST['BattlesBotsForm'];

            function botgen($len = 6) {
                $login = '';
                $keys = 'abcdeknopstuxyz';
                for ($i = 0; $i < $len; $i++) {
                    switch (mt_rand(1, 1)) {
                        case 1 :
                            $login .= $keys [mt_rand(0, 14)];
                            break;
                    }
                }
                return $login;
            }
            if ($model->bots_level > 9 && $model->bots_level < 15) $type = 2;
            elseif ($model->bots_level >14 && $model->bots_level < 20) $type = 3;
            elseif ($model->bots_level >20 && $model->bots_level < 25) $type = 4;
            else $type = 1;
            $names = array(1=>'Рекрут', 'Рядовой', 'Боец', 'Воин');
            $items = ShopItems::findAllBySet($model->id_set);
            $bots1 = Users::getBotsInLocation($model->id_location, 1);
            $bots2 = Users::getBotsInLocation($model->id_location, 2);
            if ($model->bots_count1 > $bots1) {
                $count = $model->bots_count1 - $bots1;
                for ($i = 1; $i <= $count; $i++) {
                    $bot = new Users();
                    $bot->side = 1;
                    $bot->class = 1;
                    $bot->id_role = 5;
                    $bot->login = $names[$type].' Краллов '.($i > 1 ? $i : '');
                    $bot->level = $model->bots_level;
                    $bot->battle_type = 1;
                    $bot->battle_id = $model->id_location;
                    $bot->avatar = 1;
                    if (!$bot->save(false)) {
                        throw new CHttpException(500, Yii::t('layout', 'Ошибка при сохранении бота!'));
                    }
                    foreach ($items as $item) {
                        ShopItems::getNewItem($item->id_item, $model->quality, $bot->id_user, false, true);
                    }
                    $health = Users::calcParam($bot->id_user, 'health');
                    $strength = Users::calcParam($bot->id_user, 'strength');
                    $bot->health = round($health + ($health/100)*($type*20)) - $health;
                    $bot->strength = round($strength + ($strength/100)*($type*3)) - $strength;
                    $bot->health_now = round(($bot->health+$health)*1.4);
                    if (!$bot->save(false)) {
                        throw new CHttpException(500, Yii::t('layout', 'Ошибка при сохранении бота!'));
                    }
                }
            }
            else {
                $count = $bots1 - $model->bots_count1;
                $criteria = new CDbCriteria();
                $criteria->compare('side', 1);
                $criteria->compare('id_role', 5);
                $criteria->compare('battle_id', $model->id_location);
                $criteria->limit = $count;
                Users::model()->deleteAll($criteria);
            }
            if ($model->bots_count2 > 0) {
                $count = $model->bots_count2 - $bots2;
                for ($i = 1; $i <= $count; $i++) {
                    $bot = new Users();
                    $bot->side = 2;
                    $bot->class = 1;
                    $bot->id_role = 5;
                    $bot->login = $names[$type].' Элийцев '.($i > 1 ? $i : '');
                    $bot->level = $model->bots_level;
                    $bot->battle_type = 1;
                    $bot->battle_id = $model->id_location;
                    $bot->avatar = 2;
                    if (!$bot->save(false)) {
                        throw new CHttpException(500, Yii::t('layout', 'Ошибка при сохранении бота!'));
                    }
                    foreach ($items as $item) {
                        ShopItems::getNewItem($item->id_item, $model->quality, $bot->id_user, false, true);
                    }
                    $health = Users::calcParam($bot->id_user, 'health');
                    $strength = Users::calcParam($bot->id_user, 'strength');
                    $bot->health = round($health + ($health/100)*($type*20)) - $health;
                    $bot->strength = round($strength + ($strength/100)*($type*3)) - $strength;
                    $bot->health_now = round(($bot->health+$health)*1.4);
                    if (!$bot->save(false)) {
                        throw new CHttpException(500, Yii::t('layout', 'Ошибка при сохранении бота!'));
                    }
                }
            }
            else {
                $count = $bots2 - $model->bots_count2;
                $criteria = new CDbCriteria();
                $criteria->compare('side', 2);
                $criteria->compare('id_role', 5);
                $criteria->compare('battle_id', $model->id_location);
                $criteria->limit = $count;
                Users::model()->deleteAll($criteria);
            }

            if ($battle->save())
                $this->redirect(array('index'));
        }

        $this->render('update', array(
            'battle' => $battle,
            'model' => $model,
        ));
    }

    public function loadModel($id) {
        $model = BattlesLocations::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, Yii::t('admin_layout', 'Страница не найдена!'));
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param UserDepartments $model the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'user-departments-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

}
