<?php
class SitemapGenerator
{
    protected $webRoot;
    protected $webindexPath;

    public function __construct()
    {
        $ssl = $_SERVER['SSL_SESSION_ID'] || strtolower($_SERVER['HTTPS']) === 'on' || (string)$_SERVER['HTTPS'] === '1';
        $this->webRoot = ($ssl ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . '/';

        list($scriptPath) = get_included_files();
        $this->webindexPath = dirname($scriptPath) . DIRECTORY_SEPARATOR . 'webindex' . DIRECTORY_SEPARATOR;
    }

    public function execute()
    {
        header('Content-Type: text/xml');
        header('Expires: ' . gmdate("D, d M Y H:i:s") . " GMT");
        header('Cache-Control: no-cache, must-revalidate');
        header('Pragma: no-cache');

        $this->outputStartTags();
        $this->outputChapterUrls();
        $this->outputEndTags();
    }

    protected function outputStartTags()
    {
        echo '<?xml version="1.0" encoding="UTF-8"?>' . chr(10) .
            '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . chr(10);
    }

    protected function outputEndTags()
    {
        echo '</urlset>';
    }

    protected function outputChapterUrls()
    {
        $productFiles = glob($this->webindexPath . 'products-*.json');
        if ($productFiles) {
            foreach($productFiles as $productFile) {
                $products = $this->getData($productFile);
                if ($products) {
                    foreach($products as $product) {
                        $this->outputChapters($product);
                    }
                }
            }
        }
    }

    /**
     * @param array $product
     */
    protected function outputChapters($product)
    {
        if (isset($product['id'], $product['lc'], $product['uriName'])) {
            $uriName = $product['uriName'];
            $language = $product['lc'];
            $filename = $product['id'] . '-' . $language . '.json';
            $chapters = $this->getData($filename);
            if ($chapters) {
                foreach($chapters as $chapter) {
                    echo $this->renderEntry($this->webRoot . $language . '/' . $uriName . '/' . $chapter['path'] . '/');
                }
            }
        }
    }

    /**
     * @param string $url
     * @return string
     */
    protected function renderEntry($url)
    {
        return '<url><loc>' . $url . '</loc></url>';
    }

    /**
     * @param string $filename
     * @return null|array
     */
    protected function getData($filename)
    {
        $data = null;
        $content = file_get_contents(strpos($filename, '/') === 0 ? $filename : $this->webindexPath . $filename);
        if ($content) {
            $content = json_decode($content, true);
            if (!empty($content['data'])) {
                $data = $content['data'];
            }
        }
        return $data;
    }
}

$sitemapGenerator = new SitemapGenerator();
$sitemapGenerator->execute();

