<?php

use App\HomeInfo;
use App\Module;
use App\Product;
use App\Service;
use App\User;
use App\Setting;
use App\Language;
use App\Helpers\ImageHelper;
use App\Newsletter;
use App\Providers\AppServiceProvider;
use App\UsersNotification;
use Illuminate\Support\LazyCollection;
use Illuminate\Support\Str;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;

if (!function_exists('languages')){

    /**
     * Return list of languages from database
     * @return LazyCollection
     */
    function languages(): LazyCollection
    {
        $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', (request()->header('local') ?? LaravelLocalization::getCurrentLocale()))->first();
        return $languages;
    }
}

if (!function_exists('getCurrentLocale')){

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

if (!function_exists('descriptions')){

    /**
     * Return description for model
     * @param $model
     * @param null $local_lang
     * @return mixed
     */
    function descriptions($model, $local_lang = null)
    {
        $description = $model->descriptions->where('language_id', $local_lang ?? currentLanguage()->id)->first();
        return $description ?? null;
    }
}

if (!function_exists('parseExternalVideoLink')){

    /**
     * Parse youtube|vimo|etc link to get video ID, video embed link, video thumbnails
     * @param $link
     * @return array
     */
    function parseExternalVideoLink($link) :array
    {

        /**
         * Links to test
         * https://youtu.be/N6wn8zMRlVE
         * https://www.youtube.com/watch?v=zlnau3yk0oU
         * https://www.youtube.com/watch?v=zlnau3yk0oU&features=adsdsd
         * https://www.youtube.com/embed/OC9zn5BKlC0
         */

        $linkPattern = '/^(https:\/\/(www\.)?(youtu|youtube){1}.([a-z]{1,4}))(\/watch\?v=|\/embed\/|\/){0,1}([a-zA-z0-9]{2,15})(&.)*/';

        $m= preg_match($linkPattern, $link, $linkMatches);

        // dd($m, $linkMatches);
        if (count($linkMatches) && $linkMatches[6]){
            $code = $linkMatches[6];
            $video_url = 'https://www.youtube.com/embed/'.$code;
            $image = "https://img.youtube.com/vi/$code/hqdefault.jpg";
        } else {
            $video_url = $link;
        }

        // $public = asset('/uploads/images/'.time().'.jpg');

        // Download images from remote server
        // $in=    fopen($image, "rb");
        // $out=   fopen($public, "wb");
        // while ($chunk = fread($in,8192))
        // {
        //     fwrite($out, $chunk, 8192);
        // }
        // fclose($in);
        // fclose($out);


        return [
            'code' => $code,
            'url' => $video_url,
            'image' => $image
        ];

    }
}

if (!function_exists('newsletters')){

    /**
     * Return all newsletters email
     * @return LazyCollection
     */
    function newsletters() :LazyCollection
    {
        $newsletters = Newsletter::cursor();
        return $newsletters;
    }
}

if (!function_exists('getUser')){

    /**
     * Return admin by id
     * @param $id
     * @return mixed
     */
    function getUser($id)
    {
        $user = User::find($id);
        return $user;
    }
}

if (!function_exists('settings')){

    /**
     * Return settings
     * @param string|array $key
     * @return array
     */
    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 string|null
     */
    function meta($field, $local): ?string
    {
        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'];
        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('wordLimit')){

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

}

if (!function_exists('getImage')){

    /**
     * A short_cut function calls Imagehelper class to
     * Return the url of the image
     *
     * @param $file
     * @return string
     */
    function getImage($file): string
    {
        return ImageHelper::get($file);
    }

}

if (!function_exists('getFile')){

    /**
     * A get URL of the file if it exists, otherwise return null
     * Return the url of the image
     *
     * @param $file
     * @return string
     */
    function getFile($file): ?string
    {
        if (!$file) {
            return null;
        }
        $filePath= public_path($file);
        // dump($filePath , is_file($filePath));
        if (is_file($filePath)) {
            return asset($file);
        } else {
            return 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 ($currentUrl == $url){
            return $class;
        }
        if (is_array($url) && in_array($currentUrl, $url)){
            return $class;
        }
        return '';
    }



}

if (!function_exists('stripText')){

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

}

if (!function_exists('products')){

    function products()
    {
        $products = Product::withDescription([], null, [1,0]);
        return $products;
    }

}

if (!function_exists('services')){

    function services()
    {
        $services = Service::withDescription();
        return $services;
    }

}
