<?php

declare(strict_types=1);

require_once __DIR__ . DIRECTORY_SEPARATOR . 'auth.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'layout.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'dashboard_icons.php';
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_template.php';
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_ui_settings.php';
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_api_keys.php';

fate_admin_require_login();

$installed = fate_installed_template_ids();
$templateInspects = [];
foreach ($installed as $tid) {
    $templateInspects[$tid] = fate_template_inspect($tid);
}
$lockedByEnv = defined('FATE_TEMPLATE_SOURCE') && FATE_TEMPLATE_SOURCE === 'env';

$error = null;
$saved = isset($_GET['saved']) && $_GET['saved'] === '1';

$stored = fate_ui_settings_normalize(fate_ui_settings_read());

$tabRaw = isset($_GET['tab']) && is_string($_GET['tab']) ? strtolower(trim($_GET['tab'])) : 'site';
$activeTab = in_array($tabRaw, ['site', 'keys', 'links', 'template'], true) ? $tabRaw : 'site';

$buildUrl = static function (?string $tab = null) use ($activeTab): string {
    return 'template.php?tab=' . rawurlencode($tab ?? $activeTab);
};

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $sitePatch = [];
    $csrf = isset($_POST['csrf']) && is_string($_POST['csrf']) ? $_POST['csrf'] : '';
    if (!fate_admin_csrf_check($csrf)) {
        $error = '工作階段逾期或驗證失敗，請重新整理後再試。';
    } else {
        $sitePatch = [
            'site_display_name' => $_POST['site_display_name'] ?? '',
            'site_display_tagline' => $_POST['site_display_tagline'] ?? '',
            'url_line' => $_POST['url_line'] ?? '',
            'url_line_community' => $_POST['url_line_community'] ?? '',
            'url_x' => $_POST['url_x'] ?? '',
            'url_telegram' => $_POST['url_telegram'] ?? '',
            'label_other' => $_POST['label_other'] ?? '',
            'url_other' => $_POST['url_other'] ?? '',
        ];
        $tplPick = isset($_POST['template']) && is_string($_POST['template']) ? $_POST['template'] : null;
        $result = fate_ui_settings_save_admin_post($sitePatch, $tplPick, $lockedByEnv, $installed);
        if (!$result['ok']) {
            $error = $result['error'] ?? '儲存失敗。';
        } else {
            $keyValues = isset($_POST['api_key_value']) && is_array($_POST['api_key_value']) ? $_POST['api_key_value'] : [];
            $keyClear = isset($_POST['api_key_clear']) && is_array($_POST['api_key_clear']) ? $_POST['api_key_clear'] : [];
            $keyResult = fate_api_keys_save_admin_post($keyValues, $keyClear);
            if (!$keyResult['ok']) {
                $error = $keyResult['error'] ?? 'API 金鑰儲存失敗。';
            } else {
                $returnTab = isset($_POST['return_tab']) && is_string($_POST['return_tab']) ? $_POST['return_tab'] : 'site';
                if (!in_array($returnTab, ['site', 'keys', 'links', 'template'], true)) {
                    $returnTab = 'site';
                }
                header('Location: template.php?tab=' . rawurlencode($returnTab) . '&saved=1', true, 302);
                exit;
            }
        }
    }
    if ($error !== null && $sitePatch !== []) {
        $merge = array_merge(fate_ui_settings_read(), $sitePatch);
        if (!$lockedByEnv && isset($_POST['template']) && is_string($_POST['template'])) {
            $merge['template'] = $_POST['template'];
        }
        $stored = fate_ui_settings_normalize($merge);
        $postTab = isset($_POST['return_tab']) && is_string($_POST['return_tab']) ? $_POST['return_tab'] : '';
        if (in_array($postTab, ['site', 'keys', 'links', 'template'], true)) {
            $activeTab = $postTab;
        }
    }
}

$csrf = fate_admin_csrf_token();

$srcKey = defined('FATE_TEMPLATE_SOURCE') ? (string) FATE_TEMPLATE_SOURCE : 'default';
$sourceLabel = [
    'env' => '環境變數 FATE_TEMPLATE',
    'file' => '設定檔 fate_ui_settings.json',
    'default' => '預設 default',
    'custom' => '載入前已定義 FATE_TEMPLATE',
][$srcKey] ?? $srcKey;

$keyGroups = fate_api_keys_grouped_registry();
$keyUnsetCount = 0;
foreach ($keyGroups as $keys) {
    foreach ($keys as $keyId => $_meta) {
        if (fate_api_key_admin_status($keyId)['state'] === 'unset') {
            $keyUnsetCount++;
        }
    }
}

fate_admin_layout_start(['page' => '網站與模版', 'active' => 'template', 'body_class' => 'admin-body--template']);
?>
        <div class="template-admin">
            <header class="template-hero" aria-label="網站與模版">
                <div class="template-hero__glow" aria-hidden="true"></div>
                <div class="template-hero__inner">
                    <div class="template-hero__lead">
                        <span class="template-hero__icon" aria-hidden="true"><?= fate_admin_dashboard_icon('template') ?></span>
                        <div class="template-hero__copy">
                            <h1 class="template-hero__title">網站與模版</h1>
                            <p class="template-hero__sub">前台名稱、社群連結、API 金鑰與模版；設定存於 <code>fate_ui_settings.json</code>，金鑰存於 <code>fate_secrets.json</code>。</p>
                        </div>
                    </div>
                    <span class="sync-pill sync-pill--ok">
                        <code><?= htmlspecialchars(FATE_TEMPLATE, ENT_QUOTES, 'UTF-8') ?></code>
                    </span>
                </div>
            </header>

            <?php if ($saved): ?>
                <div class="sync-banner sync-banner--ok" role="status">
                    <span class="sync-banner__icon"><?= fate_admin_dashboard_icon('check') ?></span>
                    <p class="sync-banner__text">已儲存。重新整理前台即可看到更新。</p>
                </div>
            <?php endif; ?>

            <?php if ($error !== null): ?>
                <div class="sync-banner sync-banner--bad" role="alert">
                    <span class="sync-banner__icon"><?= fate_admin_dashboard_icon('alert-bad') ?></span>
                    <p class="sync-banner__text"><?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></p>
                </div>
            <?php endif; ?>

            <?php foreach (fate_api_keys_misplacement_warnings() as $warn): ?>
                <div class="sync-banner sync-banner--bad" role="alert">
                    <span class="sync-banner__icon"><?= fate_admin_dashboard_icon('alert-bad') ?></span>
                    <p class="sync-banner__text"><?= htmlspecialchars($warn['message'], ENT_QUOTES, 'UTF-8') ?></p>
                </div>
            <?php endforeach; ?>

            <div class="template-meta">
                <span class="template-meta__item">
                    <span class="template-meta__label">模版來源</span>
                    <span class="template-meta__value"><?= htmlspecialchars($sourceLabel, ENT_QUOTES, 'UTF-8') ?></span>
                </span>
                <span class="template-meta__item">
                    <span class="template-meta__label">已安裝</span>
                    <span class="template-meta__value"><code><?= htmlspecialchars(implode(', ', $installed), ENT_QUOTES, 'UTF-8') ?></code></span>
                </span>
            </div>

            <div class="template-tabs-col sync-panel" id="template-tabs">
                <nav class="masseur-tabs masseur-tabs--main template-tabs" role="tablist" aria-label="設定主題">
                    <a class="masseur-tabs__btn<?= $activeTab === 'site' ? ' is-active' : '' ?>"
                       href="<?= htmlspecialchars($buildUrl('site'), ENT_QUOTES, 'UTF-8') ?>"
                       role="tab"
                       aria-selected="<?= $activeTab === 'site' ? 'true' : 'false' ?>"
                       id="tab-btn-site">網站設定</a>
                    <a class="masseur-tabs__btn<?= $activeTab === 'keys' ? ' is-active' : '' ?>"
                       href="<?= htmlspecialchars($buildUrl('keys'), ENT_QUOTES, 'UTF-8') ?>"
                       role="tab"
                       aria-selected="<?= $activeTab === 'keys' ? 'true' : 'false' ?>"
                       id="tab-btn-keys">
                        API 金鑰
                        <?php if ($keyUnsetCount > 0): ?>
                            <span class="masseur-tabs__count"><?= (int) $keyUnsetCount ?></span>
                        <?php endif; ?>
                    </a>
                    <a class="masseur-tabs__btn<?= $activeTab === 'links' ? ' is-active' : '' ?>"
                       href="<?= htmlspecialchars($buildUrl('links'), ENT_QUOTES, 'UTF-8') ?>"
                       role="tab"
                       aria-selected="<?= $activeTab === 'links' ? 'true' : 'false' ?>"
                       id="tab-btn-links">社群連結</a>
                    <a class="masseur-tabs__btn<?= $activeTab === 'template' ? ' is-active' : '' ?>"
                       href="<?= htmlspecialchars($buildUrl('template'), ENT_QUOTES, 'UTF-8') ?>"
                       role="tab"
                       aria-selected="<?= $activeTab === 'template' ? 'true' : 'false' ?>"
                       id="tab-btn-template">前台模版</a>
                </nav>

                <form method="post" action="<?= htmlspecialchars($buildUrl(), ENT_QUOTES, 'UTF-8') ?>" class="template-form stack-form">
                    <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8') ?>">
                    <input type="hidden" name="return_tab" value="<?= htmlspecialchars($activeTab, ENT_QUOTES, 'UTF-8') ?>">

                    <div class="template-tab-panel<?= $activeTab === 'site' ? ' is-active' : '' ?>" id="tab-panel-site" role="tabpanel" aria-labelledby="tab-btn-site">
                        <p class="template-section-hint">空白欄位時，前台抬頭沿用預設「FATE」「店家探索」。環境變數優先於設定檔。</p>
                        <div class="field-grid">
                            <div class="field">
                                <label for="site_display_name">網站名稱（主標）</label>
                                <input type="text" name="site_display_name" id="site_display_name" maxlength="80"
                                       value="<?= htmlspecialchars($stored['site_display_name'], ENT_QUOTES, 'UTF-8') ?>"
                                       placeholder="例如：FATE">
                            </div>
                            <div class="field">
                                <label for="site_display_tagline">副標／說明一行</label>
                                <input type="text" name="site_display_tagline" id="site_display_tagline" maxlength="80"
                                       value="<?= htmlspecialchars($stored['site_display_tagline'], ENT_QUOTES, 'UTF-8') ?>"
                                       placeholder="例如：店家探索">
                            </div>
                        </div>
                    </div>

                    <div class="template-tab-panel<?= $activeTab === 'keys' ? ' is-active' : '' ?>" id="tab-panel-keys" role="tabpanel" aria-labelledby="tab-btn-keys">
                        <p class="template-section-hint">留空表示不變更已儲存的金鑰；勾選「清除」可刪除檔案中的該項（環境變數不受影響）。</p>
                        <?php foreach ($keyGroups as $groupName => $keys): ?>
                            <section class="template-key-group">
                                <h3 class="template-key-group__title"><?= htmlspecialchars($groupName, ENT_QUOTES, 'UTF-8') ?></h3>
                                <?php foreach ($keys as $keyId => $meta): ?>
                                    <?php $st = fate_api_key_admin_status($keyId); ?>
                                    <div class="api-key-block">
                                        <div class="field field--full">
                                            <label for="api_key_<?= htmlspecialchars($keyId, ENT_QUOTES, 'UTF-8') ?>">
                                                <?= htmlspecialchars($meta['label'], ENT_QUOTES, 'UTF-8') ?>
                                                <span class="api-key-id"><code><?= htmlspecialchars($keyId, ENT_QUOTES, 'UTF-8') ?></code></span>
                                            </label>
                                            <p class="sub api-key-hint"><?= htmlspecialchars($meta['hint'], ENT_QUOTES, 'UTF-8') ?></p>
                                            <?php if (!empty($meta['apply_urls']) && is_array($meta['apply_urls'])): ?>
                                                <ul class="api-key-links">
                                                    <?php foreach ($meta['apply_urls'] as $link): ?>
                                                        <?php
                                                        if (!is_array($link)) {
                                                            continue;
                                                        }
                                                        $linkLabel = isset($link['label']) && is_string($link['label']) ? trim($link['label']) : '';
                                                        $linkUrl = isset($link['url']) && is_string($link['url']) ? trim($link['url']) : '';
                                                        if ($linkLabel === '' || $linkUrl === '' || !preg_match('#^https://#i', $linkUrl)) {
                                                            continue;
                                                        }
                                                        ?>
                                                        <li><a href="<?= htmlspecialchars($linkUrl, ENT_QUOTES, 'UTF-8') ?>" target="_blank" rel="noopener noreferrer"><?= htmlspecialchars($linkLabel, ENT_QUOTES, 'UTF-8') ?></a></li>
                                                    <?php endforeach; ?>
                                                </ul>
                                            <?php endif; ?>
                                            <p class="api-key-status api-key-status--<?= htmlspecialchars($st['state'], ENT_QUOTES, 'UTF-8') ?>">
                                                <?= htmlspecialchars($st['label'], ENT_QUOTES, 'UTF-8') ?>
                                                <?php if ($st['masked'] !== ''): ?>
                                                    <span class="api-key-mask"><?= htmlspecialchars($st['masked'], ENT_QUOTES, 'UTF-8') ?></span>
                                                <?php endif; ?>
                                            </p>
                                            <?php if ($st['state'] === 'env'): ?>
                                                <p class="sub">環境變數：<code><?= htmlspecialchars($meta['env'], ENT_QUOTES, 'UTF-8') ?></code>
                                                    <?php if (!empty($meta['env_legacy'])): ?>
                                                        或 <code><?= htmlspecialchars((string) $meta['env_legacy'], ENT_QUOTES, 'UTF-8') ?></code>
                                                    <?php endif; ?>
                                                </p>
                                            <?php else: ?>
                                                <input type="password"
                                                       name="api_key_value[<?= htmlspecialchars($keyId, ENT_QUOTES, 'UTF-8') ?>]"
                                                       id="api_key_<?= htmlspecialchars($keyId, ENT_QUOTES, 'UTF-8') ?>"
                                                       class="api-key-input"
                                                       maxlength="512"
                                                       autocomplete="new-password"
                                                       placeholder="輸入新金鑰（留空不變更）">
                                                <label class="field field--check api-key-clear">
                                                    <input type="checkbox" name="api_key_clear[<?= htmlspecialchars($keyId, ENT_QUOTES, 'UTF-8') ?>]" value="1">
                                                    <span>清除已儲存的金鑰</span>
                                                </label>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </section>
                        <?php endforeach; ?>
                    </div>

                    <div class="template-tab-panel<?= $activeTab === 'links' ? ' is-active' : '' ?>" id="tab-panel-links" role="tabpanel" aria-labelledby="tab-btn-links">
                        <p class="template-section-hint">請填完整 <code>https://</code> 網址；未填則前台不顯示該項目。</p>
                        <div class="field-grid">
                            <div class="field">
                                <label for="url_line">LINE（官方帳號／加好友連結）</label>
                                <input type="url" name="url_line" id="url_line" maxlength="2048" inputmode="url"
                                       value="<?= htmlspecialchars($stored['url_line'], ENT_QUOTES, 'UTF-8') ?>"
                                       placeholder="https://line.me/…">
                            </div>
                            <div class="field">
                                <label for="url_line_community">LINE 社群（OpenChat／社群連結）</label>
                                <input type="url" name="url_line_community" id="url_line_community" maxlength="2048" inputmode="url"
                                       value="<?= htmlspecialchars($stored['url_line_community'], ENT_QUOTES, 'UTF-8') ?>"
                                       placeholder="https://line.me/ti/g2/…">
                            </div>
                            <div class="field">
                                <label for="url_x">X（Twitter）</label>
                                <input type="url" name="url_x" id="url_x" maxlength="2048" inputmode="url"
                                       value="<?= htmlspecialchars($stored['url_x'], ENT_QUOTES, 'UTF-8') ?>"
                                       placeholder="https://x.com/…">
                            </div>
                            <div class="field">
                                <label for="url_telegram">Telegram（頻道或群組連結）</label>
                                <input type="url" name="url_telegram" id="url_telegram" maxlength="2048" inputmode="url"
                                       value="<?= htmlspecialchars($stored['url_telegram'], ENT_QUOTES, 'UTF-8') ?>"
                                       placeholder="https://t.me/…">
                            </div>
                            <div class="field">
                                <label for="label_other">其它連結名稱</label>
                                <input type="text" name="label_other" id="label_other" maxlength="64"
                                       value="<?= htmlspecialchars($stored['label_other'], ENT_QUOTES, 'UTF-8') ?>"
                                       placeholder="例如：Discord、官網…">
                            </div>
                            <div class="field">
                                <label for="url_other">其它連結網址</label>
                                <input type="url" name="url_other" id="url_other" maxlength="2048" inputmode="url"
                                       value="<?= htmlspecialchars($stored['url_other'], ENT_QUOTES, 'UTF-8') ?>"
                                       placeholder="https://…">
                            </div>
                        </div>
                    </div>

                    <div class="template-tab-panel<?= $activeTab === 'template' ? ' is-active' : '' ?>" id="tab-panel-template" role="tabpanel" aria-labelledby="tab-btn-template">
                        <?php if ($lockedByEnv): ?>
                            <div class="sync-banner sync-banner--bad" role="alert">
                                <span class="sync-banner__icon"><?= fate_admin_dashboard_icon('alert-warn') ?></span>
                                <p class="sync-banner__text">伺服器已設定非空的 <code>FATE_TEMPLATE</code>，無法由此頁切換模版；仍可儲存其他 TAB 的設定。</p>
                            </div>
                        <?php else: ?>
                            <div class="template-install-guide sync-panel sync-panel--nested">
                                <h3 class="template-install-guide__title">安裝新模版</h3>
                                <ol class="template-install-guide__steps">
                                    <li>上傳資料夾至 <code>templates/&lt;識別名&gt;/</code>（識別名：小寫英數、底線、連字號）</li>
                                    <li>至少包含 <code>home.php</code>；選用 <code>store.php</code>、<code>member_profile.php</code>、<code>login.php</code>、<code>register.php</code>（缺檔自動用 default）</li>
                                    <li>（建議）新增 <code>theme.json</code> 設定名稱、說明、CSS；或只放 <code>theme.css</code> 也會自動載入</li>
                                    <li>重新整理此頁 → 下方列表會出現新模版 → 選取後儲存</li>
                                </ol>
                                <p class="template-section-hint mb-0">範例 manifest：<code>data/template-theme.json.example</code></p>
                            </div>
                            <div class="template-tpl-list">
                                <?php foreach ($installed as $tid):
                                    $inspect = $templateInspects[$tid] ?? fate_template_inspect($tid);
                                    $desc = trim((string) ($inspect['description'] ?? ''));
                                ?>
                                    <label class="template-tpl-option">
                                        <input type="radio" name="template" value="<?= htmlspecialchars($tid, ENT_QUOTES, 'UTF-8') ?>" <?= ($stored['template'] ?? 'default') === $tid ? 'checked' : '' ?> required>
                                        <span class="template-tpl-option__box" aria-hidden="true"></span>
                                        <span class="template-tpl-option__text">
                                            <strong><?= htmlspecialchars((string) ($inspect['title'] ?? $tid), ENT_QUOTES, 'UTF-8') ?>
                                                <code class="template-tpl-option__id"><?= htmlspecialchars($tid, ENT_QUOTES, 'UTF-8') ?></code></strong>
                                            <?php if ($desc !== ''): ?>
                                                <span><?= htmlspecialchars($desc, ENT_QUOTES, 'UTF-8') ?></span>
                                            <?php endif; ?>
                                            <span class="template-tpl-pages">
                                                <?php foreach ($inspect['pages'] as $page): ?>
                                                    <span class="template-tpl-page template-tpl-page--<?= $page['present'] ? 'ok' : ($page['fallback'] ? 'fallback' : 'miss') ?>">
                                                        <?= htmlspecialchars($page['label'], ENT_QUOTES, 'UTF-8') ?>
                                                        <?php if ($page['present']): ?>✓<?php elseif ($page['fallback']): ?>→ default<?php else: ?>✗<?php endif; ?>
                                                    </span>
                                                <?php endforeach; ?>
                                            </span>
                                            <?php if (!empty($inspect['stylesheets'])): ?>
                                                <span class="template-tpl-meta">CSS：<?= htmlspecialchars(implode(', ', $inspect['stylesheets']), ENT_QUOTES, 'UTF-8') ?></span>
                                            <?php endif; ?>
                                            <?php if (!empty($inspect['has_manifest'])): ?>
                                                <span class="template-tpl-meta">已讀取 theme.json</span>
                                            <?php elseif ($tid !== 'default'): ?>
                                                <span class="template-tpl-meta">未提供 theme.json（可選）</span>
                                            <?php endif; ?>
                                        </span>
                                    </label>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>

                    <div class="template-form-foot">
                        <button type="submit" class="sync-btn sync-btn--primary">儲存設定</button>
                        <a href="index.php" class="sync-btn">返回概覽</a>
                    </div>
                </form>
            </div>
        </div>
<?php
fate_admin_layout_end();
