<?php

/**
 * This is the model class for table "battles_navigator".
 *
 * The followings are the available columns in table 'battles_navigator':
 * @property string $id_navigator
 * @property string $id_location
 * @property string $near_location
 * @property integer $type_navigator
 * @property integer $side_navigator
 *
 * The followings are the available model relations:
 * @property BattlesLocations $nearLocation
 * @property BattlesLocations $idLocation
 */
class BattlesNavigator extends CActiveRecord {

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return 'battles_navigator';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('id_location, near_location, type_navigator, side_navigator', 'required'),
            array('type_navigator, side_navigator', 'numerical', 'integerOnly' => true),
            array('id_location, near_location', 'length', 'max' => 11),
            // The following rule is used by search().
            // @todo Please remove those attributes that should not be searched.
            array('id_navigator, id_location, near_location, type_navigator, side_navigator', 'safe', 'on' => 'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'nearLocation' => array(self::BELONGS_TO, 'BattlesLocations', 'near_location', 'condition' => 'status = 1'),
            'idLocation' => array(self::BELONGS_TO, 'BattlesLocations', 'id_location', 'condition' => 'status = 1'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'id_navigator' => 'Id Navigator',
            'id_location' => 'Id Location',
            'near_location' => 'Near Location',
            'type_navigator' => 'Type Navigator',
            'side_navigator' => 'Side Navigator',
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     *
     * Typical usecase:
     * - Initialize the model fields with values from filter form.
     * - Execute this method to get CActiveDataProvider instance which will filter
     * models according to data in model fields.
     * - Pass data provider to CGridView, CListView or any similar widget.
     *
     * @return CActiveDataProvider the data provider that can return the models
     * based on the search/filter conditions.
     */
    public function search() {
        // @todo Please modify the following code to remove attributes that should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('id_navigator', $this->id_navigator, true);
        $criteria->compare('id_location', $this->id_location, true);
        $criteria->compare('near_location', $this->near_location, true);
        $criteria->compare('type_navigator', $this->type_navigator);
        $criteria->compare('side_navigator', $this->side_navigator);

        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 BattlesNavigator the static model class
     */
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    /**
     * Возвращает массив ближайших локаций
     * @param int $id_location ид локации
     * @param int $user персонаж
     * @return array $locations
     */
    public static function getNearLocations($id_location, $user) {
        $criteria = new CDbCriteria();
        $criteria->with = array('nearLocation');
        $criteria->together = true;
        $criteria->compare('t.id_location', $id_location);
        $criteria->compare('t.side_navigator', $user->side);
        $criteria->addCondition('nearLocation.level_min <= ' . $user->level);
        $criteria->addCondition('nearLocation.level_max >= ' . $user->level);
        return self::model()->findAll($criteria);
    }

    /**
     * Проверяет доступ к локации
     * @param type $id_location
     * @param type $user
     * @return boolean
     */
    public static function checkAccessToLocation($id_location, $user) {
        if ($user->side != $user->idLocation->side_now) {
            return false;
        }
        $location = BattlesLocations::model()->findByPk($id_location);
        if (!$location) 
            return false;
        if ($user->level < $location->level_min || $user->level > $location->level_max) {
            return false;
        }
        $near = CHtml::listData(self::getNearLocations($id_location, $user), 'id_navigator', 'near_location');
        /* Если поле боя действительно рядом - продолжаем */
        if (in_array($user->battle_id, $near)) {
            return true;
        }
        return false;
    }

}
