<?php

namespace App\Helpers\Backoffice;

use App\Models\Backoffice\WebsiteObjectLanguage;
use Illuminate\Database\Eloquent\Collection;
use App\Helpers\Backoffice\LanguageHelper;

class DatabaseHelper
{
    public static function resolve_link($link)
    {
        if (!$link) {
            return [];
        }
        if (is_string($link)) {
            $link = json_decode($link, true);
        }
        if (array_key_exists('objectId', $link)) {
            $activeLanguage = LanguageHelper::getActiveLanguage();
            $websiteObject = WebsiteObjectLanguage::where('website_object_id', $link['objectId'])
                ->where('wo_language_id', $activeLanguage)
                ->first();
            if ($websiteObject) {
                $link['url'] = LanguageHelper::lang_url($websiteObject->lang_uri, $activeLanguage);
            }
        }

        return $link;
    }

    public static function loadPolymorphicDependencies(
        Collection $collection,
        string $polymorphicName,
        string $modelType,
        array $relation,
        string $polyType = null,
        string $polyId = null
    )
    {
        if (empty($polyType)) {
            $polyType = $polymorphicName."_type";
        }

        if (empty($polyId)) {
            $polyId = $polymorphicName."_id";
        }
        $newCollection = new Collection();

        foreach ($collection as $model) {
            if ($model->$polymorphicName instanceof $modelType) {
                $new_collection->add($model->$polymorphicName);
            }
        }

        $newCollection->load($relation);
        return $collection;
    }
}
