<?php

class GuildController extends Controller {

    public function accessRules() {
        return array(
            array('deny',
                'roles' => array('banned'),
                'deniedCallback' => array(Yii::app()->controller, 'redirectToHome'),
            ),
            array('allow',
                'actions' => array('index', 'storage', 'buildings', 'buildingInfo', 'inviteAnswer', 'create', 'exit', 'invite', 'journal', 'kick', 'lower', 'online', 'swap', 'settings', 'upper', 'view'),
                'users' => array('@'),
            ),
            array('deny',
                'users' => array('*'),
                'deniedCallback' => array(Yii::app()->controller, 'redirectToHome'),
            )
        );
    }

    public function actionIndex() {
        $user = Users::findUser();
        if ($user->guild_id) {
            $this->redirect(array('view', 'id' => $user->guild_id));
            Yii::app()->end();
        }
        $this->render('index');
    }

    public function actionCreate() {
        $user = Users::findUser();
        if ($user->guild_id) {
            $this->redirect(Yii::app()->user->returnUrl);
            Yii::app()->end();
        } elseif ($user->level < 10) {
            Yii::app()->user->setFlash('info', 'Создавать гильдию можно с 10 уровня.');
            $this->redirect('/guild/index');
            Yii::app()->end();
        }
        $model = new Guilds;
        if (isset($_POST['Guilds'])) {
            $model->attributes = $_POST['Guilds'];
            $model->money = $user->money;
            if ($model->validate()) {
                $model->side = $user->side;
                $model->save();
                $user->guild_invite = null;
                $user->guild_id = $model->id_guild;
                $user->guild_rank = 5;
                $user->money -= $model->price * 100;
                $user->guild_time = time();
                if (!$user->save(false)) {
                    throw new CHttpException(500, Yii::t('layout', 'Ошибка при сохранении пользователя!'));
                }
                $this->redirect(array('view', 'id' => $model->id_guild));
            }
        }
        $this->render('create', array(
            'model' => $model,
        ));
    }

    public function actionView($id) {
        $model = $this->loadModel($id);
        $user = Users::findUser();
        $max = BattleHelper::maxGuildXP($model->level);
        $warriors = $healers = 0;
        foreach ($model->users as $member) {
            if ($member->class == 1 && $member->last_visit > (time() - 60 * 60))
                $warriors++;
            elseif ($member->class == 2 && $member->last_visit > (time() - 60 * 60))
                $healers++;
        }
        if (isset($_POST['Guilds'])) {
            $model->info = $_POST['Guilds']['text'];
            if ($model->validate()) {
                $model->info_creator = Yii::app()->user->id;
                $model->info_time = time();
                if (!$model->save(false)) {
                    throw new CHttpException(500, Yii::t('layout', 'Произошла ошибка при работе с БД!'));
                }
                $this->redirect(array('view', 'id' => $model->id_guild));
            }
        }
        $min = BattleHelper::maxGuildXP($model->level - 1);
        $max = BattleHelper::maxGuildXP($model->level);

        if ($model->xp > 0) {
            $percent = round(($model->xp - $min) * 100 / ($max - $min));
        } else
            $percent = 0;
        $xp = array(
            'percent' => $percent,
            'max' => $max,
        );

        $this->render('view', array(
            'model' => $model,
            'xp' => $xp,
            'user' => $user,
            'warriors' => $warriors,
            'healers' => $healers,
        ));
    }
    
    public function actionStorage($id) {
        $model = $this->loadModel($id);
        $user = Users::findUser();
        $types = array(500=>500, 1000=>1000, 5000=>5000, 10000=>10000);
        if (isset($_GET['type']) && in_array($_GET['type'], $types)) {
            $value = $_GET['type'];
            if ($value > $user->iron)
               Yii::app()->user->setFlash('error', 'Недостаточно железа');
            else {
                $user->iron -= $value;
                $model->iron += $value;
                if (!$user->save(false)) {
                    throw new CHttpException(500, Yii::t('layout', 'Произошла ошибка при работе с БД!'));
                }
                if (!$model->save(false)) {
                    throw new CHttpException(500, Yii::t('layout', 'Произошла ошибка при работе с БД!'));
                }
                $history = new GuildsHistory();
                $history->id_guild = $model->id_guild;
                $history->type = 2;
                $history->subtype = 1;
                $history->info = $value;
                $history->id_user = $user->id_user;
                if (!$history->save(false)) {
                    throw new CHttpException(500, Yii::t('layout', 'Произошла ошибка при работе с БД!'));
                }
                Yii::app()->user->setFlash('info', 'Вы положили в Тайник <img src="/images/icons/iron.png" alt="*"> '.$value.' железа');
            }
            $this->redirect(array('guild/storage', 'id' => $model->id_guild));
        }
        
        $this->render('storage', ['model' => $model, 'types' => $types]);
    }
    
    public function actionBuildings($id) {
        $model = $this->loadModel($id);
        $buildings = Buildings::model()->findAll();
		$user = Users::findUser();
        $this->render('buildings', ['model' => $model, 'buildings' => $buildings, 'user' => $user]);
    }
    
    public function actionBuildingInfo($id, $build) {
        $model = $this->loadModel($id);
        $info = $this->loadModel($build, 'Buildings');
        $user = Users::findUser();
        $building = GuildsBuildings::model()->findByPk(array('id_guild'=>$id, 'id_building'=>$build));
        $types = array(500=>500, 1000=>1000, 5000=>5000, 10000=>10000);
        $progress = array();
        if (!empty($building)) {
            $progress['need'] = DataHelper::guildMainPrices($building->level);
            $progress['percent'] = round($building->iron*100/$progress['need']);
        }
        else {
            $building = new GuildsBuildings();
            $building->id_guild = $id;
            $building->id_building = $build;
            $building->save(false);
            $progress['need'] = DataHelper::guildMainPrices(0);
            $progress['percent'] = 0;
        }
        if (isset($_GET['type']) && in_array($_GET['type'], $types) && $building->level < $model->level) {
            $value = $_GET['type'];
            if ($value > $model->iron)
               Yii::app()->user->setFlash('error', 'Недостаточно железа');
            else {
                $model->iron -= $value;
                $building->iron += $value;
                if ($building->iron >= $progress['need']) {
                    $building->iron -= $progress['need'];
                    $building->level++;
                }
                if (!$building->save(false)) {
                    throw new CHttpException(500, Yii::t('layout', 'Произошла ошибка при работе с БД!'));
                }
                if (!$model->save(false)) {
                    throw new CHttpException(500, Yii::t('layout', 'Произошла ошибка при работе с БД!'));
                }
                $history = new GuildsHistory();
                $history->id_guild = $model->id_guild;
                $history->type = 2;
                $history->subtype = 2;
                $history->info = $value;
                $history->id_user = $user->id_user;
                if (!$history->save(false)) {
                    throw new CHttpException(500, Yii::t('layout', 'Произошла ошибка при работе с БД!'));
                }
                Yii::app()->user->setFlash('info', 'Вы добавили <img src="/images/icons/iron.png" alt="*"> '.$value.' железа');
            }
            $this->redirect(array('guild/buildingInfo', 'id'=>$id, 'build'=>$build));
        }
        if (isset($_GET['do'])) {
            $value = $building->level*100;
            $bonus = $building->level*0.5;
            if ($value > $user->iron)
               Yii::app()->user->setFlash('error', 'Недостаточно железа');
            else {
                $user->iron -= $value;
                $user->guild_buff = $bonus;
                $user->guild_buff_time = time() + 2*60*60;
                if (!$user->save(false)) {
                    throw new CHttpException(500, Yii::t('layout', 'Произошла ошибка при работе с БД!'));
                }
                Yii::app()->user->setFlash('info', 'Вы активировали  Камень ярости на 2 часа');
            }
            $this->redirect(array('guild/buildingInfo', 'id'=>$id, 'build'=>$build));
        }
        $this->render('building', ['model' => $model, 'building' => $building, 'info' => $info, 'progress' => $progress, 'types' => $types, 'user' => $user]);
    }
    
    public function actionOnline($id) {
        $model = $this->loadModel($id);
        $criteria = new CDbCriteria();
        $criteria->condition = 't.last_visit > ' . (time() - 60 * 60);
        $criteria->compare('t.guild_id', $id);
        $criteria->order = 't.guild_rank DESC';
        $count = Users::model()->count($criteria);
        $pages = new CPagination($count);
        // элементов на страницу
        $pages->pageSize = 10;
        $pages->route = '/guild/online';
        $pages->params = array('id' => $id);
        $pages->applyLimit($criteria);

        $models = Users::model()->findAll($criteria);
        $this->render('online', array('models' => $models, 'pages' => $pages));
    }

    public function actionInvite($id) {
        $user = Users::findUser();
        $member = Users::findUser($id);
        $model = $this->loadModel($user->guild_id);
        if (!$member->guild_id && $user->guild_id && $user->guild_rank >= $model->rank_invite && $member->side == $user->side && count($model->users) < 10) {
            $member->guild_invite = $model->id_guild;
            $member->guild_rank = 1;
            if (!$member->save(false)) {
                throw new CHttpException(500, Yii::t('layout', 'Произошла ошибка при работе с БД!'));
            }
            Yii::app()->user->setFlash('info', Users::getFullLogin($id) . ' отправлено приглашение');
        }
        $this->redirect(array('/user/index/', 'id' => $id));
        Yii::app()->end();
    }

    public function actionInviteAnswer($type) {
        $user = Users::findUser();
        $model = $this->loadModel($user->guild_invite);
        if ($user->guild_invite && !$user->guild_id && $model->side == $user->side && $type == 'accept' && count($model->users) < 10) {
            $user->guild_id = $model->id_guild;
            if ($model->level < 2) {
                $user->guild_rank = 1;
            } else {
                $user->guild_rank = 0;
            }
            $history = new GuildsHistory();
            $history->id_guild = $model->id_guild;
            $history->type = 1;
            $history->subtype = 1;
            $history->id_target = $user->id_user;
            if (!$history->save(false)) {
                throw new CHttpException(500, Yii::t('layout', 'Произошла ошибка при работе с БД!'));
            }
            $user->guild_time = time();
            $user->guild_invite = null;
            if (!$user->save(false)) {
                throw new CHttpException(500, Yii::t('layout', 'Произошла ошибка при работе с БД!'));
            }
            $this->redirect(array('/guild/view', 'id' => $model->id_guild));
            Yii::app()->end();
        } elseif ($type == 'cancel') {
            $user->guild_invite = null;
            if (!$user->save(false)) {
                throw new CHttpException(500, Yii::t('layout', 'Произошла ошибка при работе с БД!'));
            }
            $this->redirect(array('/user/index'));
            Yii::app()->end();
        } else {
            Yii::app()->user->setFlash('info', 'Вы не можете вступить в гильдию, достигнут лимит участников.');
            $user->guild_invite = null;
            if (!$user->save(false)) {
                throw new CHttpException(500, Yii::t('layout', 'Произошла ошибка при работе с БД!'));
            }
            $this->redirect(array('/site/index'));
        }
        Yii::app()->end();
    }

    public function actionExit() {
        $user = Users::findUser();
        $model = $this->loadModel($user->guild_id);
        if ($user->guild_rank < 5 && $user->guild_id == $model->id_guild) {
            $user->guild_id = null;
            $user->guild_rank = null;
            $user->guild_xp = null;
            if (!$user->save(false)) {
                throw new CHttpException(500, Yii::t('layout', 'Произошла ошибка при работе с БД!'));
            }
            $history = new GuildsHistory();
            $history->id_guild = $model->id_guild;
            $history->type = 1;
            $history->subtype = 2;
            $history->id_target = $user->id_user;
            if (!$history->save(false)) {
                throw new CHttpException(500, Yii::t('layout', 'Произошла ошибка при работе с БД!'));
            }
            Yii::app()->user->setFlash('info', 'Вы вышли из гильдии');
        }
        $this->redirect(Yii::app()->user->returnUrl);
        Yii::app()->end();
    }

    public function actionKick($id) {
        $user = Users::findUser();
        $member = Users::findUser($id);
        $model = $this->loadModel($user->guild_id);
        if ($user->guild_rank >= $model->rank_kick && $user->guild_id == $member->guild_id && $member->guild_rank < $user->guild_rank) {
            $member->guild_id = null;
            $member->guild_rank = null;
            $member->guild_xp = null;
            if (!$member->save(false)) {
                throw new CHttpException(500, Yii::t('layout', 'Произошла ошибка при работе с БД!'));
            }
            $history = new GuildsHistory();
            $history->id_guild = $user->guild_id;
            $history->type = 1;
            $history->subtype = 5;
            $history->id_target = $member->id_user;
            if (!$history->save(false)) {
                throw new CHttpException(500, Yii::t('layout', 'Произошла ошибка при работе с БД!'));
            }
            Yii::app()->user->setFlash('info', Users::getFullLogin($id) . ' исключен из гильдии');
        }
        $this->redirect(array('/guild/view/', 'id' => $model->id_guild, 'action' => 'moderate'));
        Yii::app()->end();
    }

    public function actionUpper($id) {
        $user = Users::findUser();
        $member = Users::findUser($id);
        $model = $this->loadModel($user->guild_id);
        if ($user->guild_rank >= 3 && $member->guild_rank < $user->guild_rank && $member->guild_rank < 4) {
            if ($model->level < 4 && $member->guild_rank == 3) {
                $this->redirect(array('/guild/view/', 'id' => $model->id_guild, 'action' => 'moderate'));
                Yii::app()->end();
            } elseif ($model->level > 3 && $member->guild_rank == 4) {
                $this->redirect(array('/guild/view/', 'id' => $model->id_guild, 'action' => 'moderate'));
                Yii::app()->end();
            } elseif ($model->level < 3 && $member->guild_rank == 1) {
                $member->guild_rank = 3;
            } else {
                $member->guild_rank += 1;
            }
            if (!$member->save(false)) {
                throw new CHttpException(500, Yii::t('layout', 'ПРоизошла ошибка при работе с БД!'));
            }
            $history = new GuildsHistory();
            $history->id_guild = $user->guild_id;
            $history->type = 1;
            $history->subtype = 3;
            $history->info = $member->guild_rank;
            $history->id_target = $member->id_user;
            if (!$history->save(false)) {
                throw new CHttpException(500, Yii::t('layout', 'Произошла ошибка при работе с БД!'));
            }
            Yii::app()->user->setFlash('info', Users::getFullLogin($id) . ' повышен');
        }
        $this->redirect(array('/guild/view/', 'id' => $model->id_guild, 'action' => 'moderate'));
        Yii::app()->end();
    }

    public function actionLower($id) {
        $user = Users::findUser();
        $member = Users::findUser($id);
        $model = $this->loadModel($user->guild_id);
        if ($user->guild_rank >= 3 && $member->guild_rank > 0 && $member->guild_rank < $user->guild_rank) {
            if ($model->level < 3 && $member->guild_rank == 3) {
                $member->guild_rank = 1;
            } else {
                $member->guild_rank -= 1;
            }
            if (!$member->save(false)) {
                throw new CHttpException(500, Yii::t('layout', 'ПРоизошла ошибка при работе с БД!'));
            }
            $history = new GuildsHistory();
            $history->id_guild = $user->guild_id;
            $history->type = 1;
            $history->subtype = 4;
            $history->info = $member->guild_rank;
            $history->id_target = $member->id_user;
            if (!$history->save(false)) {
                throw new CHttpException(500, Yii::t('layout', 'Произошла ошибка при работе с БД!'));
            }
            Yii::app()->user->setFlash('info', Users::getFullLogin($id) . ' понижен');
        }
        $this->redirect(array('/guild/view/', 'id' => $model->id_guild, 'action' => 'moderate'));
        Yii::app()->end();
    }

    public function actionSwap($id) {
        $user = Users::findUser();
        $member = Users::findUser($id);
        $model = $this->loadModel($user->guild_id);
        if ($user->guild_rank == 5 && ($model->level < 4 && $member->guild_rank > 2 || $model->level > 3 && $member->guild_rank > 3)) {
            $user->guild_rank = $member->guild_rank;
            if (!$user->save(false)) {
                throw new CHttpException(500, Yii::t('layout', 'ПРоизошла ошибка при работе с БД!'));
            }
            $member->guild_rank = 5;
            if (!$member->save(false)) {
                throw new CHttpException(500, Yii::t('layout', 'ПРоизошла ошибка при работе с БД!'));
            }

            $history = new GuildsHistory();
            $history->id_guild = $user->guild_id;
            $history->type = 1;
            $history->subtype = 6;
            $history->info = $member->guild_rank;
            $history->id_target = $member->id_user;
            if (!$history->save(false)) {
                throw new CHttpException(500, Yii::t('layout', 'Произошла ошибка при работе с БД!'));
            }
            Yii::app()->user->setFlash('info', Users::getFullLogin($id) . ' новый лидер гильдии');
        }
        $this->redirect(array('/guild/view/', 'id' => $model->id_guild, 'action' => 'moderate'));
        Yii::app()->end();
    }

    public function actionSettings($id) {
        $model = $this->loadModel($id);
        $user = Users::findUser();
        if ($model->id_guild != $user->guild_id || $user->guild_rank < 5) {
            $this->redirect(Yii::app()->user->returnUrl);
            Yii::app()->end();
        }
        if ($model->level < 4) {
            $ranks = array(
                3 => 'капитан',
                5 => 'предводитель'
            );
        } else {
            $ranks = array(
                3 => 'капитан',
                4 => 'командующий',
                5 => 'предводитель'
            );
        }

        if (isset($_POST['Guilds'])) {
            $model->rank_invite = $_POST['Guilds']['rank_invite'];
            $model->rank_kick = $_POST['Guilds']['rank_kick'];
            if ($model->save())
                $this->redirect(array('view', 'id' => $model->id_guild));
        }

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

    public function actionJournal($id) {
        $model = $this->loadModel($id);
        $user = Users::findUser();
        if ($model->id_guild != $user->guild_id) {
            $this->redirect(Yii::app()->user->returnUrl);
            Yii::app()->end();
        }
        $history = new GuildsHistory('search');
        $history->id_guild = $user->guild_id;
        $history->type = Yii::app()->request->getParam('type');
        $this->render('journal', array(
            'model' => $model,
            'history' => $history
        ));
    }

    public function loadModel($id, $model = 'Guilds') {
        $model = $model::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'Запрашиваемая страница не существует');
        return $model;
    }

}
