<?php
    
    $siteName = getOption('general.store_name');
    $ogImage = getImageCdn(getOption('general.logo'), 0, 0, true, false);
    $imageProductMineType = null;
    $metaData = null;
    $title = "";
    $description = "";
    $keywords = "";
    $locale = env('APP_LOCALE');
    if (empty($locale)) $locale = 'us';
    $languages = config('seo::default.hreflangs');
    $languageHrefs = $languages;
    $routeName = 'home';
    $appUrlMeta = env('APP_URL');
    if (function_exists('getMetaDataConfig')) {
        $metaData = getMetaDataConfig(false);
    }
    if (!function_exists('getUrlMimeType')) {
        function getUrlMimeType($image_url) {
            $mime_type = null;
            $file_extension = pathinfo(parse_url($image_url, PHP_URL_PATH), PATHINFO_EXTENSION);
            // Define a map of common image file extensions to MIME types
            $mime_types = [
                'jpg' => 'image/jpeg',
                'jpeg' => 'image/jpeg',
                'png' => 'image/png',
                'gif' => 'image/gif',
                'bmp' => 'image/bmp',
                'webp' => 'image/webp',
            ];
            // Check if the file extension is in the map and get the corresponding MIME type
            if (array_key_exists(strtolower($file_extension), $mime_types)) {
                $mime_type = $mime_types[strtolower($file_extension)];
            }
            return $mime_type;
        }
    }
    if (!function_exists('getOgType')) {
        function getOgType($routeName) {
            $retval = 'website';

            switch ($routeName) {
                case 'product':
                    $retval = 'product';
                    break;

                case 'post':
                    $retval = 'article';
                    break;

                case 'news':
                    $retval = 'article';
                    break;

                default: break;
            }

            return $retval;
        }
    }

    if (!empty($metaData->canonical)) { // by link
        $actual_link = $metaData->canonical;
    } else if (isset($canonical_url)) {
        $actual_link = $canonical_url;
    }
    if (empty($actual_link)) {
        $actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]" . strtok($_SERVER["REQUEST_URI"], '?');
    }
    if (strpos($appUrlMeta, "printblur") !== false) {
        $actual_link = str_replace($_SERVER["HTTP_HOST"], "printblur.com", $actual_link);
    }
    if (!isset($robots_index) || !$robots_index) {
        $robots_index = 'index, follow, max-image-preview:large';
    }
    if (!empty($_GET) && (
        strpos($_SERVER["REQUEST_URI"], '/c/') !== false || 
        strpos($_SERVER["REQUEST_URI"], '/shop/') !== false || 
        strpos($_SERVER["REQUEST_URI"], '/explore/') !== false || 
        strpos($_SERVER["REQUEST_URI"], '/blog/') !== false)
    ) {
        $ignoreParams = ["utm_id", "utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content", "adgroupid", "campaignid", "gclid", "zarsrc", "fbclid", "gbraid", "wbraid", "internal_source", "tr", "psafe_param", "gidzl", "zdlink", "affiliate_id", "clearCache", "clear_cache"];
        $isNoIndex = true;
        foreach ($_GET as $key => $value) {
            if (in_array($key, $ignoreParams)) {
                $isNoIndex = false;
                break;
            }
        }
        if ($isNoIndex) {
            $robots_index = 'noindex, follow';
        }
    }
    if (!empty($metaImage)) {
        $ogImage = getImageCdn($metaImage, 0, 0, true, false);
    }
 
    switch (Route::currentRouteName()) { /** Redefined Routes Name */
        case 'categoryOrTag':
        case 'product-detail':
        case 'productShort': { 
            if (\Request::get('current_route_name')) {
                $routeName = \Request::get('current_route_name');
            }
            break;
        }
        case 'category-list':   $routeName = 'category'; break;
        case 'tag::explore':    $routeName = 'tag'; break;
        default:                $routeName = Route::currentRouteName(); break;
    }
    if ($routeName == 'product' && !empty($_GET['spid'])) {
        $routeName = 'params_product';
    } else if ($routeName == 'category' && (!empty($displayedFilters['type_variant_id']) || !empty($displayedFilters['color_variant_id']))) {
        $routeName = 'filter_category';
    }
    
    $metaConfig = getOption($routeName);
    if (!empty($metaData->meta_title)) { // by link
        $title = $metaData->meta_title;
    } else if (!empty($metaTitle)) { // by share
        $title = $metaTitle;
    } else if (!empty($metaConfig->title)) { // by seo template
        $title = $metaConfig->title;
    } 

    if (!empty($metaData->meta_description)) { // by link
        $description = $metaData->meta_description;
    } else if (!empty($metaDescription)) { // by share
        $description = $metaDescription;
    } else if (!empty($metaConfig->description)) { // by seo template
        $description = $metaConfig->description;
    } 

    if (!empty($metaData->meta_keywords)) { // by link
        $keywords = $metaData->meta_keywords;
    } else if (!empty($metaKeywords)) { // by share
        $keywords = $metaKeywords;
    } else if (!empty($metaConfig->keywords)) { // by seo template
        $keywords = $metaConfig->keywords;
    } 

    $replaceVariable = [
        '{name}' => '', 
        '{store_name}' => '', 
        '{name_category}' => '', 
        '{name_type}' => (!empty($displayedFilters['type_variant_id'])) ? $displayedFilters['type_variant_id'] : '', 
        '{name_size}' => (!empty($displayedFilters['size_variant_id'])) ? $displayedFilters['size_variant_id'] : '', 
        '{name_style}' => (!empty($displayedFilters['style_variant_id'])) ? $displayedFilters['style_variant_id'] : '', 
        '{name_color}' => (!empty($displayedFilters['color_variant_id'])) ? $displayedFilters['color_variant_id'] : '', 
        '{name_shop}' => '',
        '{name_brand}' => '', 
        '{product_id}' => '', 
        '{name_price}' => '', 
        '{site_name}' => $siteName, 
        '{created_at}' => '',
        '{count}' => (!empty($meta['total_count'])) ? $meta['total_count'] : '',
        '{discount_percent}' => ''
    ];
    if (!empty($flashSale->sale_percent)) {
        $replaceVariable['{discount_percent}'] = $flashSale->sale_percent . '% OFF';
    }
    if (!empty($totalCount)) {
        $replaceVariable['{count}'] = $totalCount;
    }
    $dateFormat = 'm d, Y';
    switch ($routeName) {
        case 'home':
            $replaceVariable['{name}'] = __('Trang chủ');
            break;
        case 'category':
        case 'filter_category':
        case 'archive':
            if (!empty($category['image_url'])) {
                $ogImage = getImageCdn($category['image_url'], 540, 540, true, false);
            } 
            $replaceVariable['{name}'] = (!empty($category['name'])) ? $category['name'] : '';
            $replaceVariable['{name_category}'] = $replaceVariable['{name}'];
            $replaceVariable['{created_at}'] = (!empty($category['created_at'])) ? date($dateFormat, strtotime($category['created_at'])) : date($dateFormat);
            break;
        case 'product':
        case 'params_product':
            if (!empty($product['image_url'])) {
                $ogImage = getImageCdn($product['image_url'], 960, 960, true, false);
            }
            if (!empty($category['name'])) {
                $replaceVariable['{name_category}'] = $category['name'];
            }
            if (!empty($product['user']['name'])) {
                $replaceVariable['{store_name}'] = ucfirst($product['user']['name']);
                $replaceVariable['{name_shop}'] = ucfirst($product['user']['name']);
            }
            $replaceVariable['{name_brand}'] = (!empty($product['brand']['name'])) ? ucfirst($product['brand']['name']) : '';
            $replaceVariable['{name_price}'] = (!empty($product['display_price'])) ? $product['display_price'] : '';
            $replaceVariable['{name}'] = (!empty($product['name'])) ? ucfirst($product['name']) : '';
            $replaceVariable['{product_id}'] = (!empty($product['id'])) ? $product['id'] : '';
            $replaceVariable['{created_at}'] = (!empty($product['created_at'])) ? date($dateFormat, strtotime($product['created_at'])) : date($dateFormat);
            if (!empty($product['default_sku_id'])) {
                $variants = \Illuminate\Support\Facades\DB::table('product_sku_value')
                            ->join('product_variant', 'product_sku_value.variant_id', '=', 'product_variant.id')
                            ->join('product_variant_option', 'product_sku_value.variant_option_id', '=', 'product_variant_option.id')
                            ->select([
                                'product_variant.name as variant_name', 
                                'product_variant.slug as variant_slug', 
                                'product_variant_option.name as variant_option_name', 
                                'product_variant_option.code as variant_option_code', 
                                'product_variant_option.slug as variant_option_slug'
                            ])
                            ->where('product_sku_value.sku_id', '=', $product['default_sku_id'])
                            ->get();
                foreach ($variants as $item) {
                    switch (strtolower($item->variant_slug)) {
                        case 'type':
                            $replaceVariable['{name_type}'] = ucfirst($item->variant_option_name);
                            break;

                        case 'style':
                            $replaceVariable['{name_style}'] = ucfirst($item->variant_option_name);
                            break;

                        case 'color':
                            $replaceVariable['{name_color}'] = ucfirst($item->variant_option_name);
                            break;

                        case 'size':
                            $replaceVariable['{name_size}'] = ucfirst($item->variant_option_name);
                            break;
                        
                        default:
                            # code...
                            break;
                    }
                }
            }
            break;
        case 'news':
            $replaceVariable['{name}'] = __('Tin tức');
            break;
        case 'post':
            if (!empty($post['image_url'])) {
                $ogImage = getImageCdn($post['image_url'], 540, 540, true, false);
            }
            $replaceVariable['{name}'] = (!empty($post['name'])) ? $post['name'] : '';
            $replaceVariable['{created_at}'] = (!empty($post['created_at'])) ? date($dateFormat, strtotime($post['created_at'])) : date($dateFormat);
            break;
        case 'search':
            $replaceVariable['{name}'] = (isset($query)) ? ucfirst($query) : '';
            break;
        case 'brand':
            $replaceVariable['{name}'] = (!empty($brand['name'])) ? ucfirst($brand['name']) : '';
            break;
        case 'tag':
            $replaceVariable['{name}'] = (!empty($tagTitle)) ? ucfirst($tagTitle) : '';
            break;
        case 'seller':
            $replaceVariable['{name}'] = (!empty($seller['name'])) ? ucfirst($seller['name']) : '';
            break;
    }

    if (in_array($locale, ['en','us', 'uk', 'ca', 'au']) && !empty($replaceVariable['{name_type}'])) {
        $replaceVariable['{name_type}'] .= "'s";
    }

    if (in_array($routeName, ['product', 'params_product'])) {
        $metaTemplate = getOption('params_product');
        $cloneReplaceVariable = $replaceVariable;
        unset($cloneReplaceVariable['{name_type}']);
        unset($cloneReplaceVariable['{name_style}']);
        unset($cloneReplaceVariable['{name_color}']);
        unset($cloneReplaceVariable['{name_size}']);
        $replaceFrom = array_keys($cloneReplaceVariable);
        $replaceTo = array_values($cloneReplaceVariable);
        if (!empty($metaTemplate->title)) {
            $titleBak = preg_replace('!\s+!', ' ', str_replace($replaceFrom, $replaceTo, $metaTemplate->title));
        }
        if (!empty($metaTemplate->description)) {
            $descriptionBak = preg_replace('!\s+!', ' ', str_replace($replaceFrom, $replaceTo, $metaTemplate->description));
        }
        if (!empty($metaTemplate->keywords)) {
            $keywordsBak = preg_replace('!\s+!', ' ', str_replace($replaceFrom, $replaceTo, $metaTemplate->keywords));
        }
    }
    $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));

    
    if (isset($isErrorPage) && $isErrorPage) {
        $title = __("Sorry - 404 Page Not Found | " . $siteName);
        $robots_index = "noindex, follow";
    }

    if (isset($product) && isset($product['image_url'])) {
        $imageProductMineType = getUrlMimeType($product['image_url']);
    }

    $parsedUrl = parse_url(url()->current());
    $pathName = (!empty($parsedUrl['path'])) ? $parsedUrl['path'] : '/';
   
    $configHreflangs = \Illuminate\Support\Facades\DB::table('hreflang_config')
                                                ->where('url', '=', $pathName)
                                                ->first();
    if (!empty($configHreflangs->content)) {
        $hreflangs = json_decode($configHreflangs->content, true);
    }

    $url = \Request::url();
    $params = \Request::all();
    $paramsPrev = $paramsNext = $params;
    $isShowPaginatePrev = false;
    $isShowPaginateNext = false;
    if (!empty($meta) && key_exists('has_next', $meta)) {
        if ($meta['has_next'] == false) {
            if (!empty($meta['is_post_page'])) {
                if (isset($meta['page_id']) && $meta['page_id'] > 0) {
                    if ($paramsPrev['page'] == 1) {
                        unset($paramsPrev['page']);
                    } else {
                        $paramsPrev['page'] -= 1;
                    }
                    $isShowPaginatePrev = true;
                }
            } else {
                if (isset($meta['page_id']) && $meta['page_id'] > 0) {
                    if ($paramsPrev['page_id'] == 1) {
                        unset($paramsPrev['page_id']);
                    } else {
                        $paramsPrev['page_id'] -= 1;
                    }
                    $isShowPaginatePrev = true;
                }
            }
        } else {
            $isShowPaginatePrev = true;
            $isShowPaginateNext = true;
            if (isset($meta['page_id']) && $meta['page_id'] == 0) {
                if (!empty($meta['is_post_page'])) {
                    $paramsNext['page'] = 2;
                } else {
                    $paramsNext['page_id'] = 1;
                }
                $isShowPaginatePrev = false;
                $isShowPaginateNext = true;
            } else {
                if (!empty($meta['is_post_page'])) {
                    $paramsNext['page'] += 1;
                    if ((int)$paramsPrev['page'] == 1){
                        unset($paramsPrev['page']);
                        $isShowPaginatePrev = false;
                    } else {
                        $paramsPrev['page'] -= 1;
                    }
                } else {
                    $paramsNext['page_id'] += 1;
                    if ($paramsPrev['page_id'] == 1){
                        unset($paramsPrev['page_id']);
                    } else {
                        $paramsPrev['page_id'] -= 1;
                    }
                }
            }
        }
    }
    
    try {
        header('Link: <' . $actual_link . '>; rel="canonical"');
    } catch (Exception $_) {}

    $_SERVER['FINAL_TITLE'] = $title;
    $_SERVER['FINAL_KEYWORDS'] = $keywords;
    $_SERVER['FINAL_DESCRIPTION'] = $description;
    $_SERVER['FINAL_IMAGE'] = $ogImage;

?>

<meta charset="utf-8">
<meta http-equiv="content-language" content="{{ (!empty($languages[$locale])) ? $languages[$locale] : 'en' }}" />
<meta http-equiv="audience" content="General" />
<title>{{ $title }}</title>
<meta name="keywords" content="{{ $keywords }}">
<meta name="description" content="{{ $description }}">
@if (!empty($imageProductMineType))
    <link rel="preload" fetchpriority="high" as="image" href="{{ getImageCdn($product['image_url'], 960, 960, false, true) }}" type="image/webp">
@endif

@if (config('seo::default.allow_index', true))
<meta name="robots" content="{{ $robots_index }}" />
<link rel="canonical" href="{{ $actual_link }}" />
@else
<meta name="robots" content="noindex, nofollow" />
@endif

<meta name="revisit-after" content="1 days" />
<meta name="resource-type" content="Document" />
<meta name="distribution" content="Global" />
@if(!empty($_SERVER['HTTP_HOST']))
<meta name="copyright" content="Copyright © {{ date('Y') }} by {{ strtoupper($_SERVER['HTTP_HOST']) }}" />
<meta name="author" content="{{ $_SERVER['HTTP_HOST'] }}" />
@endif
<meta name="abstract" content="{{__('Global online marketplace, where people come together to make, sell, buy, and collect unique items')}}" />

<meta property="og:locale" content="{{ (!empty($languages[$locale])) ? $languages[$locale] : 'en' }}" />
<meta property="og:type" content="{{ getOgType($routeName) }}" />
<meta property="og:title" content="{{ $title }}" />
<meta property="og:description" content="{{ $description }}" />
<meta property="og:url" content="{{ $actual_link }}" />
<meta property="og:site_name" content="{{ $siteName }}" />
<meta property="og:image" content="{{ $ogImage }}" />
<meta property="og:image:secure_url" content="{{ $ogImage }}" />
<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="700" />
<meta property="og:image:alt" content="{{ $title }}" />
<meta property="fb:app_id" content="{{ getOption('fb.app_id') }}"/>
<meta property="fb:pages" content="{{ getOption('fb.page_id') }}"/>
<meta name="og:email" content="{{ getOption('email.support', 'support@printerval.com') }}"/>
<meta name="og:phone_number" content="{{ getOption('general.phone_number', '+1586 325 6268') }}"/>

<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="{{ $title }}">
<meta name="twitter:description" content="{{ $description }}">
<meta name="twitter:image" content="{{ $ogImage }}">

@if(!empty($hreflangs))
<link rel="alternate" href="{{ url(str_replace('/us', '/', $hreflangs[array_keys($hreflangs)[0]])) }}" hreflang="x-default" />
    @foreach ($hreflangs as $hrefLocale => $href)
        @if(!empty($href))
            <link rel="alternate" href="{{ url($href) }}" hreflang="{{ (!empty($languageHrefs[$hrefLocale])) ? $languageHrefs[$hrefLocale] : 'en' }}" />
        @endif
    @endforeach
@endif

@if ($isShowPaginatePrev)
<link rel="prev" href="{{ !empty($paramsPrev) ? \Request::url() . '?' . http_build_query($paramsPrev) : \Request::url() }}" />
@endif
@if ($isShowPaginateNext)
<link rel="next" href="{{ \Request::url() . '?' . http_build_query($paramsNext)}}" />  
@endif

@if (!empty($product['id']))
    <meta name="product-id" content="{{ $product['id'] }}">
@endif