<?php

declare(strict_types=1);

/**
 * BLOG 動作：save_post / delete_post / save_category / delete_category / toggle_hidden
 */

require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'app.php';
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_public_session.php';
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_public_member_auth.php';
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_blog.php';

fate_public_session_start();

function fate_blog_action_back(string $target, string $ok = '', string $bad = ''): void
{
    if ($ok !== '') {
        $_SESSION['fate_blog_flash_ok'] = $ok;
    }
    if ($bad !== '') {
        $_SESSION['fate_blog_flash_bad'] = $bad;
    }
    header('Location: ../' . ltrim($target, '/'), true, 303);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    fate_blog_action_back('blog.php', '', '無效的請求。');
}

$member = fate_public_member_current();
if ($member === null) {
    header('Location: ../login.php?next=' . rawurlencode('blog.php'), true, 302);
    exit;
}

$tok = isset($_POST['csrf']) && is_string($_POST['csrf']) ? $_POST['csrf'] : '';
if (!fate_public_member_csrf_check($tok)) {
    fate_blog_action_back('blog.php', '', '工作階段逾期，請重新整理後再試。');
}

$pdo = null;
try {
    require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'pdo.php';
    if (isset($GLOBALS['pdo']) && $GLOBALS['pdo'] instanceof PDO) {
        $pdo = $GLOBALS['pdo'];
    }
} catch (Throwable) {
    $pdo = null;
}

if (!$pdo instanceof PDO) {
    fate_blog_action_back('blog.php', '', '資料庫連線失敗。');
}

if (!fate_blog_viewer_can_manage($pdo)) {
    fate_blog_action_back('blog.php', '', '僅管理員可執行此操作。');
}

$action = isset($_POST['action']) && is_string($_POST['action']) ? $_POST['action'] : '';
$returnTo = isset($_POST['return_to']) && is_string($_POST['return_to']) ? trim($_POST['return_to']) : 'blog.php';
if ($returnTo === '' || str_contains($returnTo, '..') || preg_match('#^https?://#i', $returnTo) === 1) {
    $returnTo = 'blog.php';
}
if (!preg_match('#^(blog\.php(\?[a-z0-9_=&.-]+)?|blog_post\.php\?id=\d+(&edit=1)?)$#', $returnTo)) {
    $returnTo = 'blog.php';
}

function fate_blog_action_save_fail_back(int $postId, string $returnTo): string
{
    if ($postId > 0 && preg_match('#^blog\.php\?edit=\d+$#', $returnTo) === 1) {
        return $returnTo;
    }
    if ($postId > 0) {
        return 'blog_post.php?id=' . $postId . '&edit=1';
    }

    return 'blog.php?compose=1';
}

$memberId = (int) ($member['id'] ?? 0);

if ($action === 'save_post') {
    $postId = isset($_POST['post_id']) ? (int) $_POST['post_id'] : 0;
    $data = [
        'title' => $_POST['title'] ?? '',
        'body' => $_POST['body'] ?? '',
        'excerpt' => $_POST['excerpt'] ?? '',
        'category_id' => $_POST['category_id'] ?? 0,
        'slug' => $_POST['slug'] ?? '',
        'is_announcement' => !empty($_POST['is_announcement']),
        'is_published' => !empty($_POST['is_published']),
        'is_hidden' => !empty($_POST['is_hidden']),
    ];
    if (!isset($_POST['is_published'])) {
        $data['is_published'] = true;
    }
    $r = fate_blog_post_save($pdo, $data, $memberId, $postId);
    if ($r['ok']) {
        $successTarget = $returnTo;
        if (!preg_match('#^blog\.php(\?|$)|^blog_post\.php\?id=\d+#', $successTarget)) {
            $successTarget = 'blog_post.php?id=' . (int) $r['id'];
        }
        fate_blog_action_back($successTarget, '文章已儲存。', '');
    }
    fate_blog_action_back(fate_blog_action_save_fail_back($postId, $returnTo), '', $r['error'] ?? '儲存失敗。');
}

if ($action === 'delete_post') {
    $postId = isset($_POST['post_id']) ? (int) $_POST['post_id'] : 0;
    $r = fate_blog_post_delete($pdo, $postId);
    if ($r['ok']) {
        fate_blog_action_back('blog.php', '文章已刪除。', '');
    }
    fate_blog_action_back($returnTo, '', $r['error'] ?? '刪除失敗。');
}

if ($action === 'toggle_hidden') {
    $postId = isset($_POST['post_id']) ? (int) $_POST['post_id'] : 0;
    $hidden = !empty($_POST['hidden']);
    $r = fate_blog_post_set_hidden($pdo, $postId, $hidden);
    if ($r['ok']) {
        fate_blog_action_back($returnTo, $hidden ? '文章已隱藏。' : '文章已恢復顯示。', '');
    }
    fate_blog_action_back($returnTo, '', $r['error'] ?? '更新失敗。');
}

if ($action === 'save_category') {
    $categoryId = isset($_POST['category_id']) ? (int) $_POST['category_id'] : 0;
    $r = fate_blog_category_save($pdo, [
        'name' => $_POST['name'] ?? '',
        'slug' => $_POST['slug'] ?? '',
        'sort_order' => $_POST['sort_order'] ?? 0,
        'is_hidden' => !empty($_POST['is_hidden']),
    ], $categoryId);
    if ($r['ok']) {
        fate_blog_action_back('blog.php?manage=categories', '分類已儲存。', '');
    }
    fate_blog_action_back('blog.php?manage=categories', '', $r['error'] ?? '儲存分類失敗。');
}

if ($action === 'delete_category') {
    $categoryId = isset($_POST['category_id']) ? (int) $_POST['category_id'] : 0;
    $r = fate_blog_category_delete($pdo, $categoryId);
    if ($r['ok']) {
        fate_blog_action_back('blog.php?manage=categories', '分類已刪除。', '');
    }
    fate_blog_action_back('blog.php?manage=categories', '', $r['error'] ?? '刪除分類失敗。');
}

if ($action === 'save_settings') {
    $patch = [
        'enabled' => !empty($_POST['enabled']),
        'show_announcements_on_home' => !empty($_POST['show_announcements_on_home']),
        'posts_per_page' => $_POST['posts_per_page'] ?? 12,
        'home_announcements_limit' => $_POST['home_announcements_limit'] ?? 3,
        'nav_label' => $_POST['nav_label'] ?? '',
    ];
    if (fate_blog_settings_save($patch)) {
        fate_blog_action_back('blog.php?manage=settings', '設定已儲存。', '');
    }
    fate_blog_action_back('blog.php?manage=settings', '', '無法寫入設定檔（請確認 data/ 可寫）。');
}

fate_blog_action_back($returnTo, '', '未知的操作。');
