<?php

// -----------------------------------------------------------------------------

use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Route;

// -----------------------------------------------------------------------------

if (! function_exists('alert_box')) {
    /**
     * @param $msg
     * @param  string $typ
     * @return array
     */
    function alert_box($msg, $typ = 'success')
    {
        return ['alert-box' => $typ, 'alert-msg' => $msg];
    }
}

// -----------------------------------------------------------------------------
// Nicht-numerische Zeichen aus String entfernen

if (! function_exists('strip_non_numeric')) {
    function strip_non_numeric($in)
    {
        $out = $in;
        if (is_string($in)) {
            $out = preg_replace('/\D/', '', $in);
        }

        return $out;
    }
}

// -----------------------------------------------------------------------------
// Mehrzeiligen Text in Array umwandeln (Pro Zeile ein Array-Item)

if (! function_exists('lines_to_array')) {
    function lines_to_array($text)
    {
        $text = is_scalar($text) ? trim($text) : null;
        $lines = filled($text) ? preg_split('/\\r\\n|\\r|\\n/', $text) : [];
        $lines = array_map('trim', $lines);
        $lines = array_unique($lines, SORT_REGULAR);
        $lines = array_filter($lines, function ($e) {
            return filled($e);
        });

        return $lines;
    }
}

// -----------------------------------------------------------------------------
// Telefonnummer nach E164 formatieren

if (! function_exists('normalize_phone')) {
    function normalize_phone($phone)
    {
        $phone_normalized = null;
        if (is_scalar($phone)) {
            $country_code = '+49';
            $phone_normalized = trim($phone);
            $phone_normalized = str_replace($country_code, 0, $phone_normalized);
            $phone_normalized = preg_replace('/\D/', '', $phone_normalized);
            if (substr($phone_normalized, 0, 1) === '0') {
                $phone_normalized = substr($phone_normalized, 1);
            }
            $phone_normalized = $country_code . $phone_normalized;
        }

        return $phone_normalized;
    }
}

// -----------------------------------------------------------------------------
// IBAN nach DIN 5008 formatieren (Vierergruppen von links)

if (! function_exists('iban_format')) {
    function iban_format($iban)
    {
        $iban_formatted = $iban;
        if (is_string($iban_formatted)) {
            $iban_formatted = preg_replace('/\s+/', '', $iban_formatted);
            $iban_formatted = wordwrap(strtoupper($iban_formatted), 4, ' ', true);
        }

        return $iban_formatted;
    }
}

// -----------------------------------------------------------------------------
// Zahl nach europäischem Format formatieren

if (! function_exists('number_format_EU')) {
    function number_format_EU($value, $decimals = 2)
    {
        return number_format($value, $decimals, ',', '.');
    }
}

// -----------------------------------------------------------------------------
// Zahl mit deutscher Mehrwertsteuer verrechnen

if (! function_exists('apply_vat')) {
    function apply_vat($value, $vat = 1.19)
    {
        if (is_numeric($value)) {
            $value *= $vat;
        }

        return $value;
    }
}

// -----------------------------------------------------------------------------
// Listenstring von Duplikaten befreien

if (! function_exists('str_list_unique')) {
    function str_list_unique($in = null, $delimiter = ' ')
    {
        $in = is_scalar($in) ? trim($in) : null;
        $delimiter = is_scalar($delimiter) ? $delimiter : ' ';
        $out = $in;
        if (filled($in)) {
            $arr = explode($delimiter, $in);
            $arr = array_map('trim', $arr);
            $arr = array_unique($arr, SORT_REGULAR);
            $arr = array_filter($arr, function ($e) {
                return filled($e);
            });
            $out = implode($delimiter, $arr);
        }

        return $out;
    }
}

// -----------------------------------------------------------------------------
// Array rekursiv von doppelten Values befreien

if (! function_exists('array_unique_recursive')) {
    function array_unique_recursive($array)
    {
        $result = array_map('unserialize', array_unique(array_map('serialize', $array)));
        foreach ($result as $key => $value) {
            if (is_array($value)) {
                $result[$key] = array_unique_recursive($value);
            }
        }

        return $result;
    }
}

// -----------------------------------------------------------------------------
/**
 * Sanitizes an HTML classname to ensure it only contains valid characters.
 *
 * Strips the string down to A-Z,a-z,0-9,_,-. If this results in an empty
 * string then it will return the alternative value supplied.
 *
 * @todo Expand to support the full range of CDATA that a class attribute can contain.
 */

if (! function_exists('sanitize_html_class')) {
    /**
     * @param  string $class    The classname to be sanitized
     * @param  string $fallback Optional. The value to return if the sanitization ends up as an empty string.
     *                          Defaults to an empty string.
     * @return string The sanitized value
     */
    function sanitize_html_class($class, $fallback = '')
    {
        // Strip out any % encoded octets
        $sanitized = preg_replace('|%[a-fA-F0-9][a-fA-F0-9]|', '', $class);

        // Limit to A-Z,a-z,0-9,_,-
        $sanitized = preg_replace('/[^A-Za-z0-9_-]/', '', $sanitized);

        if ('' == $sanitized && $fallback) {
            return sanitize_html_class($fallback);
        }

        return $sanitized;
    }
}

// -----------------------------------------------------------------------------

if (! function_exists('sanitize_html_classes')) {
    function sanitize_html_classes($list)
    {
        $list = is_scalar($list) ? trim($list) : null;

        $arr = explode(' ', $list);
        $arr = array_map('sanitize_html_class', $arr);

        $list = str_list_unique(implode(' ', $arr));

        return $list;
    }
}

// -----------------------------------------------------------------------------
/**
 * Add leading zeros when necessary.
 *
 * If you set the threshold to '4' and the number is '10', then you will get
 * back '0010'. If you set the threshold to '4' and the number is '5000', then you
 * will get back '5000'.
 *
 * Uses sprintf to append the amount of zeros based on the $threshold parameter
 * and the size of the number. If the number is large enough, then no zeros will
 * be appended.
 */

if (! function_exists('zeroise')) {
    /**
     * @param  int    $number    Number to append zeros to if not greater than threshold.
     * @param  int    $threshold Digit places number needs to be to not have zeros added.
     * @return string Adds leading zeros to number if needed.
     */
    function zeroise($number, $threshold)
    {
        return sprintf('%0' . $threshold . 's', $number);
    }
}

// -----------------------------------------------------------------------------
/**
 * Normalize EOL characters and strip duplicate whitespace.
 */

if (! function_exists('normalize_whitespace')) {
    /**
    * @param string $str The string to normalize.
    * @return string The normalized string.
    */
    function normalize_whitespace($str)
    {
        $str = trim($str);
        $str = str_replace("\r", "\n", $str);
        $str = preg_replace(['/\n+/', '/[ \t]+/'], ["\n", ' '], $str);

        return $str;
    }
}

// -----------------------------------------------------------------------------
/**
 * Get Weekend days for a specific timespan.
 */

if (! function_exists('get_weekends')) {
    /**
     * @param  Carbon $start
     * @param  Carbon $end
     * @return array
     */
    function get_weekends(Carbon $start, Carbon $end, $format = 'Y-m-d')
    {
        $weekends = [];

        while ($start->lte($end)) {
            if ($start->isWeekend()) {
                $weekends[] = $start->copy()->format($format);
            }
            $start->addDay();
        }

        return $weekends;
    }
}

// -----------------------------------------------------------------------------
/**
 * Get holidays for a specific timespan.
 */

if (! function_exists('get_holidays')) {
    /**
     * @param  Carbon $start
     * @param  Carbon $end
     * @return array
     */
    function get_holidays(Carbon $start, Carbon $end, $format = 'Y-m-d')
    {
        $holidays = [];

        $current = $start->copy();

        while ($current->lte($end)) {
            $easter = Carbon::createFromTimestamp(easter_date($current->year));
            $holidays[$current->copy()->firstOfYear()->format($format)] = 'Neujahr';
            //$holidays[$start->copy()->day(6)->format($format)] = 'Heilige drei Könige';
            //$holidays[$easter->copy()->subDays(3)->format($format)] = 'Gründonnerstag';
            $holidays[$easter->copy()->subDays(2)->format($format)] = 'Karfreitag';
            //$holidays[$easter->copy()->format($format)] = 'Ostersonntag';
            $holidays[$easter->copy()->addDay()->format($format)] = 'Ostermontag';
            $holidays[$current->copy()->month(5)->day(1)->format($format)] = 'Tag der Arbeit';
            $holidays[$easter->copy()->addDays(39)->format($format)] = 'Christi Himmelfahrt';
            $holidays[$easter->copy()->addDays(50)->format($format)] = 'Pfingstmontag';
            //$holidays[$easter->copy()->addDays(60)->format($format)] = 'Fronleichnam';
            //$holidays[$start->copy()->month(8)->day(15)->format($format)] = 'Maria Himmelfahrt';
            $holidays[$current->copy()->month(10)->day(3)->format($format)] = 'Tag der deutschen Einheit';
            //$holidays[$start->copy()->month(10)->lastOfMonth()->format($format)] = 'Reformationstag';
            //$holidays[$start->copy()->month(11)->day(1)->format($format)] = 'Allerheiligen';
            $holidays[$current->copy()->month(12)->day(25)->format($format)] = '1. Weihnachtstag';
            $holidays[$current->copy()->month(12)->day(26)->format($format)] = '2.Weihnachtstag';
            $current->addYear()->startOfYear();
        }

        $ret = [];

        foreach ($holidays as $key => $value) {
            $date = Carbon::parse($key);
            if ($start->lte($date) && $end->gte($date)) {
                $ret[$key] = $value;
            }
        }

        return $ret;
    }
}

// -----------------------------------------------------------------------------

if (! function_exists('theme_enabled')) {
    function theme_enabled()
    {
        $themeEnabled = boolval(env('THEME_ENABLED'));

        return $themeEnabled;
    }
}

// -----------------------------------------------------------------------------

if (! function_exists('to_session_old')) {
    function to_session_old(array $data)
    {
        array_walk($data, function ($value, $key) {
            session()->now($key, $value);
        });
    }
}

if (! function_exists('per_page_default')) {
    function per_page_default()
    {
        return config('pagination.perPage.default');
    }
}

if (! function_exists('per_page_options')) {
    function per_page_options()
    {
        return config('pagination.perPage.options', []);
    }
}

if (! function_exists('remove_non_alphabetical')) {
    function remove_non_alphabetical($string)
    {
        return preg_replace('/[^a-zA-Z]/', '', $string);
    }
}

if (! function_exists('busted_asset')) {
    /**
     * @param $assetFile
     * @return string
     */
    function busted_asset($asset)
    {
        return asset($asset) . '?v=' . filemtime(public_path($asset));
    }
}

if (! function_exists('get_ajax_routes_arr')) {
    function get_ajax_routes_arr () {
        $ajaxRoutesCollection = collect(Route::getRoutes())->filter(function ($route) {
            return str_contains($route->getName(), 'ajax');
        });
        $ajaxRoutesArr = [];
        foreach ($ajaxRoutesCollection as $route) {
            if(str_contains($route->uri(), ['{', '}'])) {
                $ajaxRoutesArr[$route->getName()] = route($route->getName(), '');
            } else {
                $ajaxRoutesArr[$route->getName()] = route($route->getName());
            }
        }
        return $ajaxRoutesArr;
    }
}