<?php

declare(strict_types=1);

require_once __DIR__ . DIRECTORY_SEPARATOR . 'auth.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'layout.php';
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_site_presets.php';

fate_admin_require_login();

$pdo = null;
$dbErr = 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 $e) {
    $dbErr = $e->getMessage();
}

$error = null;
$saved = isset($_GET['saved']) && $_GET['saved'] === '1';
$appliedMode = isset($_GET['mode']) ? (int) $_GET['mode'] : 0;
$presets = fate_site_preset_definitions_for_admin();
$status = fate_site_preset_status();
$forumModuleInstalled = fate_forum_module_installed();
$maxSiteMode = fate_site_preset_max_mode();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $csrf = isset($_POST['csrf']) && is_string($_POST['csrf']) ? $_POST['csrf'] : '';
    if (!fate_admin_csrf_check($csrf)) {
        $error = '工作階段逾期或驗證失敗，請重新整理後再試。';
    } else {
        $mode = isset($_POST['site_mode']) ? (int) $_POST['site_mode'] : 0;
        if ($mode < 1 || $mode > $maxSiteMode) {
            $error = '請選擇有效的功能模式。';
        } else {
            $result = fate_site_preset_apply($mode, $pdo);
            if (!$result['ok']) {
                $error = $result['error'] ?? '套用失敗';
            } else {
                header('Location: site_modes.php?saved=1&mode=' . (int) $result['mode'], true, 302);
                exit;
            }
        }
    }
    $status = fate_site_preset_status();
}

$csrf = fate_admin_csrf_token();
$currentMode = (int) ($status['detected'] ?? 0);

fate_admin_layout_start(['page' => '功能快速設定', 'active' => 'site_modes', 'body_class' => 'admin-body--site-modes']);
?>
        <header class="page-header">
            <h1 class="page-title">功能快速設定</h1>
            <p class="sub">一鍵切換店家、推薦技師與文字評論的組合<?= $forumModuleInstalled ? '（含討論區外掛）' : '' ?>。套用後仍可至「推薦技師」<?= $forumModuleInstalled ? '、「外掛管理」' : '' ?>微調細部選項。</p>
        </header>

        <?php if ($saved): ?>
            <div class="msg ok">已套用<?= $appliedMode >= 1 && $appliedMode <= 4 ? '模式 ' . (int) $appliedMode : '功能模式' ?>。</div>
        <?php endif; ?>
        <?php if ($error !== null): ?>
            <div class="msg bad"><?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></div>
        <?php endif; ?>
        <?php if ($dbErr !== null): ?>
            <div class="msg bad">資料庫連線異常：<?= htmlspecialchars($dbErr, ENT_QUOTES, 'UTF-8') ?><?= $forumModuleInstalled ? '（模式四若需顯示隱藏版區可能無法自動還原）' : '' ?></div>
        <?php endif; ?>

        <div class="card site-mode-status">
            <h2 class="h2" style="margin-top:0;">目前狀態</h2>
            <?php if (!empty($status['is_custom'])): ?>
                <p class="sub site-mode-status__warn">目前為<strong>自訂組合</strong>（與下列<?= $maxSiteMode ?>種預設不完全相同）。選擇一個模式並套用可恢復標準設定。</p>
            <?php elseif ($currentMode >= 1): ?>
                <p class="sub">最接近 <strong>模式 <?= $currentMode ?></strong>。</p>
            <?php endif; ?>
            <ul class="site-mode-status__list">
                <li>店家文字評論：<?= !empty($status['store_reviews_enabled']) ? '啟用' : '關閉' ?></li>
                <li>推薦技師：<?= !empty($status['feature_enabled']) ? '啟用' : '關閉' ?></li>
                <li>技師文字評論：<?= !empty($status['reviews_enabled']) ? '啟用' : '關閉' ?></li>
                <?php if ($forumModuleInstalled): ?>
                <li>討論區外掛：<?= !empty($status['forum']) ? '啟用' : '關閉' ?></li>
                <?php endif; ?>
            </ul>
        </div>

        <form method="post" action="site_modes.php" class="site-mode-form">
            <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8') ?>">

            <ul class="site-mode-list">
                <?php foreach ($presets as $preset): ?>
                    <?php
                    $pid = (int) $preset['id'];
                    $isCurrent = !$status['is_custom'] && $currentMode === $pid;
                    ?>
                    <li class="site-mode-card card<?= $isCurrent ? ' site-mode-card--current' : '' ?>">
                        <label class="site-mode-card__label">
                            <input type="radio" name="site_mode" value="<?= $pid ?>"<?= $isCurrent ? ' checked' : '' ?>>
                            <span class="site-mode-card__body">
                                <span class="site-mode-card__title"><?= htmlspecialchars((string) $preset['title'], ENT_QUOTES, 'UTF-8') ?></span>
                                <span class="site-mode-card__summary"><?= htmlspecialchars((string) $preset['summary'], ENT_QUOTES, 'UTF-8') ?></span>
                                <ul class="site-mode-card__features">
                                    <?php foreach ($preset['features'] as $feat): ?>
                                        <li><?= htmlspecialchars((string) $feat, ENT_QUOTES, 'UTF-8') ?></li>
                                    <?php endforeach; ?>
                                </ul>
                            </span>
                            <?php if ($isCurrent): ?>
                                <span class="site-mode-card__badge">使用中</span>
                            <?php endif; ?>
                        </label>
                    </li>
                <?php endforeach; ?>
            </ul>

            <div class="site-mode-form__foot">
                <button type="submit" class="btn btn--primary">套用所選模式</button>
            </div>
        </form>

        <div class="card site-mode-help">
            <h2 class="h2" style="margin-top:0;">說明</h2>
            <ul class="site-mode-help__list">
                <li>模式一僅保留店家資訊；會員回報（歇業／更名等）仍可在店家頁使用。</li>
                <li>模式二在店家頁顯示「店家評論」區，可獨立於推薦技師。</li>
                <li>模式三在模式二基礎上，另開放推薦技師與技師文字評論。</li>
                <?php if ($forumModuleInstalled): ?>
                <li>模式四啟用討論區外掛後，導覽列會出現「討論區」，店家頁改以討論串取代內嵌文字評論。</li>
                <li>細部選項（評論僅正式會員、N 幣獎勵、版區隱藏等）請至 <a href="masseurs.php?tab=settings">推薦技師</a>、<a href="plugins.php">外掛管理</a>、<a href="../forum/admin/index.php">論壇管理</a> 調整。</li>
                <?php else: ?>
                <li>細部選項（評論僅正式會員、N 幣獎勵等）請至 <a href="masseurs.php?tab=settings">推薦技師</a> 調整。</li>
                <?php endif; ?>
            </ul>
        </div>
<?php
fate_admin_layout_end();
