<?php

use App\Models\Module;
use App\Models\Setting;
use App\Models\Language;
use App\Models\Visitor;
use App\Models\UserModule;
use App\Services\Currency\CurrencyService;
use Illuminate\Support\Facades\Auth;
use App\Providers\AppServiceProvider;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;

if (!function_exists('usermodules')) {
    function usermodules(){
        $modules= null;
        if (in_array(Auth::user()->role, ['super_admin', 'admin'])) {
            $modules = Module::where('deleted_at', null)->get();
            // dd($modules);
        }elseif (Auth::user()->role == 'sub_admin') {
            $ids = UserModule::where('user_id',Auth::user()->id)->pluck('module_id');
            $modules = Module::find($ids);
        }
        return $modules;
    }
}

if (!function_exists('languages')) {

    /**
     * Return list of languages from database
     * @return mixed
     */
    function languages() {
        $languages = Language::where('status', 1)->cursor();
        return $languages;
    }

}

if (!function_exists('currentLanguage')) {

    /**
     * Return current language from database
     * @return mixed
     */
    function currentLanguage() {
        $languages = Language::where('status', 1)->where('local', LaravelLocalization::getCurrentLocale())->first();
        return $languages;
    }

}

if (!function_exists('getCurrentLocale')) {

    /**
     * Return current current locale from database
     * @return mixed
     */
    function getCurrentLocale() {
        $current = Language::where('status', 1)->where('local', LaravelLocalization::getCurrentLocale())->first()->local;
        return $current;
    }

}

if (!function_exists('array_first')) {

    /**
     * Return first item  of array

     */
    function array_first($array) {
        if (count($array) > 0) {
            return $array[0];
        } else {
            return null;
        }
    }

}

if (!function_exists('settings')) {

    /**
     * Return settings
     * @param string|array $key
     * @return
     */
    function settings($key = null) {
        if (is_array($key)) {
            $allSettings = Setting::whereIn('key', $key)->cursor()->toArray();
            foreach ($allSettings as $setting) {
                $settings[$setting['key']] = $setting['value'];
            }
        } elseif ($key) {
            $settings = Setting::where('key', $key)->first()->value;
        } else {
            $allSettings = Setting::cursor()->toArray();
            foreach ($allSettings as $setting) {
                $settings[$setting['key']] = $setting['value'];
            }
        }
        return $settings;
    }

}

if (!function_exists('meta')) {

    /**
     * Return meta fields from module table
     * by field name and local language
     * this functions used mostly in blades views
     * to get meta field to each path individually
     * @param $field
     * @param $local
     * @return mixed
     */
    function meta($field, $local) {
        return AppServiceProvider::getMeta()['fields'][$local][$field] ?? null;
    }

}

if (!function_exists('metaFields')) {

    /**
     * Return meta field to module by module path from modules table
     * most used in blades views
     * @param $modulePath
     * @param null $fieldName
     * @param null $local
     * @return mixed|null
     */
    function metaFields($modulePath, $fieldName = null, $local = null) {
        $meta = Module::where('path', $modulePath)->pluck('meta')->toArray();
        $meta = array_first($meta);
        $meta = $fieldName && $local ? $meta['fields'][$local][$fieldName] ?? null : $meta['fields'];
        if(!$meta)
        {
            $meta = __($modulePath .'.' . $fieldName);
        }
        return $meta ?? null;
    }

}

if (!function_exists('moduleName')) {

    /**
     * Return module name to module by module path from modules table
     * most used in blades views
     * @param $modulePath
     * @param null $local
     * @return mixed
     */
    function moduleName($modulePath, $local = null) {
        $meta = Module::where('path', $modulePath)->pluck('meta')->toArray();
        $meta = array_first($meta);
        $meta = $local ? $meta['module_name'][$local] : $meta['module_name'];
        return $meta ?? null;
    }

}

if (!function_exists('isActive')) {

    /**
     * Return module name to module by module path from modules table
     * most used in blades views
     * @param $url
     * @param $class
     * @return mixed
     */
    function isActive($url, $class = 'active') {
        $currentUrl = url()->current();
        if (is_array($url)) {
            if (in_array($currentUrl, $url)) {
                return $class;
            }
        }

        if ($currentUrl == $url) {
            return $class;
        }

        return true;
    }

}

if (!function_exists('stripText')) {

    /**
     * Return module name to module by module path from modules table
     * most used in blades views
     * @param $text
     * @param $limit
     * @return mixed
     */
    function stripText($text, int $limit = null) {
        $description = strip_tags($text);
        $description = preg_replace('/\s\s+/', ' ', $description);
        if ($limit) {
            $description = \Illuminate\Support\Str::limit($description, $limit);
        }
        return $description ?? '';
    }

    if (!function_exists('wordLimit')) {

        /**
         * Return limit words
         * @param $string
         * @param $limit
         * @param null $end
         * @return string
         */
        function wordLimit($string, $limit = null, $end = '...'): string {
            return Str::words(stripText($string), $limit, $end);
        }

    }
}

if (!function_exists('getAmountDetails')) {
    /**
     * params => $total = all total (subtotal + tax)
     * return => amount = subtotal
     *
     * @param $total
     * @return array
     */
    function getAmountDetails($total): array
    {
        $tax = (float)settings('tax');
        $taxAmount = round(($tax * $total) / ($tax + 100), 2);
        return [
            'tax' => $taxAmount,
            'amount' => round($total - $taxAmount, 2),
        ];
    }
}

if (!function_exists('applyTax')) {
    /**
     * @param $amount
     * @return array
     */
    function applyTax($amount): array
    {
        $settingTax = (float)settings('tax');

        $tax = round($amount * $settingTax / 100, 2);
        $amount += $tax;

        return [
            'amount' => round($amount, 2),
            'tax' => $tax,
        ];
    }
}



