<?php

if (! function_exists('formatterPhoneNumber')) {
    function formatterPhoneNumber($str)
    {
        $formatted = '';
        $str = str_replace(' ', '', $str);

        if (substr($str, 0, 3) == '+36') {
            if (substr($str, 3, 1) === '1') {
                $formatted .= '+36 1';
                $formatted .= ' '.substr($str, 4, 3);
                $formatted .= ' '.substr($str, 7, strlen($str));
            } else {
                $formatted .= substr($str, 0, 3);
                $formatted .= ' '.substr($str, 3, 2);
                $formatted .= ' '.substr($str, 5, 3);
                $formatted .= ' '.substr($str, 8, strlen($str));
            }
        } else {
            $formatted = $str;
        }

        return $formatted;
    }
}

if (! function_exists('formatterDateTime')) {
    function formatterDateTime($str, $format = 'Y.m.d H:i:s'): string
    {
        return Carbon\Carbon::createFromTimeString($str)->format($format);
    }
}

if (! function_exists('formatterDate')) {
    function formatterDate($str, $format = 'Y.m.d'): string
    {
        return Carbon\Carbon::createFromDate($str)->format($format);
    }
}

if (! function_exists('from_camel_case')) {
    function from_camel_case($input)
    {
        preg_match_all('!([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)!', $input, $matches);
        $ret = $matches[0];
        foreach ($ret as &$match) {
            $match = $match == strtoupper($match) ? strtolower($match) : lcfirst($match);
        }

        return implode('_', $ret);
    }
}

if (! function_exists('parseAPIVersionFromNamespace')) {
    function parseAPIVersionFromNamespace($str, $VPrefix = false): array
    {
        $NsArr = explode('\\', substr($str, strpos($str, '\\api\\') + 1));
        $verSting = $NsArr[1];
        if (is_numeric(substr($verSting, 0, 1))) {
            $verNumber = substr($verSting, 0);
        } else {
            $verNumber = substr($verSting, 1);
        }
        $retVer = $verNumber;
        if ($VPrefix) {
            $retVer = 'v'.$retVer;
        }

        return ['apiVersion' => $retVer];
    }
}

if (! function_exists('bool2text')) {
    /** Convert a truthy value to string "True", otherwise "False" **/
    function bool2text($value)
    {
        return $value ? 'true' : 'false';
    }
}
if (! function_exists('getOrderFromOrderArchive')) {
    function getOrderFromOrderArchive($orderArchiveId = null, $orderArchive = null)
    {
        if ($orderArchiveId) {
            $orderArchive = \App\Models\OrderArchive::find($orderArchiveId);
        }

        return \App\Models\Order::where('humanId', $orderArchive->humanId)->first();
    }
}

if (! function_exists('getSql')) {
    /** Convert a truthy value to string "True", otherwise "False" **/
    // Illuminate\Database\Eloquent\Builder
    function getSql(\Illuminate\Database\Eloquent\Builder $Q)
    {
        return Illuminate\Support\Str::replaceArray('?', $Q->getBindings(), $Q->toSql());
    }
}
