<?php

require_once __DIR__.'/../src/init.php';

global $config;

use samdark\sitemap\Sitemap;
use app\foreignone\files\ArchiveType;
use app\foreignone\Post;
use app\foreignone\PostLanguage;

$db = getDB();

$sitemap = new Sitemap($config['sitemap_dir'].'/sitemap.xml');
$addr = 'https://'.$config['domain'];

$sitemap->addItem("{$addr}/",
    changeFrequency: Sitemap::WEEKLY);

// pages
$q = $db->query("SELECT short_name FROM pages");
while ($row = $db->fetch($q)) {
    $sitemap->addItem("{$addr}/{$row['short_name']}/",
        changeFrequency: Sitemap::WEEKLY);
}

// files
$sitemap->addItem("{$addr}/files/",
    changeFrequency: Sitemap::WEEKLY);
foreach (ArchiveType::cases() as $fc) {
    $sitemap->addItem("{$addr}/files/".$fc->value.'/',
        changeFrequency: Sitemap::MONTHLY);
}

foreach ([ArchiveType::WilliamFriedman, ArchiveType::Baconiana] as $fc) {
    $q = $db->query("SELECT id FROM {$fc->value}_collection WHERE type='folder'");
    while ($row = $db->fetch($q)) {
        $sitemap->addItem("{$addr}/files/".$fc->value.'/'.$row['id'].'/',
            changeFrequency: Sitemap::MONTHLY);
    }
}

$q = $db->query("SELECT id FROM books WHERE type='folder' AND external=0");
while ($row = $db->fetch($q)) {
    $sitemap->addItem("{$addr}/files/".$row['id'].'/',
        changeFrequency: Sitemap::MONTHLY);
}

foreach (PostLanguage::cases() as $pl) {
   $sitemap->addItem("{$addr}/articles/".($pl != PostLanguage::English ? '?lang='.$pl->value : ''),
       changeFrequency: Sitemap::WEEKLY);

   $q = $db->query("SELECT * FROM posts WHERE visible=1");
   while ($row = $db->fetch($q)) {
       $post = new Post($row);
       $sitemap->addItem("{$addr}".$post->getUrl($pl),
           changeFrequency: Sitemap::WEEKLY);
   }
}

$sitemap->write();