<?php

use App\Models\BackendAuth\BackendConfiguration;
use App\Facades\RequestContext;

if (!function_exists('load_polymorphic_dependencies')) {
    function load_polymorphic_dependencies(
        Illuminate\Database\Eloquent\Collection $collection,
        $polymorphic_name,
        $model_type,
        array $relation,
        $poly_type = null,
        $poly_id = null
    ) {
        if (empty($poly_type)) {
            $poly_type = $polymorphic_name."_type";
        }

        if (empty($poly_id)) {
            $poly_id = $polymorphic_name."_id";
        }
        $new_collection = new Illuminate\Database\Eloquent\Collection();

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

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

if (!function_exists('fulltext_search_term')) {
    function fulltext_search_term($term, $allInclusive = true, $wildcard = true)
    {
        if (empty($term)) {
            return $term;
        }
        $term = str_replace("@", " ", $term);
        $term = str_replace("+", " ", $term);
        $term = str_replace("-", " ", $term);
        $term = str_replace("<", " ", $term);
        $term = str_replace(">", " ", $term);
        $term = str_replace("(", " ", $term);
        $term = str_replace(")", " ", $term);
        $term = str_replace("~", " ", $term);
        $term = str_replace("*", " ", $term);

        $words = explode(" ", trim($term));

        $terms = array();

        foreach ($words as $word) {
            if ($wildcard) {
                $word = $word."*";
            }

            if (!empty($word)) {
                if ($allInclusive) {
                    $word = "+".$word;
                }

                $terms[] = $word;
            }
        }

        return implode(" ", $terms);
    }
}

if (!function_exists('env_database')) {
    function env_database($key, $configKey = null) {
        if (is_null(RequestContext::get('env_' . $key))) {
            $model = BackendConfiguration::where('name', $key)->first();
            if (!is_null($model) || !empty($model->value)) {
                RequestContext::set('env_' . $key, $model->value);
            } else {
                RequestContext::set('env_' , $key, config(is_null($configKey) ? 'app.' . $key : $configKey));
            }
        }
        return RequestContext::get('env_' . $key);
    }
}




