<?php
include("incl/database.php");
include("incl/factory.php");
include("incl/pages.php");

$pages = search_database("SELECT id, title FROM Article", []);
$navdata = search_database("SELECT id, title FROM Article WHERE category != ?", ["article"]);
$articleData = search_database("SELECT id, title FROM Article WHERE category = ?", ["article"]);
$articleIds = get_article_ids($articleData);

$currentId = get_page_id();
$page = null;
$pageContent = "";
$article = "";
if (page_exists($pages, $currentId)) {
    $page = get_page($currentId);
    if ($page["category"] == "article") {
        $pageContent = "articles.php";
    } else {
        $pageContent = $page["content"];
    }

    if (in_array($currentId, $articleIds)) {
        if ($currentId == 5) {
            $article = "pages/articles/articles.php";
        } else {
            $article = "pages/articles/" . $page["content"];
        }
    }
} else {
    $pageContent = "404.php";
}

$title = $page["title"];
?>
<!DOCTYPE html>
<html lang ="sv">
    <head>
        <meta charset="utf-8">
        <title><?= $title ?></title>
        <link rel="stylesheet" href="css/layout.css"/>
        <link rel="stylesheet" href="css/themes/default.css"/>
    </head>
    <body>
        <main>
            <div class="container">
                <h1>Begravningsmuseum Online</h1>
            </div>
            <?php echo gen_navigation($navdata, $currentId); ?>
            <?php echo in_array($currentId, $articleIds) ? gen_articlelist($articleData, $currentId) : ""; ?>
            <div class="container">
                <article>
                    <?= "<h2>$title</h2>" ?>
                    <?php include("pages/" . $pageContent); ?>
                    <?= "Publicerad {$page["pubdate"]} {$page["author"]}"; ?>
                </article>
                <footer>
                    <p>Begravningmuseum Online &copy; 2010 - 1017</p>
                    Validatorer:
                    <a href="https://validator.w3.org/check/referer">HTML5</a>
                    <a href="https://jigsaw.w3.org/css-validator/check/referer">CSS</a>
                </footer>
            </div>
        </main>
    </body>
</html>
