<?php

class Auction extends CActiveRecord {
    public $price_step;
    public $price_step_gold;
    public $price_step_silver;
    public $min_price;
    public $min_price_gold;
    public $min_price_silver;
    public $max_price;
    public $max_price_gold;
    public $max_price_silver;
    public $max_level;
    public $level;
    public $quality;
    public $type;
    public $show_value;
    public $show;
    public $sort;
    public $name;
    public $all;
    public $trade;
    public $number;

    public function tableName() {
        return 'auction';
    }

    public function rules() {
        return array(
            array('id_item', 'priceValidate', 'on' => 'insert'),
            array('min_price_silver, max_price_silver', 'numerical', 'integerOnly' => true, 'max' => 99, 'on' => 'insert'),
            array('lot', 'priceValidateTrade', 'on' => 'insertTrade'),
            array('number', 'required', 'on' => 'insertTrade'),
            array('number', 'numerical', 'integerOnly' => true, 'min' => 5, 'on' => 'insertTrade'),
            array('id_item, lot, id_user, price, price_out, end, last, 
                        min_price_gold, min_price_silver, max_price_gold, max_price_silver, max_level, price_step, 
                        price_step_gold, price_step_silver, number', 'numerical'),
            array('sort, name, trade', 'type', 'type' => 'string'),
            array('sort, name', 'type', 'type' => 'string', 'on' => 'search'),
            array('level, quality, type, show', 'numerical', 'on' => 'search'),
            array('time, all', 'safe'),
        );
    }

    public function priceValidate() {
        $this->min_price = $this->min_price_gold * 100 + $this->min_price_silver;
        $this->max_price = $this->max_price_gold * 100 + $this->max_price_silver;
        if (!$this->min_price && !$this->max_price) {
            $this->addError('min_price', Yii::t('layout', 'Укажите минимальную цену.'));
            $this->addError('max_price', Yii::t('layout', 'Укажите цену для выкупа.'));
        } elseif ($this->min_price < 5) {
            $this->addError('min_price', Yii::t('layout', 'Минимальная цена должна быть не ниже 5 серебра.'));
        } elseif ($this->max_price < 10) {
            $this->addError('max_price', Yii::t('layout', 'Максимальная цена должна быть не ниже 10 серебра.'));
        } elseif ($this->min_price >= $this->max_price) {
            $this->addError('min_price', Yii::t('layout', 'Минимальная цена должна быть ниже цены выкупа.'));
        }
    }

    public function priceValidateTrade() {
        $this->min_price = $this->min_price_gold * 100 + $this->min_price_silver;
        if (!$this->min_price_gold && !$this->min_price_silver) {
            $this->addError('price_out', Yii::t('layout', 'Укажите цену для ресурса.'));
        }
        if ($this->min_price < 5) {
            $this->addError('price_out', Yii::t('layout', 'Минимальная цена должна быть не ниже 5 серебра.'));
        }
    }

    public function relations() {
        return array(
            'idUser' => array(self::BELONGS_TO, 'Users', 'id_user'),
            'idItem' => array(self::BELONGS_TO, 'UserItems', 'id_item'),
        );
    }

    public function attributeLabels() {
        return array(
            'min_price' => Yii::t('layout', 'Ставка'),
            'min_price_gold' => Yii::t('layout', 'Ставка'),
            'min_price_silver' => Yii::t('layout', 'Ставка'),
            'max_price' => Yii::t('layout', 'Выкуп'),
            'max_price_gold' => Yii::t('layout', 'Выкуп'),
            'level' => Yii::t('layout', 'Уровень'),
            'quality' => Yii::t('layout', 'Бонус'),
            'type' => Yii::t('layout', 'Слот'),
            'show' => Yii::t('layout', 'Показывать'),
            'sort' => Yii::t('layout', 'Сортировка'),
            'name' => Yii::t('layout', 'Название'),
            'price_step' => Yii::t('layout', 'Повысить'),
            'trade' => Yii::t('layout', 'Ресурсы'),
            'number' => Yii::t('layout', 'Количество'),
            'price_out' => Yii::t('layout', 'Выкуп'),
        );
    }

    protected function beforeSave() {
        if (parent::beforeSave()) {
            if ($this->isNewRecord) {
                $this->time = time() + 60 * 60 * 24;
                $this->id_user = Yii::app()->user->id;
            }
            return true;
        } else
            return false;
    }

    public function search() {
        $criteria = new CDbCriteria;
        $criteria->with = array('idItem');
        $criteria->together = true;

        //$criteria->select = array('*', 'idItem.health+idItem.armor+idItem.strength+idItem.regeneration+idItem.energy as idItem.all');
        if ($this->show == 1 && $this->type) {
            $all = UserItems::calcAllParamsByType($this->type);
            $criteria->condition = '(idItem.health+idItem.armor+idItem.strength+idItem.regeneration+idItem.energy) > ' . $all;
        } elseif ($this->show == 2)
            $criteria->condition = 't.id_user !=' . Yii::app()->user->id;
        elseif ($this->show == 3)
            $criteria->condition = 't.id_user =' . Yii::app()->user->id;
        elseif ($this->show == 4)
            $criteria->condition = 't.last =' . Yii::app()->user->id;

        $criteria->addCondition("`time` > '" . time() . "' AND `lot` = '1' AND `end` < '1'");

        if ($this->name)
            $criteria->compare('idItem.name', $this->name, 'LIKE');
        if ($this->quality)
            $criteria->compare('idItem.quality', $this->quality);
        if ($this->type)
            $criteria->compare('idItem.type', $this->type);
        if ($this->level)
            $criteria->addBetweenCondition('idItem.level', $this->level, $this->max_level);
        if ($this->sort) {
            if ($this->sort == 'all')
                $criteria->order = '(idItem.health+idItem.armor+idItem.strength+idItem.regeneration+idItem.energy) DESC';
            else
                $criteria->order = $this->sort . ' DESC';
        }
        else
            $criteria->order = 't.time DESC';

        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
        ));
    }

    //Поиск для ресурсов
    public function searchTrade($sort = 'iron') {
        $criteria = new CDbCriteria;
        $criteria->select = array('*, `price_out`/IF(`iron` > 0, `iron`, `bottles`) as `price_step`');
        if ($sort == 'my') {
            $criteria->condition = 'id_user = ' . Yii::app()->user->id;
        } else {
            $criteria->condition = $sort . ' > 0';
            $criteria->addCondition("id_user != " . Yii::app()->user->id);
        }

        $criteria->addCondition("`time` > '" . time() . "' AND `lot` = '2' AND `end` < '1'");
        $criteria->order = '`price_step` ASC';

        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
        ));
    }

    /**
     * Returns the static model of the specified AR class.
     * Please note that you should have this exact method in all your CActiveRecord descendants!
     * @param string $className active record class name.
     * @return Files the static model class
     */
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    public static function backItem($model) {
        //Выбираем шмотку из аука
        $item = UserItems::model()->findByPk($model->id_item);
        if (!$item) {
            return false;
        }
        $item->status = ITEM_IN_MAIL;
        if (!$item->save(false)) {
            throw new CHttpException(500, Yii::t('layout', 'Ошибка при операции с предметом!'));
        }

        //Отправляем почту
        $id_dialog = Users::checkDialog(Yii::app()->user->id, 100);
        $mail = new UsersMessages();
        $mail->id_dialog = $id_dialog;
        $mail->id_user = 100;
        $mail->users = Yii::app()->user->id;
        $mail->type = 3;
        $mail->message = 'Посылка (предмет)';
        if (!$mail->save(false)) {
            throw new CHttpException(500, Yii::t('layout', 'Ошибка при отправке почты!'));
        }
        return true;
    }

}
