<?php
class UserController extends Controller {
    public function accessRules() {
        return array(
            array('deny',
                'roles' => array('banned'),
                'deniedCallback' => array(Yii::app()->controller, 'redirectToHome'),
            ),
            array('allow',
                'actions' => array('index', 'backpack', 'body', 'destroy', 'options', 'premium', 'stats', 'store', 'abilities'),
                'users' => array('@'),
            ),
            array('allow',
                'actions' => array('setBan', 'unBan'),
                'roles' => array('moder'),
            ),
            array('allow',
                'actions' => array('save'),
                'roles' => array('demo'),
            ),
            array('deny',
                'users' => array('*'),
                'deniedCallback' => array(Yii::app()->controller, 'redirectToHome'),
            )
        );
    }
    
    public function actionIndex($id = null) {
        if (!$id) $id = Yii::app()->user->id;
        $model = Users::findUser($id);
        //Счетчики вещей
        $count['body'] = UserItems::model()->countByAttributes(array(
            'id_user' => $model->id_user,
            'status' => ITEM_ON_BODY,
        ));
        if ($model->id_user == Yii::app()->user->id) {
            $count['backpack'] = UserItems::model()->countByAttributes(array(
                'id_user' => Yii::app()->user->id,
                'status' => ITEM_IN_BACKPACK,
            ));
            $count['store'] = UserItems::model()->countByAttributes(array(
                'id_user' => Yii::app()->user->id,
                'status' => ITEM_IN_STORE,
            ));
        }
        $model->login = Users::getFullLogin($id);
        $model->money = FuncHelper::Money($model->money);
        $min = BattleHelper::maxXP($model->level-1);
        $max = BattleHelper::maxXP($model->level);
        if ($model->xp > 0) {
            $percent = round(($model->xp-$min)*100/($max-$min));
        }
        else
            $percent = 0;
        $xp = array(
            'percent' => $percent,
            'max' => $max,
        );

        //Если админ, показываем форму для бана
        if (Yii::app()->user->roleCat == 3) {
            $block = new UserBan();
        } else
            $block = null;

        $user = Users::findUser();
        $this->render('index', array(
            'model' => $model,
            'count' => $count,
            'xp' => $xp,
            'block' => $block,
            'user' => $user
        ));
    }
    
    public function actionStats($id = null) {
        if (!$id) $id = Yii::app()->user->id;
        $model = Users::findUser($id);
        if (!$model) $model = Users::findUser();
        $stats = UserStatistic::model()->findByPk($id);
        if (!$stats) $stats = array();
        $this->render('stats', array(
            'model' => $model,
            'stats' => $stats
        ));
    }   
	
    public function actionAbilities($id = null) {
        if (!$id) $id = Yii::app()->user->id;
        $model = Users::findUser($id);
		$id_ability = (int)$_GET['ability'];
		if (!empty($id_ability) && UsersAbilities::model()->countByAttributes(['id_user' => Yii::app()->user->id, 'id' => $id_ability]) > 0) {
			$abilities = UsersAbilities::model()->findAllByAttributes(['id_user' => Yii::app()->user->id], ['condition' => '`id` <> '.$id_ability.'  AND chosen > 0', 'order' => 'chosen DESC']);
			$chosen = 2;
			foreach ($abilities as $ability) {
				UsersAbilities::model()->updateByPk($ability->id, ['chosen' => $chosen]);
				$chosen--;
			}
			UsersAbilities::model()->updateByPk($id_ability, ['chosen' => 3]);
            $this->redirect(['/user/abilities', 'id' => $id]);
            Yii::app()->end();
        }
		$abilities = UsersAbilities::model()->findAllByAttributes(['id_user' => Yii::app()->user->id], ['order' => 'chosen DESC']);
        $this->render('abilities', ['model' => $model, 'abilities' => $abilities]);
    }

    public function actionBody($id = null) {
        if (!$id) $id = Yii::app()->user->id;
        $model = Users::findUser($id);
        $count = array();

        //Счетчик рюкзака
        if ($model->id_user == Yii::app()->user->id) {
            $count['backpack'] = UserItems::model()->countByAttributes(array(
                'id_user' => Yii::app()->user->id,
                'status' => ITEM_IN_BACKPACK,
            ));
        }

        for ($i = 1; $i < 13; $i++) {
            $criteria = new CDbCriteria;
            $criteria->select = array('id_item', 'name', 'type', 'level', 'img', 'status', 'id_user', '(strength+energy+regeneration+health+armor+enchant_strength+enchant_energy+enchant_regeneration+enchant_health+enchant_armor) as sum');
            $criteria->compare('id_user', $id);
            $criteria->compare('type', $i);
            $criteria->compare('status', ITEM_ON_BODY);
            $user_item = UserItems::model()->find($criteria);
            if ($user_item) {
                $items[$i]['id'] = $user_item->id_item;
                $items[$i]['name'] = UserItems::itemName($user_item->id_item);
                $items[$i]['level'] = $user_item->level;
                $items[$i]['status'] = $user_item->status;
                $items[$i]['id_user'] = $user_item->id_user;
                $items[$i]['img'] = $user_item->img;
                if ($id != Yii::app()->user->id) {
                    $compare_item = UserItems::findUserItem($user_item);
                    if ($compare_item)
                        $items[$i]['better'] = ($user_item->sum > $compare_item->sum ? $user_item->sum - $compare_item->sum : false);
                    else
                        $items[$i]['better'] = $user_item->sum; 
                }
                else 
                    $items[$i]['better'] = 0;
            } else {
                $items[$i]['id'] = 0;
                $items[$i]['img'] = 0;
                $items[$i]['better'] = 0;
            }
            $items[$i]['type'] = FuncHelper::getType($i);
        }

        $this->render('body', array(
            'model' => $model,
            'items' => $items,
            'count' => $count
        ));
    }

    public function actionBackpack() {
        $model = Users::model()->findByPk(Yii::app()->user->id);
        //Счетчики
        $count['store'] = UserItems::model()->countByAttributes(array(
            'id_user' => Yii::app()->user->id,
            'status' => ITEM_IN_STORE,
        ));
        $count['backpack'] = UserItems::model()->countByAttributes(array(
            'id_user' => Yii::app()->user->id,
            'status' => ITEM_IN_BACKPACK,
        ));

        $criteria = new CDbCriteria;
        $criteria->select = array('id_item', 'level', 'type', 'img', 'personal', 'status', '(strength+energy+regeneration+health+armor+enchant_strength+enchant_energy+enchant_regeneration+enchant_health+enchant_armor) as sum');
        $criteria->compare('id_user', Yii::app()->user->id);
        $criteria->compare('status', ITEM_IN_BACKPACK);
        $user_items = UserItems::model()->findAll($criteria);
        
        $this->render('backpack', array(
            'model' => $model, 
            'items' => $user_items, 
            'count' => $count
        ));
    }

    public function actionStore() {
        $model = Users::model()->findByPk(Yii::app()->user->id);
        //Счетчик рюкзака
        $count['store'] = UserItems::model()->countByAttributes(array(
            'id_user' => Yii::app()->user->id,
            'status' => ITEM_IN_STORE,
        ));
        $count['backpack'] = UserItems::model()->countByAttributes(array(
            'id_user' => Yii::app()->user->id,
            'status' => ITEM_IN_BACKPACK,
        ));

        $criteria = new CDbCriteria;
        $criteria->select = array('id_item', 'level', 'type', 'img', 'personal', 'status', '(strength+energy+regeneration+health+armor+enchant_strength+enchant_energy+enchant_regeneration+enchant_health+enchant_armor) as sum');
        $criteria->compare('id_user', Yii::app()->user->id);
        $criteria->compare('status', ITEM_IN_STORE);
        $user_items = UserItems::model()->findAll($criteria);
        $this->render('store', array('model' => $model, 'items' => $user_items, 'count' => $count));
    }

    public function actionOptions() {
        $change = Yii::app()->getRequest()->getParam('change', 'changePassword');
        $model = Users::findUser();
        $options = new OptionsForm();
        if ($change == 'login')
            $options->setScenario('changeLogin');
        elseif ($change == 'diplomat') {
            if ($model->money < 5000) {
                Yii::app()->user->setFlash('error', 'У вас недостаточно денег.');
                $this->redirect(Yii::app()->request->urlReferrer);
                Yii::app()->end();
            } else {
                $model->money -= 5000;
                $model->diplomat = 1;
                if (!$model->save(false)) {
                    throw new CHttpException(500, Yii::t('layout', 'Ошибка при сохранении пользователя!'));
                }
                Yii::app()->user->setFlash('info', 'Вы выучили навык Дипломатия');
            }
        } elseif ($change == 'class') {
            if ($model->money < 1000) {
                Yii::app()->user->setFlash('error', 'У вас недостаточно денег.');
                $this->redirect(Yii::app()->request->urlReferrer);
                Yii::app()->end();
            } else {
                $model->money -= 1000;
                $model->class = ($model->class < 2 ? 2 : 1);
                if (!$model->save(false)) {
                    throw new CHttpException(500, Yii::t('layout', 'Ошибка при сохранении пользователя!'));
                }
                Yii::app()->user->setFlash('info', 'Вы сменили свой класс');
            }
        } elseif ($change == 'side') {
            if ($model->money < 5000) {
                Yii::app()->user->setFlash('error', 'У вас недостаточно денег.');
                $this->redirect(Yii::app()->request->urlReferrer);
                Yii::app()->end();
            }
            elseif ($model->guild_id) {
                Yii::app()->user->setFlash('error', 'Вы не сможете сменить сторону пока не выйдите из гильдии.');
                $this->redirect(Yii::app()->request->urlReferrer);
                Yii::app()->end();
            } else {
                $model->money -= 5000;
                $model->side = ($model->side < 2 ? 2 : 1);
                if (!$model->save(false)) {
                    throw new CHttpException(500, Yii::t('layout', 'Ошибка при сохранении пользователя!'));
                }
                Yii::app()->user->setFlash('info', 'Вы сменили свою сторону');
            }
        } elseif ($change == 'sex') {
            if ($model->money < 500) {
                Yii::app()->user->setFlash('error', 'У вас недостаточно денег.');
                $this->redirect(Yii::app()->request->urlReferrer);
                Yii::app()->end();
            } else {
                $model->money -= 500;
                $model->sex = ($model->sex < 1 ? 1 : 0);
                if (!$model->save(false)) {
                    throw new CHttpException(500, Yii::t('layout', 'Ошибка при сохранении пользователя!'));
                }
                Yii::app()->user->setFlash('info', 'Вы сменили свой пол');
            }
        } else {
            $options->setScenario('changePassword');
            if (isset($_POST['OptionsForm'])) {
                $options->attributes = $_POST['OptionsForm'];
                if ($options->validate()) {
                    //Забираем у пользователя то, что он отправил
                    if ($options->password_new) {
                        $model->password = md5(md5($options->password_new));
                    } elseif ($options->login) {
                        if ($model->money < 5000) {
                            Yii::app()->user->setFlash('error', 'У вас недостаточно денег.');
                            $this->redirect(Yii::app()->request->urlReferrer);
                            Yii::app()->end();
                        }
                        $model->money -= 5000;
                    }

                    if (!$model->save(false)) {
                        throw new CHttpException(500, Yii::t('layout', 'Ошибка при сохранении пользователя!'));
                    }
                    if (isset($_GET['change']) && $_GET['change'] == 'login')
                        Yii::app()->user->setFlash('info', 'Ваш ник изменен');
                    else
                        Yii::app()->user->setFlash('info', 'Ваш пароль изменен');
                    $this->redirect('/user/options/');
                    Yii::app()->end();
                }
            }
        }

        $this->render('options', array('model' => $model, 'options' => $options));
    }
    
    public function actionSave() {
        $user = Users::findUser();
        if ($user->id_role == 8) {
            $save = new SaveForm();
            $save->login = $user->login;
            if (isset($_POST['SaveForm'])) {
                $save->attributes = $_POST['SaveForm'];
                $save->login = trim($save->login);
                if ($save->validate()) {
                    $user->attributes = $save->attributes;
                    $user->id_role = 1;
                    if (!isset($_SERVER['HTTP_X_HOST'])) {
                        $user->password = md5(md5($save->password));
                    }
                    else {
                        $user->password = md5(md5(md5('pumpit'.$_SESSION['pumpit_id'])));
                    }
                    if ($user->sex == 0) $user->avatar = 1;
                    else $user->avatar = 2;
                    if (!$user->save(false)) {
                        throw new CHttpException(500, Yii::t('layout', 'Ошибка при сохранении пользователя!'));
                    }
                    Yii::app()->user->setFlash('info', 'Вы успешно сохранили персонажа. Приятной игры!');
                    $this->redirect('/user/');
                    Yii::app()->end();
                }
            }
            $this->render('save', array('user' => $user, 'save' => $save));  
        }
        else {
            $this->redirect('/user/');
            Yii::app()->end();
        }
    }

    public function actionPremium($type = null) {
        $model = Users::findUser();
        if ($type && intval($type) > 0 && intval($type) < 6) {
            $price = FuncHelper::premiumPrices($type);
            if (!$price || $model->money < $price) {
                Yii::app()->user->setFlash('error', 'У вас недостаточно денег.');
                $this->redirect(Yii::app()->request->urlReferrer);
                Yii::app()->end();
            }
            $model->money -= $price;
            if ($model->premium_time > time())
                $model->premium_time += FuncHelper::premiumTimes($type);
            else
                $model->premium_time = (time() + FuncHelper::premiumTimes($type));
            if (!$model->save(false)) {
                throw new CHttpException(500, Yii::t('layout', 'Ошибка при сохранении пользователя!'));
            }
            Yii::app()->user->setFlash('info', 'Премиум активирован');
            $this->redirect('/user/premium/');
            Yii::app()->end();
        }
        $this->render('premium', array(
            'model' => $model,
        ));
    }

    public function actionDestroy() {
        $user = Users::model()->findByPk(Yii::app()->user->id);
        $type = Yii::app()->request->getParam('type');
        if ($type) {
            if ($type > 4) 
                $user->backpack_destroy = 0;
            else 
                $user->backpack_destroy = $type;
            if (!$user->save(false)) {
                throw new CHttpException(500, Yii::t('layout', 'Ошибка при сохранении пользователя!'));
            }
            Yii::app()->user->setFlash('info', 'Изменения сохранены');
            $this->redirect('/user/destroy/');
        }
        $this->render('destroy', array(
            'user' => $user,
        ));
    }
    
    public function actionSetBan($id) {
        $model = new AdminForm('banUser');
        $user = Users::model()->findByPk($id);
        if (isset($_POST['AdminForm'])) {
            $model->attributes = $_POST['AdminForm'];
            if ($model->validate()) {
                $ban = new UserBan();
                $ban->attributes = $model->attributes;
                $ban->id_user = $id;
                if ($model->type == 2) {
                    $ban->time = time() + 3600 * 24 * $model->number;
                }
                elseif ($model->type == 1) {
                    $ban->time = time() + 3600 * $model->number;
                } 
                else 
                    $ban->time = 0;
                if (!$ban->save(false)) {
                    throw new CHttpException(500, Yii::t('layout', 'Ошибка при выдаче бана'));
                }
                $user->id_role = 7;
                $user->id_ban = $ban->id_ban;
                if (!$user->save(false)) {
                    throw new CHttpException(500, Yii::t('layout', 'Ошибка при выдаче бана'));
                }
                //do anything here
                echo CJSON::encode(array(
                    'status'=>'success',
                    'reload'=>true,
                ));
                Yii::app()->end();
             }
             else{
                $error = CActiveForm::validate($model);
                if($error!='[]')
                    echo $error;
                Yii::app()->end();
             }
        }
        $this->renderPartial('ban', array(
            'model'=>$model,
        ));
    }
    public function actionUnBan($id) {
        $user = Users::model()->findByPk($id);
        $user->id_ban = null;
        if (!$user->save(false)) {
            throw new CHttpException(500, Yii::t('layout', 'Ошибка при снятии бана'));
        }
        echo "true";
        Yii::app()->end();
    }

}
