<?php

namespace CliqThemes\ORM\Relations;

use CliqThemes\ORM\Model;

/**
 * Represents the inverse of a one-to-one or one-to-many relationship.
 */
class BelongsTo extends Relation
{
    protected string $foreignKey;

    protected string $ownerKey;

    /**
     * @param string $foreignKey Column on the parent model referencing the related model.
     * @param string $ownerKey   Column on the related model representing its key.
     */
    public function __construct(Model $parent, Model $related, string $foreignKey, string $ownerKey)
    {
        parent::__construct($parent, $related);
        $this->foreignKey = $foreignKey;
        $this->ownerKey = $ownerKey;
    }

    /**
     * Retrieve the related model instance for the current parent.
     */
    public function getResults(): ?Model
    {
        $value = $this->parent->{$this->foreignKey};

        if ($value === null) {
            return null;
        }

        return $this->newRelatedQuery()
            ->where($this->ownerKey, '=', $value)
            ->first();
    }
}

