<?php
namespace PortalPeople\oauth2\behaviors;

use yii\base\Behavior;
use yii\db\ActiveRecord;

class RelationBehavior extends Behavior
{
    /**
     * Map of relation names to their configurations
     * @var array
     */
    public $relations = [];

    /**
     * Tell Yii this behavior can get these properties
     */
    public function canGetProperty($name, $checkVars = true)
    {
        return isset($this->relations[$name]) || parent::canGetProperty($name, $checkVars);
    }

    /**
     * Override __get to provide dynamic properties
     */
    public function __get($name)
    {
        if (isset($this->relations[$name])) {
            return $this->getRelation($name);
        }
        
        return parent::__get($name);
    }

    /**
     * Override __call to provide dynamic relation methods
     */
    public function __call($name, $params)
    {
        // Check if this is a getter for a defined relation
        if (strpos($name, 'get') === 0) {
            $relationName = lcfirst(substr($name, 3));
            
            if (isset($this->relations[$relationName])) {
                return $this->getRelation($relationName);
            }
        }
        
        return parent::__call($name, $params);
    }

    /**
     * Provide relation based on configuration
     */
    protected function getRelation($name)
    {
        $config = $this->relations[$name];
        
        if (isset($config['type']) && $config['type'] === 'hasMany') {
            return $this->owner->hasMany($config['class'], $config['foreignKey']);
        }
        
        // Default to hasOne
        return $this->owner->hasOne($config['class'], $config['foreignKey']);
    }
}
