<?php
class MailController extends Controller {
    public function accessRules() {
        return array(
            array('deny',
                'roles' => array('banned'),
                'deniedCallback' => array(Yii::app()->controller, 'redirectToHome'),
            ),
            array('allow',
                'actions' => array('index', 'list', 'ajaxCheckToggle', 'attachment', 'deleteAll', 'new', 'takeAll', 'view'),
                'users' => array('@'),
            ),
            array('deny',
                'users' => array('*'),
                'deniedCallback' => array(Yii::app()->controller, 'redirectToHome'),
            )
        );
    }

    public function actionIndex($sort = 'in') {
        $model = new UsersDialogs('search');

        $this->render('index', array(
            'model' => $model,
        ));
    }
    
    public function actionList($id) {
        $user = Users::findUser();
        $whom = Users::findUser($id);
        $id_dialog = Users::checkDialog($id);
        $model = $this->loadModel($id_dialog, 'UsersDialogs');
        $messages = new UsersMessages('search');
        $messages->id_dialog = $id_dialog;
        $form = new MailForm();
        
        UsersMessages::model()->updateAll(array('status'=>0),'`id_dialog` = '.$id_dialog.' AND `id_user` != '.Yii::app()->user->id.' AND `type` = 0 AND `status` = 1');
        
        $types = array('message', 'resources', 'items', 'money');
        $type = in_array(Yii::app()->request->getParam('type', 'message'), $types) ? Yii::app()->request->getParam('type', 'message') : 'message';
        
        $items = array();
        if ($type == 'items') {
            $criteria = new CDbCriteria();
            $criteria->compare('id_user', Yii::app()->user->id);
            $criteria->addCondition('personal = 0');
            $criteria->addInCondition('status', array(ITEM_IN_BACKPACK, ITEM_IN_STORE));
            $items = UserItems::model()->findAll($criteria);
        }
        
        if (isset($_POST['MailForm'])) {
            $form->attributes = $_POST['MailForm'];
            if ($type == 'resources') {
                $form->type = 2;
            }
            elseif ($type == 'items') {
                $form->type = 3;
            }
            elseif ($type == 'money') {
                $form->type = 1;
            }
            else {
                $form->type = 0;
            }
            if ($form->validate()) {
                    $form->message = trim($form->message);
                    $mail = new UsersMessages();
                    $mail->attributes = $form->attributes;
                    $mail->id_user = Yii::app()->user->id;
                    $mail->id_dialog = $id_dialog;
                    $mail->users = $id;
                    if ($mail->type == 1) {
                        $money = $form->gold*100+$form->silver;
                        $percent = (round($money/20)>5 ? round($money/20) : 5);
                        $mail->message = 'Посылка (золото)';
                        $mail->money = $money;
                        $user->money -= ($money + $percent);
                    }
                    elseif ($mail->type == 2) {
                        $price = 5*round($form->number/($form->resource == 'iron' ? 10000 : 10));
                        $resource = $form->resource;
                        $mail->message = 'Посылка (ресурсы)';
                        $mail->$resource = $form->number;
                        $user->money -= $price;
                        $user->$resource -= $form->number;
                    }
                    elseif ($mail->type == 3) {
                        $item = UserItems::model()->findByPk($form->item);
                        $item->id_user = $id;
                        $item->status = ITEM_IN_MAIL;
                        if (!$item->save(false)) {
                            throw new CHttpException(500, Yii::t('layout', 'Ошибка при передаче предмета!'));
                        }
                        $mail->message = 'Посылка (предмет)';
                    }
                    else {
                        $user->iron -= 1;
                    }
                    if (!$mail->save(false)) {
                        throw new CHttpException(500, Yii::t('layout', 'Ошибка при отправке почты!'));
                    }
                    if (!$user->save(false)) {
                        throw new CHttpException(500, Yii::t('layout', 'Ошибка при сохранении пользователя!'));
                    }
                $this->redirect(array('/mail/list', 'id'=>$id)); 
                Yii::app()->end();
             }
        }
        $this->render('list', array(
            'messages' => $messages,
            'user' => $user,
            'whom' => $whom,
            'message' => $form,
            'items' => $items,
            'id' => $id,
            'type' => $type
        ));
    }

    public function actionAttachment($id) {
        $criteria = new CDbCriteria();
        $criteria->with = array('users');
        $criteria->compare('users.id_user', Yii::app()->user->id);
        $criteria->compare('t.id_message', $id);
        $criteria->compare('t.status', 1);
        $model = UsersMessages::model()->find($criteria);
        if ($model) {
            $user = Users::findUser();
            if ($model->type == 1) {
                $user->money += $model->money;
            }
            elseif ($model->type == 2) {
                if ($model->iron) {
                    $user->iron += $model->iron;
                }
                else {
                    $user->bottles += $model->bottles;
                }
            }
            elseif ($model->type == 3) {
                $count = UserItems::model()->countByAttributes(array(
                    'id_user'=> Yii::app()->user->id,
                    'status'=> ITEM_IN_BACKPACK,
                ));
                if ($count >= $user->backpack) {
                    echo CJSON::encode(array(
                        'status' => 'error',
                        'error' => 'Сначала освободите рюкзак',
                    ));
                    Yii::app()->end();
                }
                else {
                    $item = UserItems::model()->findByPk($model->item);
                    if (empty($item)) {
                        echo CJSON::encode(array(
                            'status' => 'error',
                            'error' => 'Такой вещи не существует',
                        ));
                        Yii::app()->end();
                    }
                    $item->status = ITEM_IN_BACKPACK;
                    if (!$item->save(false)) {
                        throw new CHttpException(500, Yii::t('layout', 'Ошибка при получении предмета!'));
                    }	
                }
            }
            $model->users = Yii::app()->user->id;
            $model->status = 0;
            if (!$model->save(false)) {
                throw new CHttpException(500, Yii::t('layout', 'Ошибка при получении почты!'));
            }
            if (!$user->save(false)) {
                throw new CHttpException(500, Yii::t('layout', 'Ошибка при сохранении пользователя!'));
            }
            echo CJSON::encode(array(
                'status' => 'success',
            ));
            Yii::app()->end();
        }
    }
    
    public function actionTakeAll() {
        $models = UserMail::model()->findAllByAttributes(array(
                'id_user' => Yii::app()->user->id,
                'whom' => Yii::app()->user->id,
                'new' => 1
            ));
        if (!$models) {
            $this->redirect(array('mail/index'));
            Yii::app()->end();
        }
        $user = Users::model()->findByPk(Yii::app()->user->id);
        
        foreach ($models as $model) {
            if ($model->type == 1) {
                $user->money += $model->money;
            }
            elseif ($model->type == 2) {
                if ($model->iron)
                    $user->iron += $model->iron;
                else
                    $user->bottles += $model->bottles;
            }
            elseif ($model->type == 3) {
                $count = UserItems::model()->countByAttributes(array(
                    'id_user'=> Yii::app()->user->id,
                    'status'=> ITEM_IN_BACKPACK,
                ));
                if ($count >= $user->backpack) {
                    Yii::app()->user->setFlash('info', 'Недостаточно места в рюкзаке');
                    $this->redirect(array('mail/index', 'sort'=>'new'));
                    Yii::app()->end();
                }
                else {
                    $item = UserItems::model()->findByPk($model->items);
                    $item->status = ITEM_IN_BACKPACK;
                    if (!$item->save(false)) {
                        throw new CHttpException(500, Yii::t('layout', 'Ошибка при получении предмета!'));
                    }	
                }
            }
            $model->new = 0;
            if (!$model->save(false)) {
                throw new CHttpException(500, Yii::t('layout', 'Ошибка при получении почты!'));
            }
            if (!$user->save(false)) {
                throw new CHttpException(500, Yii::t('layout', 'Ошибка при сохранении пользователя!'));
            }
        }

        Yii::app()->user->setFlash('info', 'Все посылки получены');
        $this->redirect(array('mail/index'));
        Yii::app()->end();
    }
    
    public function actionDeleteAll() {
        $models = UserMail::model()->deleteAllByAttributes(array(
                'id_user' => Yii::app()->user->id,
                'save' => 0,
                'new' => 0
            ));
        Yii::app()->user->setFlash('info', 'Все сообщения удалены');
        $this->redirect(array('mail/index'));
        Yii::app()->end();
    }
    
    public function loadModel($id, $name = 'UsersMessages') {
        $model = $name::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, Yii::t('layout', 'Страница не найдена!'));
        return $model;
    }
}