<?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_api_keys.php';

require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'spa_store_public_client_key.php';



fate_admin_require_login();



$siteUrl = fate_spa_member_site_url();

$siteUrlBlockReason = fate_spa_member_site_url_block_reason($siteUrl);

$applyUrl = fate_spa_member_apply_url();

$partnersUrl = fate_spa_partners_list_url();

$storedKeySt = fate_api_key_admin_status('spa_store_public');

$syncKey = fate_api_key('spa_store_public');

$generatedKey = '';

$generateError = '';



/** @param array{ok:bool, error?:string, data?:array<string,mixed>} $fetch */

$formatSpaStatus = static function (array $fetch): array {

    if (!$fetch['ok']) {

        return [

            'label' => '查詢失敗',

            'class' => 'spa-status--unknown',

            'detail' => (string) ($fetch['error'] ?? '無法連線新手村'),

            'api_ok' => false,

        ];

    }

    $d = $fetch['data'] ?? [];

    $label = (string) ($d['status_label'] ?? '—');

    $status = (string) ($d['status'] ?? '');

    $class = fate_spa_status_badge_class($status);

    if (($d['auth_type'] ?? '') === 'site_master') {

        $class = 'spa-status--active';

    }

    $apiOk = !empty($d['verify_ok']) || (!empty($d['api_allowed']) && !isset($d['verify_ok']));

    if (isset($d['verify_ok']) && $d['verify_ok'] === false) {

        $apiOk = false;

    }

    if (isset($d['catalog_auth_ok']) && $d['catalog_auth_ok'] === false) {

        $apiOk = false;

    }



    if (!empty($d['registered']) || (($d['auth_type'] ?? '') === 'site_master')) {

        $detail = (string) ($d['description'] ?? '');

        if (!empty($d['key_hint'])) {

            $detail = ($detail !== '' ? $detail . ' ' : '') . '金鑰尾碼：' . $d['key_hint'];

        }

        if (!empty($d['verify_reason']) && empty($d['verify_ok'])) {

            $detail .= ($detail !== '' ? ' · ' : '') . (string) $d['verify_reason'];

        } elseif (isset($d['host_matches_key']) && $d['host_matches_key'] === false) {

            $detail .= ($detail !== '' ? ' · ' : '') . '網域與申請不符';

        }

        if (!empty($d['catalog_auth_mismatch'])) {

            $detail .= ($detail !== '' ? ' · ' : '') . '店家 API 閘道驗證未通過';

        }

        if (!empty($d['updated_at'])) {

            $detail .= ($detail !== '' ? ' · ' : '') . '更新：' . $d['updated_at'];

        }

    } else {

        $detail = (string) ($d['description'] ?? '尚無申請紀錄');

    }



    return [

        'label' => $label,

        'class' => $class,

        'detail' => $detail,

        'api_ok' => $apiOk,

        'raw' => $d,

    ];

};



$syncGate = null;

if ($syncKey !== '') {

    require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'spa_store_sync.php';

    $syncGate = fate_spa_sync_api_key_gate();

}



$syncStatusFetch = fate_spa_store_public_client_status_fetch(

    $syncKey !== '' ? $syncKey : null,

    $syncKey === '' ? $siteUrl : null

);

$syncStatusUi = $formatSpaStatus($syncStatusFetch);



$hostStatusUi = null;

$showHostStatus = false;

if ($siteUrl !== '') {

    $hostStatusUi = $formatSpaStatus(fate_spa_store_public_client_status_fetch(null, $siteUrl));

    $showHostStatus = $syncKey === ''

        || ($hostStatusUi['label'] !== $syncStatusUi['label'] && $hostStatusUi['label'] !== '查詢失敗');

}



$generatedStatusUi = null;



if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'generate') {

    $csrfPost = isset($_POST['csrf']) && is_string($_POST['csrf']) ? $_POST['csrf'] : '';

    if (!fate_admin_csrf_check($csrfPost)) {

        $generateError = '工作階段逾期，請重新整理後再試。';

    } elseif ($siteUrl === '') {

        $generateError = '無法取得站台對外網址，請設定 FATE_PUBLIC_SITE_ORIGIN。';

    } elseif ($siteUrlBlockReason !== null) {

        $generateError = $siteUrlBlockReason;

    } else {

        $built = fate_spa_store_public_client_key_build($siteUrl);

        if (empty($built['ok'])) {

            $generateError = $built['error'] ?? '無法產生金鑰';

        } else {

            $generatedKey = (string) ($built['key'] ?? '');

            $_SESSION['fate_spa_generated_key'] = $generatedKey;

            $_SESSION['fate_spa_generated_for'] = $siteUrl;

        }

    }

}



if ($generatedKey === '' && !empty($_SESSION['fate_spa_generated_key']) && is_string($_SESSION['fate_spa_generated_key'])) {

    $generatedKey = $_SESSION['fate_spa_generated_key'];

}



if ($generatedKey !== '') {

    $generatedStatusUi = $formatSpaStatus(

        fate_spa_store_public_client_status_fetch($generatedKey, null)

    );

}



$pillTone = 'bad';

$pillLabel = '尚無法同步';

if ($syncGate !== null && !empty($syncGate['ok'])) {

    $pillTone = 'ok';

    $pillLabel = '可同步';

} elseif ($syncKey === '') {

    $pillLabel = '未設定金鑰';

} elseif ($syncStatusUi['label'] === '申請中') {

    $pillTone = 'warn';

    $pillLabel = '申請中';

} elseif ($syncStatusUi['label'] === '啟用') {

    $pillTone = 'warn';

    $pillLabel = '待完成驗證';

}



$csrf = fate_admin_csrf_token();

fate_admin_layout_start(['page' => '新手村 API 金鑰', 'active' => 'spa_api', 'body_class' => 'admin-body--spa-api']);

?>

        <div class="spa-api">

            <header class="spa-api-hero" aria-label="新手村 API">

                <div class="spa-api-hero__glow" aria-hidden="true"></div>

                <div class="spa-api-hero__inner">

                    <div class="spa-api-hero__lead">

                        <span class="spa-api-hero__icon" aria-hidden="true"><?= fate_admin_dashboard_icon('spa_api') ?></span>

                        <div class="spa-api-hero__copy">

                            <h1 class="spa-api-hero__title">新手村 API</h1>

                            <p class="spa-api-hero__sub">產生金鑰、向新手村申請啟用，供本站同步店家快照。</p>

                        </div>

                    </div>

                    <span class="sync-pill sync-pill--<?= htmlspecialchars($pillTone, ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars($pillLabel, ENT_QUOTES, 'UTF-8') ?></span>

                </div>

            </header>



            <?php if ($siteUrlBlockReason !== null && $generateError === ''): ?>

                <div class="sync-banner sync-banner--warn spa-api-local-notice" role="note">

                    <span class="sync-banner__icon"><?= fate_admin_dashboard_icon('alert-warn') ?></span>

                    <p class="sync-banner__text"><?= htmlspecialchars($siteUrlBlockReason, ENT_QUOTES, 'UTF-8') ?></p>

                </div>

            <?php endif; ?>



            <?php if ($generateError !== ''): ?>

                <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($generateError, ENT_QUOTES, 'UTF-8') ?></p>

                </div>

            <?php endif; ?>



            <div class="spa-api-layout">

                <div class="spa-api-main">

                    <section class="sync-panel spa-api-panel--status" aria-labelledby="spa-status-title">

                        <header class="sync-panel__head spa-api-panel__head">

                            <h2 id="spa-status-title" class="sync-panel__title">金鑰狀態</h2>

                            <a class="spa-api-refresh" href="spa_api_key.php">重新查詢</a>

                        </header>



                        <div class="spa-api-status">

                            <div class="spa-api-status__row">

                                <div class="spa-api-status__main">

                                    <span class="spa-api-status__label">同步用金鑰</span>

                                    <span class="spa-status-badge <?= htmlspecialchars($syncStatusUi['class'], ENT_QUOTES, 'UTF-8') ?>">

                                        <?= htmlspecialchars($syncStatusUi['label'], ENT_QUOTES, 'UTF-8') ?>

                                    </span>

                                </div>

                                <p class="spa-api-status__detail">

                                    <?php if ($syncKey === ''): ?>

                                        <span class="spa-api-status__warn">尚未於「網站與模版」設定金鑰。</span>

                                    <?php else: ?>

                                        <?= htmlspecialchars($syncStatusUi['detail'], ENT_QUOTES, 'UTF-8') ?>

                                        <?php if ($syncGate !== null && !empty($syncGate['ok'])): ?>

                                            <span class="spa-api-status__ok"> · 已通過連線測試</span>

                                        <?php elseif ($syncGate !== null && empty($syncGate['ok'])): ?>

                                            <span class="spa-api-status__warn"> · <?= htmlspecialchars((string) fate_spa_sync_gate_user_message($syncGate), ENT_QUOTES, 'UTF-8') ?></span>

                                        <?php elseif ($syncStatusUi['api_ok']): ?>

                                            <span class="spa-api-status__ok"> · 紀錄為啟用</span>

                                        <?php elseif ($syncStatusUi['label'] !== '查詢失敗'): ?>

                                            <span class="spa-api-status__warn"> · 尚不可同步</span>

                                        <?php endif; ?>

                                    <?php endif; ?>

                                </p>

                                <?php if ($storedKeySt['masked'] !== ''): ?>

                                    <p class="spa-api-status__mask">本站已存 <code class="api-key-mask"><?= htmlspecialchars($storedKeySt['masked'], ENT_QUOTES, 'UTF-8') ?></code></p>

                                <?php endif; ?>

                            </div>



                            <?php if ($generatedStatusUi !== null && $generatedKey !== '' && $generatedKey !== $syncKey): ?>

                            <div class="spa-api-status__row">

                                <div class="spa-api-status__main">

                                    <span class="spa-api-status__label">剛產生的金鑰</span>

                                    <span class="spa-status-badge <?= htmlspecialchars($generatedStatusUi['class'], ENT_QUOTES, 'UTF-8') ?>">

                                        <?= htmlspecialchars($generatedStatusUi['label'], ENT_QUOTES, 'UTF-8') ?>

                                    </span>

                                </div>

                                <p class="spa-api-status__detail"><?= htmlspecialchars($generatedStatusUi['detail'], ENT_QUOTES, 'UTF-8') ?></p>

                            </div>

                            <?php endif; ?>



                            <?php if ($hostStatusUi !== null && $showHostStatus): ?>

                            <div class="spa-api-status__row">

                                <div class="spa-api-status__main">

                                    <span class="spa-api-status__label">本站網域紀錄</span>

                                    <span class="spa-status-badge <?= htmlspecialchars($hostStatusUi['class'], ENT_QUOTES, 'UTF-8') ?>">

                                        <?= htmlspecialchars($hostStatusUi['label'], ENT_QUOTES, 'UTF-8') ?>

                                    </span>

                                </div>

                                <p class="spa-api-status__detail"><?= htmlspecialchars($hostStatusUi['detail'], ENT_QUOTES, 'UTF-8') ?></p>

                            </div>

                            <?php endif; ?>

                        </div>

                    </section>



                    <section class="sync-panel" aria-labelledby="spa-site-title">

                        <header class="sync-panel__head">

                            <h2 id="spa-site-title" class="sync-panel__title">本站資訊</h2>

                        </header>

                        <dl class="spa-api-info">

                            <div class="spa-api-info__row">

                                <dt>申請網址</dt>

                                <dd><code><?= $siteUrl !== '' ? htmlspecialchars($siteUrl, ENT_QUOTES, 'UTF-8') : '（未設定）' ?></code></dd>

                            </div>

                            <div class="spa-api-info__row">

                                <dt>金鑰儲存</dt>

                                <dd><?= htmlspecialchars($storedKeySt['label'], ENT_QUOTES, 'UTF-8') ?></dd>

                            </div>

                        </dl>

                    </section>



                    <section class="sync-panel" aria-labelledby="spa-gen-title">

                        <header class="sync-panel__head">

                            <h2 id="spa-gen-title" class="sync-panel__title">產生金鑰</h2>

                        </header>

                        <p class="spa-api-lead">金鑰須綁定本站<strong>對外正式網域</strong>（於「網站與模版」或 <code>FATE_PUBLIC_SITE_ORIGIN</code> 設定）。產生後請至新手村申請啟用。<strong>金鑰僅限本站使用</strong>：貼到其他分站設定後，新手村會因 <code>X-Store-Site-Origin</code> 不符而拒絕。</p>

                        <form method="post" class="spa-api-form">

                            <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8') ?>">

                            <input type="hidden" name="action" value="generate">

                            <button type="submit" class="sync-btn sync-btn--primary" <?= ($siteUrl === '' || $siteUrlBlockReason !== null) ? 'disabled title="' . htmlspecialchars($siteUrlBlockReason !== null ? $siteUrlBlockReason : '尚未設定對外網址', ENT_QUOTES, 'UTF-8') . '"' : '' ?>>

                                <?= fate_admin_dashboard_icon('api') ?>

                                <span>產生 API 金鑰</span>

                            </button>

                        </form>

                        <?php if ($generatedKey !== ''): ?>

                            <div class="spa-api-key-block">

                                <p class="spa-api-key-block__label">金鑰（請複製）</p>

                                <pre class="spa-api-key-box" id="generated-key"><?= htmlspecialchars($generatedKey, ENT_QUOTES, 'UTF-8') ?></pre>

                                <button type="button" class="sync-btn" id="copy-key-btn">複製金鑰</button>

                            </div>

                        <?php endif; ?>

                    </section>



                    <section class="sync-panel spa-api-panel--actions" aria-label="相關操作">

                        <div class="spa-api-actions">

                            <a class="spa-api-action" href="<?= htmlspecialchars($applyUrl, ENT_QUOTES, 'UTF-8') ?>" target="_blank" rel="noopener noreferrer">

                                <span class="spa-api-action__icon"><?= fate_admin_dashboard_icon('external') ?></span>

                                <span class="spa-api-action__text">

                                    <strong>新手村申請</strong>

                                    <span>提交金鑰並等待啟用</span>

                                </span>

                            </a>

                            <a class="spa-api-action" href="template.php">

                                <span class="spa-api-action__icon"><?= fate_admin_dashboard_icon('template') ?></span>

                                <span class="spa-api-action__text">

                                    <strong>網站與模版</strong>

                                    <span>貼上金鑰供同步使用</span>

                                </span>

                            </a>

                            <a class="spa-api-action" href="sync.php">

                                <span class="spa-api-action__icon"><?= fate_admin_dashboard_icon('sync') ?></span>

                                <span class="spa-api-action__text">

                                    <strong>同步店家</strong>

                                    <span>啟用後執行同步</span>

                                </span>

                            </a>

                        </div>

                    </section>

                </div>



                <aside class="sync-panel spa-api-guide" aria-labelledby="spa-guide-title">

                    <header class="sync-panel__head">

                        <h2 id="spa-guide-title" class="sync-panel__title">使用說明</h2>

                    </header>



                    <ol class="sync-steps">

                        <li class="sync-steps__item">

                            <span class="sync-steps__num" aria-hidden="true">1</span>

                            <div>

                                <strong>產生金鑰</strong>

                                <p>按「產生 API 金鑰」取得本站專用金鑰，請勿手動修改內容。</p>

                            </div>

                        </li>

                        <li class="sync-steps__item">

                            <span class="sync-steps__num" aria-hidden="true">2</span>

                            <div>

                                <strong>新手村申請</strong>

                                <p>以會員帳號登入新手村，申請網址填 <code><?= $siteUrl !== '' ? htmlspecialchars($siteUrl, ENT_QUOTES, 'UTF-8') : '本站對外網址' ?></code>，並貼上金鑰。可選是否公開於<a href="<?= htmlspecialchars($partnersUrl, ENT_QUOTES, 'UTF-8') ?>" target="_blank" rel="noopener noreferrer">合作網站列表</a>。</p>

                            </div>

                        </li>

                        <li class="sync-steps__item">

                            <span class="sync-steps__num" aria-hidden="true">3</span>

                            <div>

                                <strong>等待啟用</strong>

                                <p>送出後為「申請中」，須待新手村站方審核為「啟用」後 API 才會通行。</p>

                            </div>

                        </li>

                        <li class="sync-steps__item">

                            <span class="sync-steps__num" aria-hidden="true">4</span>

                            <div>

                                <strong>寫入並同步</strong>

                                <p>將<strong>同一把金鑰</strong>貼至 <a href="template.php">網站與模版</a>，再至 <a href="sync.php">同步店家</a> 更新快照。</p>

                            </div>

                        </li>

                    </ol>



                    <div class="sync-notes">

                        <h3 class="sync-notes__title">注意</h3>

                        <ul class="sync-notes__list">

                            <li>申請網址須為可對外連線的正式網域（新手村白名單規則）。</li>

                            <li>申請網址須與實際使用金鑰的網站一致。</li>

                            <li>僅「啟用」狀態且已寫入本站設定的金鑰可同步。</li>

                            <li>上方狀態區可隨時「重新查詢」確認進度。</li>

                        </ul>

                    </div>

                </aside>

            </div>

        </div>



        <script>

        (function () {

            var btn = document.getElementById('copy-key-btn');

            var pre = document.getElementById('generated-key');

            if (!btn || !pre) return;

            btn.addEventListener('click', function () {

                var t = pre.textContent || '';

                var done = function () {

                    btn.textContent = '已複製';

                    setTimeout(function () { btn.textContent = '複製金鑰'; }, 2000);

                };

                if (navigator.clipboard && navigator.clipboard.writeText) {

                    navigator.clipboard.writeText(t).then(done);

                } else {

                    var ta = document.createElement('textarea');

                    ta.value = t;

                    document.body.appendChild(ta);

                    ta.select();

                    try { document.execCommand('copy'); done(); } catch (e) {}

                    document.body.removeChild(ta);

                }

            });

        })();

        </script>

<?php

fate_admin_layout_end();


