<?php
if (!function_exists('inSpecCharByRegex')) {
    function inSpecCharByRegex($content, $regex)
    {
        return preg_replace_callback($regex, function ($matches) {
            return $matches[1] . SEOAutoInSpecChar($matches[2]) . $matches[3];
        }, $content);
    }
}

if (!function_exists('SEOAutoInSpecChar')) {
    function SEOAutoInSpecChar($str)
    {
        $strarr = SEOAutoS2A($str);
        $str = implode("<!---->", $strarr);
        return $str;
    }
}

if (!function_exists('SEOAutoS2A')) {
    function SEOAutoS2A($str)
    {
        $chararray = array();
        for ($i = 0; $i < strlen($str); $i++) {
            array_push($chararray, base64_encode($str[$i]));
        }
        return $chararray;
    }
}

if (!function_exists('getIgnoreKeywords')) {
    function getIgnoreKeywords($content)
    {
        $retVal = [];
        preg_match_all("/<\s*a[^>]*>(.*?)<\s*\/\s*a>/", $content, $matches);
        if (isset($matches[1])) {
            foreach ($matches[1] as $match) {
                $retVal[] = strtolower(strip_tags(html_entity_decode($match, ENT_COMPAT, 'UTF-8')));
            }
        }
        return $retVal;
    }
}

if (!function_exists('detectAutoKeywords')) {
    function detectAutoKeywords($content)
    {
        $retVal = [];
        preg_match_all('/<\s*a[^>]*data-keyword-link="([^"]*)"[^>]*>(.*?)<\s*\/\s*a>/', $content, $matches);
        if (isset($matches[2])) { // keyword text
            for ($i = 0; $i < count($matches[2]); $i++) {
                $keyword = strtolower(strip_tags(html_entity_decode($matches[2][$i], ENT_COMPAT, 'UTF-8')));
                if ($keyword && isset($matches[1][$i])) {
                    $retVal[] = [
                        'id' => $matches[1][$i],
                        'keyword' => $keyword
                    ];
                }
            }
        }
        return [$retVal, $matches[1] ?? []];
    }
}

if (!function_exists('reSpecCharByRegex')) {
    function reSpecCharByRegex($content, $regex)
    {
        return preg_replace_callback($regex, function ($matches) {
            return $matches[1] . SEOAutoReSpecChar($matches[2]) . $matches[3];
        }, $content);
    }
}

if (!function_exists('SEOAutoReSpecChar')) {
    function SEOAutoReSpecChar($str)
    {
        $strarr = explode("<!---->", $str);
        foreach ($strarr as $key => $data) {
            if (base64_encode(base64_decode($data, true)) === $data && strpos($data, "=") !== false) {
                $strarr[$key] = base64_decode($data);
            }
        }
        $str = implode("", $strarr);
        $str = stripslashes($str);
        return $str;
    }
}
if (!function_exists('getMetaDataConfig')) {
    function getMetaDataConfig($withParams = false)
    {
        $path = \Illuminate\Support\Facades\Request::path();
        if ($withParams) {
            $path = \Illuminate\Support\Facades\Request::getRequestUri();
        } else {
            $defaultParams = [];
            if (\Illuminate\Support\Facades\Request::has('spid')) {
                $defaultParams['spid'] = \Illuminate\Support\Facades\Request::input('spid');
            }
            if (!empty($defaultParams)) {
                $path = $path . '?' . http_build_query($defaultParams);
            }
        }
        $locale = env('APP_LOCALE', 'us');
        if ($locale) {
            if (substr($path, 0, strlen($locale)) == $locale) {
                $path = substr($path, strlen($locale));
            }
        }

        return \Modules\Seo\Models\MetaData::where('url', '=', '/' . ltrim($path, '/'))->first();
    }

    if (!function_exists('buildMetaConfigurationData')) {
        function buildMetaConfigurationData (string $objectName, $metaConfig, array $data) {
            $replaceVariable = [
                '{name}' => '', 
                '{store_name}' => '', 
                '{product_id}' => '', 
                '{created_at}' => '',
                '{name_category}' => '',
            ];
    
            $title = !empty($metaConfig->description) ? $metaConfig->title : '';
            $keywords = !empty($metaConfig->description) ? $metaConfig->keywords : '';
            $description = !empty($metaConfig->description) ? $metaConfig->description : '';

            if ($objectName == 'product') {
                $replaceVariable['{name}'] = $data['name'];
                $replaceVariable['{store_name}'] = $data['store_name'];
                $replaceVariable['{product_id}'] = $data['product_id'];
                $replaceVariable['{created_at}'] = $data['created_at'];
            }

            if ($objectName == 'category') {
                $replaceVariable['{name_category}'] = $data['name_category'];
            }

            if ($objectName == 'tag') {
                $replaceVariable['{name}'] = (!empty($data['name'])) ? ucfirst($data['name']) : '';
            }

            if ($objectName == 'news') {
                $replaceVariable['{name}'] = __('Tin tức');
            }

            $replaceFrom = array_keys($replaceVariable);
            $replaceTo = array_values($replaceVariable);

            $title = preg_replace('!\s+!', ' ', str_replace($replaceFrom, $replaceTo, $title));
            $description = preg_replace('!\s+!', ' ', str_replace($replaceFrom, $replaceTo, $description));
            $keywords = preg_replace('!\s+!', ' ', str_replace($replaceFrom, $replaceTo, $keywords));
    
            return [
                'title' => $title,
                'description' => $description,
                'keywords' => $keywords,
            ];
        }
    }
}

