<?php
namespace App\Services;

use App\Models\UserHistory;
use Illuminate\Support\Str;
use Yard;

class Util
{



    private static $postRoute = 'base.';

    public static function getToken()
    {
        return hash_hmac('sha256', str_random(40), config('app.key'));
    }

    public static function uuidToken()
    {
        $uuid = (string) Str::uuid();
        $e_uuid = explode("-", $uuid);
        if(isset($e_uuid[0]) && $e_uuid[1]){
            return $e_uuid[0]."-".$e_uuid[1];

        }
        return $uuid;
    }

    public static function formatDate(){
        if(\App::getLocale() === "en"){
            return 'yyyy-mm-dd';
        }
        return 'dd.mm.yyyy';

    }

    public static function formatDateDB(){
        if(\App::getLocale() === "en"){
            return 'Y-m-d';
        }
        return 'd.m.Y';
    }

    public static function formatDateTimeDB(){
        if(\App::getLocale() === "en"){
            return 'Y-m-d - H:i';
        }
        return 'd.m.Y - H:i';
    }

    public static function _format_number($value){
        return preg_replace("/[^0-9,]/", "", $value);

    }

    public static function reFormatNumber($value){
        return (float) str_replace(',', '.', self::_format_number($value));
    }

    public static function formatNumber($value, $dec=2){
        if(\App::getLocale() === "en"){
            return number_format($value, $dec, '.', ',');
        }
        return number_format($value, $dec, ',', '.');
    }

    public static function  utf8ize( $mixed ) {
        if (is_array($mixed)) {
            foreach ($mixed as $key => $value) {
                $mixed[$key] = self::utf8ize($value);
            }
        } elseif (is_string($mixed)) {
            return mb_convert_encoding($mixed, "UTF-8", "UTF-8");
        }
        return $mixed;
    }


    public static function getPostRoute(){
        return self::$postRoute;
    }
    public static function setPostRoute($postRoute){
        self::$postRoute = $postRoute;
    }

    public static function getUserShop(){
        if(\Session::has('user_shop')){
            if($user_shop = \Session::get('user_shop')){
                    return $user_shop;
            }
        }
        return false;
    }

    public static function getAuthUser(){
        if(\Auth::check() && \Auth::user()){
            return \Auth::user();
        }
        if(\Session::has('auth_user')){
            if($auth_user = \Session::get('auth_user')){
                return $auth_user;
            }
        }
        return false;
    }


    /*public static function getUserShopIdentifier(){
        if(\Session::has('user_shop_identifier')){
            if($user_shop_identifier = \Session::get('user_shop_identifier')){
                return $user_shop_identifier;
            }
        }
        return false;
    }*/

    public static function getUserHistory($identifier){
        $auth_user = self::getAuthUser();
        if($auth_user){
            return UserHistory::whereUserId($auth_user->id)->whereIdentifier($identifier)->get()->last();
        }
        return false;
    }

    public static function setUserHistoryValue($values = [], $identifier){
         if($user_history = self::getUserHistory($identifier)){
            foreach ($values as $key=>$val){
                $user_history->{$key} = $val;
            }
            $user_history->save();
         }
    }

    public static function getUserHistoryValue($key, $identifier){
        if($user_history = self::getUserHistory($identifier)) {
            return $user_history->{$key};
        }
        return null;
    }

    public static function getUserShoppingMode(){
        if($auth_user = self::getAuthUser()){
            if($auth_user->isTestMode()){
                return 'test';
            }
        }
        return 'live';
    }
    public static function addRoute($p = []){
        $b = [];
        if(\Session::has('user_shop')){
            if($user_shop = \Session::get('user_shop')){
                $b = ['subdomain' => $user_shop->slug];
            }
        }
        return array_merge($p, $b);
    }

    public static function isCheckout(){

        if(\Session::has('isCheckout')){
            if(\Session::get('isCheckout') == true){
                return true;
            }
        }
        return false;
    }

    public static function getMyMivitaUrl($protocol = true){
        $pro = $protocol ? config('app.protocol') : "";
        return $pro.config('app.pre_url_crm').config('app.domain').config('app.tld_care');
    }

    public static function getUserPaymentFor(){
        if(Yard::instance('shopping')->getYardExtra('user_shop_payment')){
            return Yard::instance('shopping')->getYardExtra('user_shop_payment');
        }
        if(\Session::has('user_shop_payment')){
            return \Session::get('user_shop_payment');
        }

        return null;
    }

    public static function getUserShopBackUrl($reference = ""){

        if(\Session::has('user_shop')){
            if(\Session::has('user_shop_domain')){
                return \Session::get('user_shop_domain');
            }
            if($user_shop = \Session::get('user_shop')){
                return config('app.protocol').$user_shop->slug.".".config('app.domain').config('app.tld_care')."/back/to/shop/".$reference;
            }
        }
        return url("/");
    }

    public static function getUserCardBackUrl($uri){

        if(\Session::has('user_shop')){
            if(\Session::has('user_shop_domain')){
                if(\Session::has('back_link')){
                    return \Session::get('back_link');
                }
                if(self::getUserPaymentFor() === 3){
                    return \Session::get('user_shop_domain')."/user/membership";
                }
                if(self::getUserPaymentFor() === 2){
                    return \Session::get('user_shop_domain')."/user/orders";
                }
                return \Session::get('user_shop_domain');
            }
            if($user_shop = \Session::get('user_shop')){
                return config('app.protocol').$user_shop->slug.".".config('app.domain').config('app.tld_care').$uri;
            }
        }
        return url($uri);
    }
    public static function sanitize($string, $force_lowercase = true, $anal = false, $substr = false)
    {
        $strip = array("~", "`", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "=", "+", "[", "{", "]",
            "}", "\\", "|", ";", ":", "\"", "'", "&#8216;", "&#8217;", "&#8220;", "&#8221;", "&#8211;", "&#8212;",
            "â€”", "â€“", ",", "<", ".", ">", "/", "?");
        $clean = trim(str_replace($strip, "", strip_tags($string)));
        $clean = preg_replace('/\s+/', "_", $clean);
        $clean = ($anal) ? preg_replace("/[^a-zA-Z0-9]/", "", $clean) : $clean ;

        if($substr){
            $clean = (strlen($clean) > 20) ? substr($clean,-20) : $clean;

        }
        return ($force_lowercase) ?
            (function_exists('mb_strtolower')) ?
                mb_strtolower($clean, 'UTF-8') :
                strtolower($clean) :
            $clean;
    }

}