<?php 

namespace App\Libs\Services;

/**
* Transforms values based on array on transformation rules
*/
use ContentTypes;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
use App\Models\GenericBackoffice\Entry;
use Config;
use File;
use Storage;

class SitemapGenerator
{
    private $languages;
    private $defaultLanguage;
    private $currentLanguage;

    public function buildSitemap() {
        $languages = LaravelLocalization::getSupportedLocales();

        $this->languages = $languages;
        $this->defaultLanguage = LaravelLocalization::getDefaultLocale();

        $pages = Entry::full()
            ->where('status', 'published')
            // ->where('no_sitemap', 0)
            ->orderBy('position', 'asc')
            ->get();

        $langsUrls = array();
        foreach ($languages as $locale => $localeData) {
            $this->currentLanguage = $locale;
            $langsUrls[$this->currentLanguage] = array();
            $i = 0;
            foreach ($pages as $page) {
                $templateId = $page->template;
                $template = Config::get('backoffice.generic.page.templates.' . $templateId);

                if ($page->slug == '404') {
                    continue;
                }

                if ($page->uri == '/') {
                    $pagePrio = 1;
                } else {
                    $pagePrio = 1 - (sizeof(explode('/', $page->uri)) - 1) / 10;
                }

                if (isset($template['view']) && $template['view']) {
                    $langsUrls[$this->currentLanguage][$i] = $this->_generateSitemapUrl($page, null, $pagePrio);
                    $i++;
                }

                $templateCfg = false;
                if (isset($template['contentType'])) {
                    $templateCfgContentType = ContentTypes::find($template['contentType']);
                    $modelClass = $templateCfgContentType->getModelType();
                    $templateCfg = $modelClass::full()
                        ->where('entry_id', $page->id)
                        ->first();
                }

                if (isset($template['detailContentType']) && $template['detailContentType']) {
                    $detailType = $template['detailContentType'];
                    $contentType = ContentTypes::find($detailType);
                    $modelClass = $contentType->getModelType();
                    $q = $modelClass::full()
                        ->where('status', 'published')
                        ->orderBy('position', 'asc');

                    /*
                    $filterField = false;
                    if ($contentType->getTypeFilterField()) {
                        $filterField = $contentType->getTypeFilterField();
                    }
                    */

                    if (isset($template['detailTypeFilter']) && $template['detailTypeFilter']) {
                        $q->whereIn('type', $template['detailTypeFilter']);
                    }


                    $pageWo = $page->websites->first();
                    $pageWoLang = $pageWo->languages->findByLocale($this->currentLanguage);

                    $objects = $q->get();

                    $prio = isset($template['sitemapPrio']) ? $template['sitemapPrio'] : '0.6';
                    foreach ($objects as $object) {
                        $parentUri = $pageWoLang->lang_uri;

                        if (isset($template['typeFilterField']) && $templateCfg) {
                            if ($templateCfg->$template['typeFilterField'] !== $object->$filterField) {
                                continue;
                            }
                        }
                        /*
                        if ($filterField) {
                            $baseUris = $contentType->getBaseUri();
                            $parentUri = $baseUris[$object->$filterField];
                        }
                        */
                        $langsUrls[$this->currentLanguage][$i] = $this->_generateSitemapUrl($object, $parentUri, $prio);
                        $i++;
                    }
                }
            }
        }

        /* Build XML */

        $out = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
        $out .= "<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\" xmlns:xhtml=\"http://www.w3.org/1999/xhtml\">\n";
        foreach ($langsUrls as $lang => $langUrls) {
            foreach ($langUrls as $i => $url) {
                $out .= "\t<url>\n";
                $out .= "\t\t<loc>" . $url['loc'] . "</loc>\n";

                if (sizeof($languages) > 1) {
                    foreach ($languages as $code => $language) {
                        $out .= "\t\t<xhtml:link rel=\"alternate\" hreflang=\"{$code}\" href=\""
                            . $langsUrls[$code][$i]['loc'] . "\" />\n";
                    }
                }
                $out .= "\t\t<lastmod>" . $url['lastmod'] . "</lastmod>\n";
                $out .= "\t\t<changefreq>weekly</changefreq>\n";
                $out .= "\t\t<priority>" . $url['priority'] . "</priority>\n";
                $out .= "\t</url>\n";
            }
        }

        $out .= "</urlset>";

        File::put(Storage::path(Config::get('path.internal.sitemap')) . '/sitemap.xml', $out);
    }

    private function _generateSitemapUrl ($object, $parentSlug = false, $prio = "0.8") {
        $sitemapUrl = array();
        $wo = $object->websites->first();
        $woLang = $wo->languages->findByLocale($this->currentLanguage);
        $langPrefix = $this->currentLanguage;

        $sitemapUrl['language'] = $this->currentLanguage;
        $sitemapUrl['loc'] = url($langPrefix . ($parentSlug ? $parentSlug . '/' . $woLang->lang_slug : $woLang->lang_uri));
        $sitemapUrl['lastmod'] = date("Y-m-d",strtotime($object->updated_at));
        $sitemapUrl['priority'] = $prio;
        return $sitemapUrl;
    }
}