<?php

declare(strict_types=1);

header('Content-Type: text/html; charset=UTF-8');

require_once __DIR__ . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'app.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_public_session.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_install.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_public_member_auth.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_template.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_page_counter.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_blog.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_seo.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_admin_nav_visibility.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_plugins.php';

fate_public_session_start();
fate_install_maybe_redirect();

$fatePublicMember = fate_public_member_current();
$frontendDb = fate_frontend_db_bootstrap();
$pdo = $frontendDb['pdo'];
$dbError = $frontendDb['dbError'];

if ($fatePublicMember !== null && $pdo instanceof PDO) {
    require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_member_profile.php';
    fate_public_member_ensure_admin_flag($pdo);
    fate_member_profile_hydrate_session($pdo, (int) $fatePublicMember['id']);
    $fatePublicMember = fate_public_member_current();
}

if (!fate_blog_enabled()) {
    http_response_code(404);
    echo '<!DOCTYPE html><html lang="zh-Hant"><head><meta charset="UTF-8"><title>找不到頁面</title></head><body><p>此功能尚未啟用。</p><p><a href="./">返回首頁</a></p></body></html>';
    exit;
}

$fateAdminNavVisible = fate_admin_nav_visible_for_frontend();
$fateForumNavVisible = fate_store_forum_plugin_active();
$fateBlogNavVisible = true;
$fateBlogNavLabel = fate_blog_nav_label();

$blogCanManage = $pdo instanceof PDO && fate_blog_viewer_can_manage($pdo);
$csrf = fate_public_member_csrf_token();

$msgOk = isset($_SESSION['fate_blog_flash_ok']) ? (string) $_SESSION['fate_blog_flash_ok'] : '';
$msgBad = isset($_SESSION['fate_blog_flash_bad']) ? (string) $_SESSION['fate_blog_flash_bad'] : '';
unset($_SESSION['fate_blog_flash_ok'], $_SESSION['fate_blog_flash_bad']);

$categoryFilter = isset($_GET['cat']) ? max(0, (int) $_GET['cat']) : 0;
$page = isset($_GET['page']) ? max(1, (int) $_GET['page']) : 1;
$compose = isset($_GET['compose']) && $_GET['compose'] === '1';
$editPostId = isset($_GET['edit']) ? max(0, (int) $_GET['edit']) : 0;
$editMode = false;
$editPost = null;
$manageTab = isset($_GET['manage']) && is_string($_GET['manage']) ? $_GET['manage'] : '';
if (!in_array($manageTab, ['', 'settings', 'categories'], true)) {
    $manageTab = '';
}

if ($compose && !$blogCanManage) {
    header('Location: blog.php', true, 302);
    exit;
}

if ($editPostId > 0 && !$blogCanManage) {
    header('Location: blog.php', true, 302);
    exit;
}

if ($manageTab !== '' && !$blogCanManage) {
    header('Location: blog.php', true, 302);
    exit;
}

if ($compose && $manageTab !== '') {
    $manageTab = '';
}

if ($editPostId > 0) {
    $compose = false;
    $manageTab = '';
    if ($pdo instanceof PDO) {
        fate_blog_ensure_tables($pdo);
        $editPost = fate_blog_post_get($pdo, $editPostId, true);
    }
    if ($editPost === null) {
        header('Location: blog.php', true, 302);
        exit;
    }
    $editMode = true;
}

if ($compose && $editPostId > 0) {
    $editPostId = 0;
    $editMode = false;
    $editPost = null;
}

$blogSettings = fate_blog_settings();

$blogCategories = $pdo instanceof PDO ? fate_blog_categories_list($pdo, $blogCanManage) : [];
$perPage = fate_blog_posts_per_page();
$listResult = ['items' => [], 'total' => 0];
if ($pdo instanceof PDO) {
    fate_blog_ensure_tables($pdo);
    $listResult = fate_blog_posts_list(
        $pdo,
        $categoryFilter > 0 ? $categoryFilter : null,
        null,
        $page,
        $perPage,
        $blogCanManage
    );
}
$blogPosts = $listResult['items'];
$blogTotal = $listResult['total'];
$blogPages = max(1, (int) ceil($blogTotal / $perPage));
if ($page > $blogPages) {
    $page = $blogPages;
}

$buildBlogUrl = static function (?int $cat = null, ?int $p = null, bool $openCompose = false, ?string $manage = null, ?int $editId = null): string {
    $q = [];
    if ($manage !== null && $manage !== '') {
        $q['manage'] = $manage;
    }
    if ($editId !== null && $editId > 0) {
        $q['edit'] = (string) $editId;
        unset($q['manage']);
    }
    if ($cat !== null && $cat > 0) {
        $q['cat'] = (string) $cat;
    }
    if ($p !== null && $p > 1) {
        $q['page'] = (string) max(1, $p);
    }
    if ($openCompose) {
        $q['compose'] = '1';
        unset($q['manage'], $q['edit']);
    }
    $url = 'blog.php';
    if ($q !== []) {
        $url .= '?' . http_build_query($q);
    }

    return $url;
};

$fatePageStatsKey = 'blog.index';
$fatePageTitle = $fateBlogNavLabel;
$fateSeoContext = fate_seo_simple_page_context($fatePageTitle, '站內文章與公告');
$fatePageStatsFooter = fate_page_stats_for_footer($pdo, $fatePageStatsKey, fate_page_stats_member_id($fatePublicMember), $fatePageTitle);
$fatePageHitCount = $fatePageStatsFooter['fatePageHitCount'];
$fatePageStatsDbOk = $fatePageStatsFooter['fatePageStatsDbOk'];

$sidebarLayout = fate_blog_sidebar_layout_vars($pdo instanceof PDO ? $pdo : null);

fate_render_blog(array_merge(compact(
    'pdo',
    'dbError',
    'fatePublicMember',
    'fateAdminNavVisible',
    'fateForumNavVisible',
    'fateBlogNavVisible',
    'fateBlogNavLabel',
    'blogCanManage',
    'csrf',
    'msgOk',
    'msgBad',
    'blogCategories',
    'blogPosts',
    'blogTotal',
    'blogPages',
    'page',
    'categoryFilter',
    'compose',
    'editMode',
    'editPostId',
    'editPost',
    'manageTab',
    'blogSettings',
    'buildBlogUrl',
    'perPage',
    'fatePageHitCount',
    'fatePageStatsDbOk',
    'fatePageTitle',
    'fateSeoContext'
), $sidebarLayout));
