<?php

declare(strict_types=1);

/**
 * 站台功能快速模式（一鍵套用店家評論、推薦技師、討論區外掛）。
 *
 * 模式對照：
 *  1 基本店家 — 僅店家資訊
 *  2 店家評論 — 店家文字評論
 *  3 店家＋技師 — 店家評論、推薦技師、技師文字評論
 *  4 完整功能 — 含討論區外掛
 */

require_once __DIR__ . DIRECTORY_SEPARATOR . 'fate_plugins.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'fate_masseur_rewards.php';

/** @return list<array{id:int,title:string,summary:string,features:list<string>}>} */
function fate_site_preset_definitions(): array
{
    return [
        [
            'id' => 1,
            'title' => '模式一：基本店家',
            'summary' => '只啟用最基本店家功能，僅店家資訊；不啟用評論、技師及外掛討論區。',
            'features' => [
                '店家列表與店家頁',
                '關閉店家評論、推薦技師、討論區外掛',
            ],
        ],
        [
            'id' => 2,
            'title' => '模式二：店家評論',
            'summary' => '除店家功能外，啟用店家文字評論。',
            'features' => [
                '店家頁可發表與瀏覽店家評論',
                '不含推薦技師、技師評論',
                '不含討論區外掛',
            ],
        ],
        [
            'id' => 3,
            'title' => '模式三：店家＋技師評論',
            'summary' => '除店家功能外，啟用店家評論、推薦技師與技師文字評論。',
            'features' => [
                '含模式二店家文字評論',
                '開放推薦技師（建檔、讚踩、標籤）',
                '開放技師文字評論',
                '不含討論區外掛',
            ],
        ],
        [
            'id' => 4,
            'title' => '模式四：完整功能',
            'summary' => '啟用所有功能，包含討論區外掛（店家／技師討論串）。',
            'features' => [
                '含模式三全部功能',
                '啟用討論區外掛與導覽連結',
                '討論區啟用時，店家頁改以討論串取代內嵌文字評論',
            ],
        ],
    ];
}

/** 功能快速設定可選的最高模式（無論壇模組時為 3）。 */
function fate_site_preset_max_mode(): int
{
    return fate_forum_module_installed() ? 4 : 3;
}

/**
 * 後台「功能快速設定」用：精簡版不含模式四。
 *
 * @return list<array{id:int,title:string,summary:string,features:list<string>}>
 */
function fate_site_preset_definitions_for_admin(): array
{
    $max = fate_site_preset_max_mode();

    return array_values(array_filter(
        fate_site_preset_definitions(),
        static fn (array $p): bool => (int) ($p['id'] ?? 0) <= $max
    ));
}

/** @return array{forum:bool,feature_enabled:bool,reviews_enabled:bool,store_reviews_enabled:bool} */
function fate_site_preset_target(int $mode): array
{
    return match (max(1, min(4, $mode))) {
        1 => ['forum' => false, 'feature_enabled' => false, 'reviews_enabled' => false, 'store_reviews_enabled' => false],
        2 => ['forum' => false, 'feature_enabled' => false, 'reviews_enabled' => false, 'store_reviews_enabled' => true],
        3 => ['forum' => false, 'feature_enabled' => true, 'reviews_enabled' => true, 'store_reviews_enabled' => true],
        4 => ['forum' => true, 'feature_enabled' => true, 'reviews_enabled' => true, 'store_reviews_enabled' => true],
        default => ['forum' => false, 'feature_enabled' => false, 'reviews_enabled' => false, 'store_reviews_enabled' => false],
    };
}

/** 依目前設定推測最接近的模式（0 = 自訂／混合）。 */
function fate_site_preset_detect(): int
{
    $forum = fate_plugin_is_enabled('forum');
    $masseur = fate_masseur_rewards_settings();
    $feature = !empty($masseur['feature_enabled']);
    $reviews = !empty($masseur['reviews_enabled']);
    $storeReviews = !empty($masseur['store_reviews_enabled']);

    if ($forum && $feature && $storeReviews) {
        return 4;
    }
    if (!$forum && $feature && $reviews && $storeReviews) {
        return 3;
    }
    if (!$forum && !$feature && !$reviews && $storeReviews) {
        return 2;
    }
    if (!$forum && !$feature && !$reviews && !$storeReviews) {
        return 1;
    }

    return 0;
}

/** @return array{forum:bool,feature_enabled:bool,reviews_enabled:bool,store_reviews_enabled:bool,mode:int,detected:int,is_custom:bool} */
function fate_site_preset_status(): array
{
    $masseur = fate_masseur_rewards_settings();
    $detected = fate_site_preset_detect();

    return [
        'forum' => fate_plugin_is_enabled('forum'),
        'feature_enabled' => !empty($masseur['feature_enabled']),
        'reviews_enabled' => !empty($masseur['reviews_enabled']),
        'store_reviews_enabled' => !empty($masseur['store_reviews_enabled']),
        'mode' => $detected,
        'detected' => $detected,
        'is_custom' => $detected === 0,
    ];
}

function fate_site_preset_forum_boards_unhide(PDO $pdo): void
{
    if (!fate_plugin_is_installed('forum')) {
        return;
    }
    $boot = fate_plugins_fate_root() . DIRECTORY_SEPARATOR . 'forum' . DIRECTORY_SEPARATOR . 'bootstrap.php';
    if (!is_file($boot)) {
        return;
    }
    require_once $boot;
    if (!function_exists('forum_ensure_tables') || !function_exists('forum_boards_all') || !function_exists('forum_board_save')) {
        return;
    }
    forum_ensure_tables($pdo);
    foreach (forum_boards_all($pdo, true) as $board) {
        $slug = (string) ($board['slug'] ?? '');
        if (!in_array($slug, ['store', 'general'], true)) {
            continue;
        }
        if ((int) ($board['is_hidden'] ?? 0) === 1) {
            forum_board_save(
                $pdo,
                (int) ($board['id'] ?? 0),
                $slug,
                (string) ($board['title'] ?? $slug),
                (string) ($board['description'] ?? ''),
                (int) ($board['sort'] ?? 0),
                false,
                (string) ($board['rules_html'] ?? ''),
                (string) ($board['announcement_html'] ?? ''),
                []
            );
        }
    }
}

/**
 * @return array{ok:bool, error?:string, mode?:int}
 */
function fate_site_preset_apply(int $mode, ?PDO $pdo = null): array
{
    $max = fate_site_preset_max_mode();
    $mode = max(1, min($max, $mode));
    $target = fate_site_preset_target($mode);

    $masseurSave = fate_masseur_rewards_save([
        'feature_enabled' => $target['feature_enabled'],
        'reviews_enabled' => $target['reviews_enabled'],
        'store_reviews_enabled' => $target['store_reviews_enabled'],
    ]);
    if (!$masseurSave['ok']) {
        return ['ok' => false, 'error' => $masseurSave['error'] ?? '無法寫入推薦技師設定。'];
    }

    if (fate_plugin_is_installed('forum')) {
        $plugins = fate_plugins_normalize(fate_plugins_read());
        $plugins['plugins']['forum'] = ['enabled' => $target['forum']];
        if (!fate_plugins_persist($plugins)) {
            return ['ok' => false, 'error' => '無法寫入外掛設定（請確認 data/ 目錄可寫）。'];
        }
        fate_plugins_sync_forum_config_enabled($target['forum']);

        if ($target['forum'] && $pdo instanceof PDO) {
            try {
                fate_site_preset_forum_boards_unhide($pdo);
            } catch (Throwable) {
                /* 版區顯示失敗不阻擋整體套用 */
            }
        }
    } elseif ($target['forum']) {
        return ['ok' => false, 'error' => '討論區外掛尚未安裝，無法套用模式四。'];
    }

    return ['ok' => true, 'mode' => $mode];
}
