<?php

namespace Hilco\Models;

use Arr;

/**
 * @property integer webfamily_id
 * @property integer related_id
 * @property string related_type
 * @property string related_category
 * @property integer createdby_id
 * @property integer lastmodifiedby_id
 * @property WebFamily webFamily
 */
class WebFamily_Related extends WebModel {
    protected $table = "WebFamily_Related";
    protected $fillable = ["webfamily_id", "related_id", "related_type", "related_category", "createdby_id", "lastmodifiedby_id"];

    use TracksLastModified;

    public function related() {
        return $this->morphTo(); // related_type values 'webPart' and 'webFamily' should be in WebAsset::morphMap
    }

    public function webFamily() {
        return $this->belongsTo(WebFamily::class, "webfamily_id", "id");
    }

    /**
     * @param array $createData
     * @return mixed
     */
    public static function createWebFamilyRelated (array $createData) {
        $webFamilyRelated = WebFamily_Related::withTrashed()->where(
            'webfamily_id', '=', $createData['webfamily_id']
        )->where(
            'related_id', '=', $createData['related_id']
        )->where(
            'related_type', '=', $createData['related_type']
        )->first();
        if ($webFamilyRelated && $webFamilyRelated->trashed()) {
            $webFamilyRelated->restore();
            $webFamilyRelated->refresh();
            $webFamilyRelated->update($createData);
        } else {
            if (! Arr::has($createData, 'createdby_id') && auth()->check()) {
                $createData['createdby_id'] = auth()->user()->id;
            }
            if (! Arr::has($createData, 'lastmodifiedby_id') && auth()->check()) {
                $createData['lastmodifiedby_id'] = auth()->user()->id;
            }
            $webFamilyRelated = WebFamily_Related::create($createData);
        }
        return $webFamilyRelated;
    }
}