<?php

namespace app\foreignone;

use app\ThemesUtil;
use engine\http\errors\NotFound;
use engine\http\errors\PermanentRedirect;
use engine\http\Response;

class MainHandler
    extends BaseHandler
{
    public function GET_index(): Response {
        global $config;

        $posts_lang = PostLanguage::English;
        $posts = Post::getList(0, 3,
            include_hidden: isAdmin(),
            filter_by_lang: $posts_lang);

        $this->skin->meta->title = lang('meta_index_title');
        $this->skin->meta->description = lang('meta_index_description');
        $this->skin->meta->url = 'https://'.$config['domain'].'/';
        $this->skin->meta->image = 'https://'.$config['domain'].'/img/4in1-preview.jpg';
        $this->skin->meta->setSocial('og:type', 'website');

        $this->skin->options->isIndex = true;

        $this->skin->set([
            'posts' => $posts,
            'posts_lang' => $posts_lang,
            'versions' => $config['book_versions']
        ]);
        return $this->skin->renderPage('index.twig');
    }

    public function GET_about() { throw new PermanentRedirect('/info/'); }
    public function GET_contacts() { throw new PermanentRedirect('/info/'); }

    public function GET_page(): Response {
        global $config;
        list($name) = $this->input('name');

        $page = Page::getByName($name);
        if (!$page) {
            if (isAdmin()) {
                $this->skin->title = $name;
                return $this->skin->renderPage('admin_page_new.twig', [
                    'short_name' => $name
                ]);
            }
            throw new NotFound();
        }

        if (!isAdmin() && !$page->visible)
            throw new NotFound();

        $bc = null;
        if ($page) {
            $this->skin->meta->url = 'https://'.$config['domain'].$page->getUrl();
            $this->skin->meta->title = $page->title;

            if ($page->parentId) {
                $bc = [];
                $parent = $page;
                while ($parent?->parentId) {
                    $parent = Page::getById($parent->parentId);
                    if ($parent)
                        $bc[] = ['url' => $parent->getUrl(), 'text' => $parent->title];
                }
                if (empty($bc))
                    $bc = null;
            }

            if ($page->shortName == 'info')
                $this->skin->options->headSection = 'about';
            else if ($page->shortName == $config['wiki_root'])
                $this->skin->options->headSection = $page->shortName;
        }

        $this->skin->title = $page ? $page->title : '???';
        return $this->skin->renderPage('page.twig', [
            'page' => $page,
            'html' => $page->getHtml(isRetina(), ThemesUtil::getUserTheme()),
            'bc' => $bc,
            'delete_token' => $this->getCSRF('delpage'.$page->shortName)
        ]);
    }

    public function GET_post(): Response {
        global $config;
        list($name, $input_lang) = $this->input('name, lang');

        $lang = null;
        try {
            if ($input_lang)
                $lang = PostLanguage::from($input_lang);
        } catch (\ValueError $e) {
            throw new NotFound($e->getMessage());
        }

        if (!$lang)
            $lang = PostLanguage::getDefault();

        $post = Post::getByName($name);
        if (!$post || (!$post->visible && !isAdmin()))
            throw new NotFound();

        if ($lang == PostLanguage::getDefault() && $input_lang == $lang->value)
            throw new PermanentRedirect($post->getUrl());
        if (!$post->hasLang($lang))
            throw new NotFound('no text for language '.$lang->name);
        if (!$post->visible && !isAdmin())
            throw new NotFound();

        $pt = $post->getText($lang);

        $other_langs = [];
        foreach (PostLanguage::cases() as $pl) {
            if ($pl == $lang)
                continue;
            if ($post->hasLang($pl))
                $other_langs[] = $pl->value;
        }

        $this->skin->meta->title = $pt->title;
        $this->skin->meta->description = $pt->getDescriptionPreview(155);
        $this->skin->meta->url = 'https://'.$config['domain'].$post->getUrl();
        if ($pt->keywords)
            $this->skin->meta->keywords = $pt->keywords;
        if (($img = $pt->getFirstImage()) !== null)
            $this->skin->meta->image = $img->getDirectUrl();

        $this->skin->title = $pt->title;
        $this->skin->options->articlesLang = $lang->value;
        $this->skin->options->wide = $pt->hasTableOfContents();
        return $this->skin->renderPage('post.twig', [
            'post' => $post,
            'pt' => $pt,
            'html' => $pt->getHtml(isRetina(), ThemesUtil::getUserTheme()),
            'selected_lang' => $lang->value,
            'other_langs' => $other_langs,
            'delete_token' => $this->getCSRF('delpost'.$post->id)
        ]);
    }

    public function GET_rss() {
        global $config;

        $lang = PostLanguage::getDefault();
        $items = array_map(function(Post $post) use ($lang, $config) {
            $pt = $post->getText($lang);
            $url = $post->getUrl();
            if (!str_starts_with($url, 'https://'))
                $url = 'https://'.$config['domain'].$url;
            return [
                'title' => $pt->title,
                'link' => $url,
                'pub_date' => date(DATE_RSS, $post->getTimestamp()),
                'description' => $pt->getDescriptionPreview(500)
            ];
        }, Post::getList(0, 20, filter_by_lang: $lang));

        $body = $this->skin->render('rss.twig', [
            'title' => lang('site_title'),
            'link' => 'https://'.$config['domain'],
            'rss_link' => 'https://'.$config['domain'].'/feed.rss',
            'items' => $items
        ]);

        header('Content-Type: application/rss+xml; charset=utf-8');
        echo $body;
        exit;
    }

    public function GET_articles(): Response {
        list($lang) = $this->input('lang');
        if ($lang) {
            $lang = PostLanguage::tryFrom($lang);
            if (!$lang || $lang == PostLanguage::getDefault())
                throw new PermanentRedirect('/articles/');
        } else {
            $lang = PostLanguage::getDefault();
        }

        $posts = Post::getList(
            include_hidden: isAdmin(),
            filter_by_lang: $lang);

        $this->skin->title = lang('articles');
        $this->skin->meta->description = lang('blog_expl_'.$lang->value);
        $this->skin->options->headSection = 'articles';
        return $this->skin->renderPage('articles.twig', [
            'posts' => $posts,
            'selected_lang' => $lang->value
        ]);
    }
}