<?php

namespace common\modules\relation\models;

use common\modules\relation\relationHelper;
use Yii;

/**
 * This is the model class for table "relation".
 *
 * @property string $alias
 * @property integer $entity1_id
 * @property integer $entity2_id
 */
class Relation extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'relation';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['alias', 'entity1_id', 'entity2_id'], 'required'],
            [['entity1_id', 'entity2_id'], 'integer'],
            [['alias'], 'string', 'max' => 50]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'alias' => Yii::t('relation', 'Alias'),
            'entity1_id' => Yii::t('relation', 'Entity1 ID'),
            'entity2_id' => Yii::t('relation', 'Entity2 ID'),
            'entity1' => Yii::t('relation', 'Entity1 ID'),
            'entity2' => Yii::t('relation', 'Entity2 ID'),
        ];
    }

    /**
     * @inheritdoc
     * @return RelationQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new RelationQuery(get_called_class());
    }

    public function getRelationSection() {
        return relationHelper::getRelation($this->alias);
    }

    public function getEntity1() {
        return $this->getEntity('entity1');
    }

    public function getEntity2() {
        return $this->getEntity('entity2');
    }

    protected function getEntity($entity) {
        $relation = $this->getRelationSection();
        if (!$relation)
            return;
        return $this->hasOne($relation[$entity]['model']::className(), [$relation[$entity]['key'] => $relation[$entity]['linked_key']]);
    }
}
