<?php

class HeroController extends Controller {

    public function accessRules() {
        return array(
            array('allow',
                'actions' => array('index', 'equipment', 'bag', 'put', 'pull', 'info', 'del', 'inventory', 'stats'),
                'users' => array('@'),
            ),
            array('deny',
                'users' => array('*'),
                'deniedCallback' => array(Yii::app()->controller, 'redirectToHome'),
            )
        );
    }

    public function actions() {
        return array(
            'page' => array(
                'class' => 'CViewAction',
            ),
        );
    }

    /*

      SELECT sum(`health`), sum(`attack`), sum(`deff`), sum(`accuracy`), sum(`dodge`)
      FROM (
      SELECT `health`,`attack`,`deff`,`accuracy`,`dodge` FROM `inventory` WHERE `user` = '1' AND `put` = '1'
      UNION
      SELECT `health`,`attack`,`deff`,`accuracy`,`dodge` FROM `users` WHERE `id` = '1'
      ) as `total`

     */

    public function actionStats() {
        $row = Users::stats();
        $this->render('stats', array(
            'health' => $row['sum(`health`)'],
            'attack' => $row['sum(`attack`)'],
            'deff' => $row['sum(`deff`)'],
            'accuracy' => $row['sum(`accuracy`)'],
            'dodge' => $row['sum(`dodge`)'],
            'crit' => $row['sum(`crit`)'],
            'acrit' => $row['sum(`acrit`)'],
        ));
    }

    public function actionDel($id) {
        $item = Inventory::findInventory($id);
        if ($item->user == Yii::app()->user->id) {
            $item->delete();
            Yii::app()->user->setFlash('success', "Вы успешно выкинули предмет");
            $this->redirect(array('hero/inventory'));
        } else {
            Yii::app()->user->setFlash('error', "Предмет не найден");
            $this->redirect(array('hero/inventory'));
        }
    }

    public function actionPut($id) {
        $users_item = Inventory::findInventory($id);
        $put = Inventory::putOn($id);
        if ($put == 1) {
            $user = Users::findUser($users_item->user);
            if ($user->level >= $users_item->level) {
                Yii::app()->user->setFlash('success', "Вы успешно надели предмет");
                Inventory::model()->updateByPk($id, array('put' => '1'));
                $this->redirect(array('hero/inventory'));
            } else {
                Yii::app()->user->setFlash('error', "Вам необходимо иметь " . $users_item->level . " уровень, чтобы одеть данный предмет");
                $this->redirect(array('hero/inventory'));
            }
        }
        if ($put == 4) {
            Yii::app()->user->setFlash('error', "Этот предмет нельзя одеть!");
            $this->redirect(array('hero/inventory'));
        }
        if ($put == 0) {
            Yii::app()->user->setFlash('error', "Прежде чем одевать новый предмет, снимите старый!");
            $this->redirect(array('hero/inventory'));
        }
        if ($put == 3) {
            $this->redirect(array('hero/inventory'));
        }
    }

    public function actionPull($id) {
        $users_item = Inventory::findInventory($id);
        $put = Inventory::pullOff($id);
        if ($put == 1) {
            Yii::app()->user->setFlash('success', "Вы успешно сняли предмет");
            Inventory::model()->updateByPk($id, array('put' => '0'));
            $this->redirect(array('hero/inventory'));
        }
        if ($put == 0) {
            Yii::app()->user->setFlash('error', "Нечего снимать");
            $this->redirect(array('hero/inventory'));
        }
        if ($put == 3) {
            $this->redirect(array('hero/inventory'));
        }
    }

    public function actionInventory() {

        $criteria = new CDbCriteria();
        $criteria->condition = 'user = :user AND ((type >= 1 AND type <= 5) OR type = 8 OR type = 7 OR type = 10)';
        $criteria->params = array(':user' => Yii::app()->user->id);
        $count = Inventory::model()->count($criteria);
        $pages = new CPagination($count);
        $pages->pageSize = 6;
        $pages->applyLimit($criteria);
        $models = Inventory::model()->findAll($criteria);
        $user = Users::model()->findUser();
        $count_items = Inventory::model()->count();

        $this->render('inventory', array(
            'models' => $models,
            'pages' => $pages,
            'level' => $user->level,
            'count_items' => $count_items,
        ));
    }

    public function actionUseEnergy($id) {
        $user = Users::model()->findUser();
        if ($user->energy == $user->energy_full) {
            Yii::app()->user->setFlash('error', 'Ваша энергия полностью заполнена');
        } else {
            echo Users::useEnergy($id);
        }
        if (intval($_GET['fight']) == 1)
            $this->redirect(array('arena/index'));
        $this->redirect(array('hero/inventory'));
    }

    public function actionIndex() {
        $user = Users::findUser();
        $head = Inventory::model()->findByAttributes(array('put' => '1', 'type' => '1', 'user' => Yii::app()->user->id));
        $body = Inventory::model()->findByAttributes(array('put' => '1', 'type' => '2', 'user' => Yii::app()->user->id));
        $pants = Inventory::model()->findByAttributes(array('put' => '1', 'type' => '3', 'user' => Yii::app()->user->id));
        $shoes = Inventory::model()->findByAttributes(array('put' => '1', 'type' => '4', 'user' => Yii::app()->user->id));
        $weapon = Inventory::model()->findByAttributes(array('put' => '1', 'type' => '5', 'user' => Yii::app()->user->id));
        $potion = Inventory::model()->findByAttributes(array('put' => '1', 'type' => '7', 'user' => Yii::app()->user->id));
        $amulet = Inventory::model()->findByAttributes(array('put' => '1', 'type' => '8', 'user' => Yii::app()->user->id));
        $procent_exp = new Helper;
        $this->render('index', array(
            'user' => $user,
            'head' => $head,
            'body' => $body,
            'belt' => $belt,
            'pants' => $pants,
            'shoes' => $shoes,
            'potion' => $potion,
            'weapon' => $weapon,
            'amulet' => $amulet,
            'procent_exp' => $procent_exp->stripsExp,
        ));
    }

    public function actionInfo($id) {
        $item = Inventory::findInventory($id);
        $owner = Users::findUser($item->user);
        $this->render('info', array(
            'item' => $item,
            'owner' => $owner->login,
        ));
    }

    function actionSettings() {
        $model = Users::findUser();

        if (isset($_POST['Users']['login'])) {
            $model->attributes = $_POST['Users'];
            if ($model->validate()) {
                $isset_name = Users::model()->findByAttributes(array('login' => htmlspecialchars($_POST['Users']['login'])));
                if (!$isset_name) {
                    $model->save(false);
                    Yii::app()->user->setFlash('success', 'Вы успешно сменили логин');
                } else {
                    Yii::app()->user->setFlash('error', 'Такой логин уже существует');
                }
                $this->redirect(array('hero/settings'));
            }
        }

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

    function actionHero($id) {
        $user = Users::findUser($id);
        
        if ($user->id == Yii::app()->user->id) {
            $this->redirect(array('hero/index'));
        }
        
        $head = Inventory::model()->findByAttributes(array('put' => '1', 'type' => '1', 'user' => $user->id));
        $body = Inventory::model()->findByAttributes(array('put' => '1', 'type' => '2', 'user' => $user->id));
        $pants = Inventory::model()->findByAttributes(array('put' => '1', 'type' => '3', 'user' => $user->id));
        $shoes = Inventory::model()->findByAttributes(array('put' => '1', 'type' => '4', 'user' => $user->id));
        $weapon = Inventory::model()->findByAttributes(array('put' => '1', 'type' => '5', 'user' => $user->id));
        $potion = Inventory::model()->findByAttributes(array('put' => '1', 'type' => '7', 'user' => $user->id));
        $amulet = Inventory::model()->findByAttributes(array('put' => '1', 'type' => '8', 'user' => $user->id));

        $this->render('user', array(
            'user' => $user,
            'head' => $head,
            'body' => $body,
            'belt' => $belt,
            'pants' => $pants,
            'shoes' => $shoes,
            'potion' => $potion,
            'weapon' => $weapon,
            'amulet' => $amulet,

        ));
    }

}
