<?php

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
use App\Libs\Database\Eloquent\Relations\BelongsToManyWebsite;
use App\Libs\Facades\Localization;

abstract class BaseModel extends Model
{
    public static $manyMethods = [
        'belongsToMany', 'morphToMany', 'morphedByMany', 'belongsToManyWebsite'
    ];

    public static function getTableName()
    {
        return with(new static)->getTable();
    }

    public static function getPrimaryKeyName()
    {
        return with(new static)->getKeyName();
    }

    public function belongsToManyWebsite(
        $related,
        $table = null,
        $foreignPivotKey = null,
        $relatedPivotKey = null,
        $parentKey = null,
        $relatedKey = null,
        $relation = null
    ) {
        // If no relationship name was passed, we will pull backtraces to get the
        // name of the calling function. We will use that function name as the
        // title of this relation since that is a great convention to apply.
        if (is_null($relation)) {
            $relation = $this->guessBelongsToManyRelation();
        }

        // First, we'll need to determine the foreign key and "other key" for the
        // relationship. Once we have determined the keys we'll make the query
        // instances as well as the relationship instances we need for this.
        $instance = $this->newRelatedInstance($related);

        $foreignPivotKey = $foreignPivotKey ?: $this->getForeignKey();

        $relatedPivotKey = $relatedPivotKey ?: $instance->getForeignKey();

        // If no table name was provided, we can guess it by concatenating the two
        // models using underscores in alphabetical order. The two model names
        // are transformed to snake case from their default CamelCase also.
        if (is_null($table)) {
            $table = $this->joiningTable($related, $instance);
        }

        $websiteId = Localization::getWebsite()->id;

        return new BelongsToManyWebsite(
            $instance->newQuery(), $this, $websiteId, $table, $foreignPivotKey,
            $relatedPivotKey, $parentKey ?: $this->getKeyName(),
            $relatedKey ?: $instance->getKeyName(), $relation);
    }


    public function keyExists($key)
    {
        $camelKey = Str::camel($key);
        return (
            array_key_exists($key, $this->attributes)
            || array_key_exists($key, $this->relations)
            || method_exists($this, $camelKey));
    }
}

