<?php

declare(strict_types=1);

$fateRoot = dirname(__DIR__);

require_once $fateRoot . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'app.php';
require_once $fateRoot . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_public_session.php';
require_once $fateRoot . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_install.php';

fate_public_session_start();

$connectError = '';
$probe = fate_install_probe($connectError);
fate_install_enforce_web_access_policy($probe);
$phase = (string) ($probe['phase'] ?? 'unknown');
$pdo = $probe['pdo'] instanceof PDO ? $probe['pdo'] : null;

$showWelcome = false;
if ($probe['complete'] && $phase === 'complete') {
    if (!empty($_SESSION['fate_install_welcome'])) {
        $showWelcome = true;
    } else {
        header('Location: ' . fate_install_admin_url(), true, 302);
        exit;
    }
}

$error = null;
$success = null;
$stickyUsername = '';
$stickyDisplay = '';
$dbForm = fate_install_db_form_defaults();
$installActionUrl = fate_install_url();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $csrf = isset($_POST['csrf']) && is_string($_POST['csrf']) ? $_POST['csrf'] : '';
    $action = isset($_POST['action']) && is_string($_POST['action']) ? $_POST['action'] : '';

    if (!fate_install_csrf_check($csrf)) {
        $error = '工作階段逾期或驗證失敗，請重新整理後再試。';
    } elseif ($action === 'save_db') {
        if (!fate_install_can_configure_db_via_wizard($pdo)) {
            $error = '目前無法由安裝精靈寫入資料庫設定（可能已安裝完成，或連線來自環境變數）。';
        } else {
            $parsed = fate_install_parse_db_input([
                'host' => $_POST['db_host'] ?? '',
                'name' => $_POST['db_name'] ?? '',
                'user' => $_POST['db_user'] ?? '',
                'pass' => $_POST['db_pass'] ?? '',
                'charset' => $_POST['db_charset'] ?? 'utf8mb4',
            ]);
            $dbForm = [
                'host' => trim((string) ($_POST['db_host'] ?? '')),
                'name' => trim((string) ($_POST['db_name'] ?? '')),
                'user' => (string) ($_POST['db_user'] ?? ''),
                'pass' => (string) ($_POST['db_pass'] ?? ''),
                'charset' => trim((string) ($_POST['db_charset'] ?? 'utf8mb4')),
            ];
            $_SESSION['fate_install_db_draft'] = $dbForm;

            if (!$parsed['ok']) {
                $error = $parsed['error'] ?? '資料庫設定格式不正確。';
            } else {
                $testErr = '';
                $test = fate_install_connect_with_config($parsed['cfg'], $testErr);
                if (!$test['ok']) {
                    $error = $testErr !== ''
                        ? ('無法連線資料庫：' . fate_install_user_facing_db_error($testErr))
                        : '無法連線資料庫，請檢查主機、帳號與密碼。';
                } else {
                    $saved = fate_install_save_db_config($parsed['cfg']);
                    if (!$saved['ok']) {
                        $error = (string) ($saved['message'] ?? '無法寫入 config/db.php。');
                    } else {
                        $success = '資料庫連線成功，已寫入 config/db.php。請繼續建立資料表。';
                        $pdo = $test['pdo'];
                        $GLOBALS['pdo'] = $pdo;
                        $GLOBALS['fate_app_pdo'] = $pdo;
                        $refreshed = fate_install_refresh_phase($pdo);
                        $phase = $refreshed['phase'];
                        $probe['complete'] = $refreshed['complete'];
                        $probe['pdo'] = $pdo;
                        $dbForm = fate_install_db_form_defaults();
                    }
                }
            }
        }
    } elseif ($action === 'run_schema') {
        if ($phase !== 'schema_missing' && !($phase === 'no_admin' && $pdo instanceof PDO && !fate_install_schema_ready($pdo))) {
            if ($phase === 'no_admin' || $phase === 'complete') {
                $error = '資料表已存在，無須重複建立。';
            } else {
                $error = '目前狀態無法建立資料表，請先完成資料庫連線設定。';
            }
        } else {
            $conn = fate_install_connect($connectError);
            if (!$conn['ok'] || !($conn['pdo'] ?? null) instanceof PDO) {
                $error = $connectError !== ''
                    ? fate_install_user_facing_db_error($connectError)
                    : '無法連線資料庫，請先完成步驟 1。';
            } else {
                $result = fate_install_run_schema($conn['pdo']);
                if ($result['ok']) {
                    $_SESSION['fate_install_flash'] = '資料表已建立（共執行 ' . (int) ($result['executed'] ?? 0) . ' 段 SQL）。請建立管理員帳號。';
                    header('Location: ' . fate_install_to_absolute(fate_install_web_path('install/') . '?step=admin'), true, 303);
                    exit;
                } else {
                    $error = (string) ($result['message'] ?? '建立資料表失敗。');
                }
            }
        }
    } elseif ($action === 'create_admin') {
        if ($phase !== 'no_admin') {
            $error = '目前無法建立管理員（可能已有帳號或資料表未就緒）。';
        } elseif (!$pdo instanceof PDO) {
            $error = '無法連線資料庫。';
        } else {
            $un = isset($_POST['username']) && is_string($_POST['username']) ? trim($_POST['username']) : '';
            $pw = isset($_POST['password']) && is_string($_POST['password']) ? $_POST['password'] : '';
            $pw2 = isset($_POST['password_confirm']) && is_string($_POST['password_confirm']) ? $_POST['password_confirm'] : '';
            $dn = isset($_POST['display_name']) && is_string($_POST['display_name']) ? trim($_POST['display_name']) : '';
            $email = isset($_POST['email']) && is_string($_POST['email']) ? trim($_POST['email']) : '';
            $stickyUsername = $un;
            $stickyDisplay = $dn;

            if ($pw !== $pw2) {
                $error = '兩次輸入的密碼不一致。';
            } else {
                $created = fate_install_create_first_admin($pdo, $un, $pw, $dn, $email);
                if ($created['ok']) {
                    require_once $fateRoot . DIRECTORY_SEPARATOR . 'admin' . DIRECTORY_SEPARATOR . 'auth.php';
                    fate_admin_complete_login($created['member'], true);
                    $_SESSION['fate_install_welcome'] = true;
                    unset($_SESSION['fate_install_db_draft']);
                    header('Location: ' . fate_install_to_absolute(fate_install_web_path('install/') . '?welcome=1'), true, 303);
                    exit;
                }
                $error = $created['error'] ?? '建立管理員失敗。';
            }
        }
    } elseif ($action === 'fix_permissions') {
        $fixResult = fate_install_fix_permissions();
        if ($fixResult['ok']) {
            $success = '目錄與權限已全部就緒。';
        } elseif ($fixResult['fixed'] !== []) {
            $success = '已修正 ' . count($fixResult['fixed']) . ' 項；仍有 '
                . count($fixResult['failed']) . ' 項需手動處理（見下方列表）。';
        } else {
            $error = '無法自動修正權限。若為 Windows／IIS 或共享主機，請依主機面板手動調整目錄擁有者與寫入權限。';
        }
    }
}

$csrf = fate_install_csrf_token();
$dbSummary = is_array($probe['db_summary'] ?? null) ? $probe['db_summary'] : fate_db_config_summary();
$dbWizard = fate_install_can_configure_db_via_wizard($pdo);
$installSteps = fate_install_step_states($phase, $pdo);
$cssPath = $fateRoot . DIRECTORY_SEPARATOR . 'admin' . DIRECTORY_SEPARATOR . 'static' . DIRECTORY_SEPARATOR . 'admin.css';
$installCssPath = __DIR__ . DIRECTORY_SEPARATOR . 'install.css';
$cssVer = is_file($cssPath) ? (string) filemtime($cssPath) : '1';
$installCssVer = is_file($installCssPath) ? (string) filemtime($installCssPath) : '1';
$from = isset($_GET['from']) && is_string($_GET['from']) ? trim($_GET['from']) : '';

if (!empty($_SESSION['fate_install_flash']) && is_string($_SESSION['fate_install_flash'])) {
    $success = (string) $_SESSION['fate_install_flash'];
    unset($_SESSION['fate_install_flash']);
}

$envChecks = fate_install_environment_checks();
$envFatalFail = false;
foreach ($envChecks as $envCheck) {
    if ($envCheck['fatal'] && !$envCheck['ok']) {
        $envFatalFail = true;
        break;
    }
}
$showEnvChecks = !$showWelcome && in_array($phase, ['no_db_config', 'db_unreachable', 'bad_config'], true);
$permChecks = fate_install_permission_checks();
$permFatalFail = fate_install_permission_has_fatal_failure($permChecks);
$permCanAutoFix = fate_install_permission_can_auto_fix($permChecks);
$showPermChecks = !$showWelcome;
$adminUrl = fate_install_admin_url();
$loginUrl = fate_install_asset_url('admin/login.php');
$adminCssUrl = fate_install_asset_url('admin/static/admin.css');
$installCssUrl = fate_install_asset_url('install/install.css');

header('Content-Type: text/html; charset=UTF-8');
?>
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="robots" content="noindex,nofollow">
    <?php
    require_once $fateRoot . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_favicon.php';
    fate_favicon_head_links();
    ?>
    <title>XSPA 安裝精靈</title>
    <link rel="stylesheet" href="<?= htmlspecialchars($adminCssUrl, ENT_QUOTES, 'UTF-8') ?>?v=<?= htmlspecialchars($cssVer, ENT_QUOTES, 'UTF-8') ?>">
    <link rel="stylesheet" href="<?= htmlspecialchars($installCssUrl, ENT_QUOTES, 'UTF-8') ?>?v=<?= htmlspecialchars($installCssVer, ENT_QUOTES, 'UTF-8') ?>">
</head>
<body class="admin-body">
<div class="admin-shell admin-shell--auth admin-shell--install">
    <main class="admin-main">
        <div class="install-brand">XSPA<span> 安裝精靈</span></div>

        <ol class="install-steps" aria-label="安裝步驟">
            <?php foreach ($installSteps as $step): ?>
                <?php
                $cls = match ($step['state']) {
                    'done' => 'is-done',
                    'active' => 'is-active',
                    default => 'is-pending',
                };
                ?>
                <li class="<?= htmlspecialchars($cls, ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars($step['label'], ENT_QUOTES, 'UTF-8') ?></li>
            <?php endforeach; ?>
        </ol>

        <header class="page-head">
            <h1 class="page-title"><?= $showWelcome ? '安裝完成' : '首次安裝' ?></h1>
            <p class="sub"><?= $showWelcome
                ? '網站已經可以使用了，以下是接下來的重點。'
                : '只要三步驟：連線資料庫 → 建立資料表 → 設定管理員。看不懂的欄位，直接用預設值即可。' ?></p>
        </header>

    <?php if ($showWelcome): ?>
        <?php unset($_SESSION['fate_install_welcome']); ?>
        <div class="msg ok">恭喜！XSPA 已安裝完成，管理員帳號也建立好了。</div>
        <div class="card install-welcome">
            <h2 class="card-title">接下來可以做這些</h2>
            <ol class="install-next">
                <li><strong>進入後台</strong>：用剛建立的管理員帳號登入，左側導覽列有所有功能。</li>
                <li><strong>同步店家資料</strong>：後台「同步」頁可從新手村 API 拉入店家與圖片。</li>
                <li><strong>設定 N 幣與獎勵</strong>：後台調整站內貨幣、推薦技師與<strong>本週推薦／週推榜</strong>（`admin/masseurs.php`、`admin/ncoin.php`）。</li>
                <li><strong>站內 BLOG</strong>：管理員登入後至 <code>blog.php</code> →「管理設定」開啟導覽、首頁公告，並發佈文章。</li>
            </ol>
            <div class="install-actions">
                <a class="btn-primary" href="<?= htmlspecialchars($adminUrl, ENT_QUOTES, 'UTF-8') ?>">進入後台</a>
            </div>
        </div>
        <div class="msg bad install-security">
            <strong>最後一步（很重要）：</strong>為了安全，請在主機上<strong>刪除整個 <code>install/</code> 目錄</strong>，或限制它的存取權限。安裝精靈已完成任務，不需要再對外開放。
        </div>
    <?php else: ?>

    <?php if ($from !== ''): ?>
        <div class="msg warn">系統尚未完成安裝，已從 <code><?= htmlspecialchars($from, ENT_QUOTES, 'UTF-8') ?></code> 導向至此。</div>
    <?php endif; ?>

    <?php if ($success !== null): ?>
        <div class="msg ok"><?= htmlspecialchars($success, ENT_QUOTES, 'UTF-8') ?></div>
    <?php endif; ?>

    <?php if ($error !== null): ?>
        <div class="msg bad"><?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></div>
    <?php endif; ?>

    <?php if ($showEnvChecks): ?>
        <div class="card install-env">
            <h2 class="card-title">環境檢查</h2>
            <p class="sub">開始前先確認主機環境。出現 <span class="env-x">✗</span> 的項目請先處理再繼續。</p>
            <ul class="install-env-list">
                <?php foreach ($envChecks as $envCheck): ?>
                    <li class="<?= $envCheck['ok'] ? 'is-ok' : ($envCheck['fatal'] ? 'is-fatal' : 'is-warn') ?>">
                        <span class="env-mark"><?= $envCheck['ok'] ? '✓' : '✗' ?></span>
                        <span class="env-label"><?= htmlspecialchars($envCheck['label'], ENT_QUOTES, 'UTF-8') ?></span>
                        <?php if (!$envCheck['ok'] && $envCheck['hint'] !== ''): ?>
                            <span class="env-hint"><?= htmlspecialchars($envCheck['hint'], ENT_QUOTES, 'UTF-8') ?></span>
                        <?php endif; ?>
                    </li>
                <?php endforeach; ?>
            </ul>
            <?php if ($envFatalFail): ?>
                <p class="sub env-blocked">請先修正上方紅色項目，重新整理本頁後再繼續。</p>
            <?php endif; ?>
        </div>
    <?php endif; ?>

    <?php if ($showPermChecks): ?>
        <div class="card install-env install-perm">
            <h2 class="card-title">目錄與權限</h2>
            <p class="sub">確認 PHP 能寫入設定、金鑰與上傳目錄。共享主機若一鍵修正失敗，請於 cPanel／Plesk 等面板調整資料夾權限（常見為 755 或 775）。</p>
            <ul class="install-env-list">
                <?php foreach ($permChecks as $permCheck): ?>
                    <li class="<?= $permCheck['ok'] ? 'is-ok' : ($permCheck['fatal'] ? 'is-fatal' : 'is-warn') ?>">
                        <span class="env-mark"><?= $permCheck['ok'] ? '✓' : '✗' ?></span>
                        <span class="env-label"><?= htmlspecialchars($permCheck['label'], ENT_QUOTES, 'UTF-8') ?>
                            <code class="perm-path"><?= htmlspecialchars($permCheck['path'], ENT_QUOTES, 'UTF-8') ?></code></span>
                        <?php if (!$permCheck['ok'] && $permCheck['hint'] !== ''): ?>
                            <span class="env-hint"><?= htmlspecialchars($permCheck['hint'], ENT_QUOTES, 'UTF-8') ?></span>
                        <?php endif; ?>
                    </li>
                <?php endforeach; ?>
            </ul>
            <?php if ($permCanAutoFix): ?>
                <form method="post" action="<?= htmlspecialchars($installActionUrl, ENT_QUOTES, 'UTF-8') ?>" class="install-perm-fix" data-install-form>
                    <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8') ?>">
                    <input type="hidden" name="action" value="fix_permissions">
                    <div class="install-actions">
                        <button type="submit" class="btn-ghost" data-submit-btn data-loading-text="修正中…">一鍵建立目錄／修正權限</button>
                    </div>
                </form>
            <?php endif; ?>
            <?php if ($permFatalFail): ?>
                <p class="sub env-blocked">請先修正上方紅色項目（至少須能寫入 <code>config/</code> 與 <code>data/</code>），再繼續安裝。</p>
            <?php endif; ?>
        </div>
    <?php endif; ?>

    <div class="card">
        <h2 class="card-title">目前進度</h2>
        <ul class="sub install-status-list">
            <li>資料庫連線：
                <?php if ($phase === 'no_db_config'): ?>
                    <span class="badge badge--pending">尚未設定</span>
                <?php elseif ($phase === 'db_unreachable'): ?>
                    <span class="badge badge--off">連線失敗</span>
                <?php elseif ($pdo instanceof PDO): ?>
                    <span class="badge badge--ok">已連線</span>
                <?php else: ?>
                    <span class="badge badge--pending">待確認</span>
                <?php endif; ?>
            </li>
            <li>資料表：
                <?php if ($pdo instanceof PDO && fate_install_schema_ready($pdo)): ?>
                    <span class="badge badge--ok">已建立</span>
                <?php else: ?>
                    <span class="badge badge--pending">尚未建立</span>
                <?php endif; ?>
            </li>
            <li>管理員帳號：
                <?php if ($pdo instanceof PDO && fate_install_admin_count($pdo, true) > 0): ?>
                    <span class="badge badge--ok">已建立</span>
                <?php else: ?>
                    <span class="badge badge--pending">尚未建立</span>
                <?php endif; ?>
            </li>
        </ul>
    </div>

    <?php if ($phase === 'bad_config'): ?>
        <div class="msg bad">會員表設定錯誤：<code>FATE_MEMBER_DATABASE</code> 與 <code>FATE_MEMBER_TABLE</code> 須為英數與底線。</div>
    <?php elseif (($phase === 'no_db_config' || $phase === 'db_unreachable') && $dbWizard && !$permFatalFail && !$envFatalFail): ?>
        <div class="card card--narrow">
            <h2 class="card-title">步驟 1：連線資料庫</h2>
            <p class="sub">請填寫<strong>主機控制台已建立</strong>的 MySQL 連線資訊（HestiaCP、cPanel、Plesk 等）。虛擬主機使用者<strong>無法</strong>由程式自動建立資料庫，須先於控制台建立資料庫與使用者，再將完整名稱貼入下方（常含帳號前綴，例如 <code>youruser_dbname</code>）。</p>
            <?php if ($phase === 'db_unreachable' && $connectError !== ''): ?>
                <div class="msg bad">上次連線失敗：<?= htmlspecialchars(fate_install_user_facing_db_error($connectError), ENT_QUOTES, 'UTF-8') ?></div>
            <?php endif; ?>
            <?php if (fate_db_config_source() === 'legacy' && !is_file(fate_install_db_config_path())): ?>
                <p class="sub">偵測到 <code>newbies/db_connect.php</code>，新安裝建議在此建立專用的 <code>config/db.php</code>（寫入後優先使用）。</p>
            <?php endif; ?>
            <form method="post" action="<?= htmlspecialchars($installActionUrl, ENT_QUOTES, 'UTF-8') ?>" autocomplete="off" data-install-form>
                <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8') ?>">
                <input type="hidden" name="action" value="save_db">
                <label for="db_host">資料庫主機</label>
                <input type="text" name="db_host" id="db_host" required maxlength="255"
                       value="<?= htmlspecialchars($dbForm['host'], ENT_QUOTES, 'UTF-8') ?>" placeholder="localhost">
                <p class="field-hint">多數虛擬主機填 <code>localhost</code>；若主機另有指定請依控制台為準。</p>
                <label for="db_name" style="margin-top:0.75rem;">資料庫名稱</label>
                <input type="text" name="db_name" id="db_name" required maxlength="64" pattern="[A-Za-z0-9_]+"
                       value="<?= htmlspecialchars($dbForm['name'], ENT_QUOTES, 'UTF-8') ?>" placeholder="youruser_dbname">
                <p class="field-hint">請填控制台顯示的<strong>完整</strong>資料庫名稱，不要留空或使用未建立的庫名。</p>
                <label for="db_user" style="margin-top:0.75rem;">使用者</label>
                <input type="text" name="db_user" id="db_user" required maxlength="128" autocomplete="off"
                       value="<?= htmlspecialchars($dbForm['user'], ENT_QUOTES, 'UTF-8') ?>" placeholder="youruser_dbuser">
                <label for="db_pass" style="margin-top:0.75rem;">密碼</label>
                <input type="password" name="db_pass" id="db_pass" autocomplete="new-password"
                       value="<?= htmlspecialchars($dbForm['pass'], ENT_QUOTES, 'UTF-8') ?>">
                <details class="install-advanced">
                    <summary>進階選項</summary>
                    <label for="db_charset">字元集</label>
                    <input type="text" name="db_charset" id="db_charset" maxlength="32" pattern="[A-Za-z0-9_]+"
                           value="<?= htmlspecialchars($dbForm['charset'], ENT_QUOTES, 'UTF-8') ?>">
                    <p class="field-hint">預設 utf8mb4，一般不需更動。</p>
                </details>
                <div class="install-actions">
                    <button type="submit" data-submit-btn data-loading-text="連線測試中…">測試連線並儲存</button>
                </div>
            </form>
        </div>
    <?php elseif ($phase === 'no_db_config' || $phase === 'db_unreachable'): ?>
        <div class="card">
            <h2 class="card-title">步驟 1：資料庫連線</h2>
            <?php if (($dbSummary['source'] ?? '') === 'env'): ?>
                <p class="sub">目前使用環境變數 <code>FATE_DB_*</code>，精靈無法覆寫。請在伺服器調整環境變數，或移除後改由 <code>config/db.php</code> 設定。</p>
                <p class="sub">主機 <code><?= htmlspecialchars((string) ($dbSummary['host'] ?? ''), ENT_QUOTES, 'UTF-8') ?></code>、資料庫 <code><?= htmlspecialchars((string) ($dbSummary['name'] ?? 'fate'), ENT_QUOTES, 'UTF-8') ?></code></p>
            <?php elseif (($dbSummary['source'] ?? '') === 'legacy'): ?>
                <p class="sub">目前偵測到 <code>newbies/db_connect.php</code>，但無法取得有效連線。請手動建立 <code>config/db.php</code>，或確認 legacy 連線可用。</p>
            <?php else: ?>
                <p class="sub"><code>config</code> 目錄不可寫入，無法自動建立 <code>db.php</code>。請手動複製 <code>config/db.example.php</code> 並調整權限。</p>
            <?php endif; ?>
            <?php if ($phase === 'db_unreachable' && $connectError !== ''): ?>
                <p class="sub">連線錯誤：<code><?= htmlspecialchars($connectError, ENT_QUOTES, 'UTF-8') ?></code></p>
            <?php endif; ?>
        </div>
    <?php elseif ($phase === 'admin_inactive'): ?>
        <div class="msg warn">已有管理員帳號但未啟用，請聯絡主機管理者或直接在資料庫啟用帳號，再至 <a href="<?= htmlspecialchars($loginUrl, ENT_QUOTES, 'UTF-8') ?>">後台登入</a>。</div>
    <?php else: ?>
        <?php if ($phase === 'schema_missing' && !$permFatalFail): ?>
            <div class="card">
                <h2 class="card-title">步驟 2：建立資料表</h2>
                <p class="sub">將在您已連線的資料庫 <code><?= htmlspecialchars((string) ($dbSummary['name'] ?? ''), ENT_QUOTES, 'UTF-8') ?></code> 內建立約 26 張資料表（僅結構與必要預設值）。<strong>不會</strong>建立新資料庫；共享主機須先在控制台建好資料庫。按下後請稍候幾秒。</p>
                <form method="post" action="<?= htmlspecialchars($installActionUrl, ENT_QUOTES, 'UTF-8') ?>" data-install-form>
                    <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8') ?>">
                    <input type="hidden" name="action" value="run_schema">
                    <div class="install-actions">
                        <button type="submit" data-submit-btn data-loading-text="建立中，請稍候…">建立全部資料表</button>
                    </div>
                </form>
            </div>
        <?php endif; ?>

        <?php if ($phase === 'no_admin' && $pdo instanceof PDO && !$permFatalFail): ?>
            <div class="card card--narrow" id="install-step-admin">
                <h2 class="card-title">步驟 3：建立第一位管理員</h2>
                <p class="sub">此帳號將寫入 <code><?= htmlspecialchars(FATE_MEMBER_DATABASE . '.' . FATE_MEMBER_TABLE, ENT_QUOTES, 'UTF-8') ?></code>，<code>role = admin</code>，可直接登入後台。</p>
                <form method="post" action="<?= htmlspecialchars($installActionUrl, ENT_QUOTES, 'UTF-8') ?>" autocomplete="username" data-install-form>
                    <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8') ?>">
                    <input type="hidden" name="action" value="create_admin">
                    <label for="username">帳號</label>
                    <input type="text" name="username" id="username" required autofocus maxlength="80"
                           value="<?= htmlspecialchars($stickyUsername, ENT_QUOTES, 'UTF-8') ?>">
                    <p class="field-hint">用來登入後台的帳號，建議用英數字。</p>
                    <label for="display_name" style="margin-top:0.75rem;">顯示名稱（選填，最多 <?= (int) fate_member_display_name_max_chars() ?> 字；未填將以帳號顯示）</label>
                    <input type="text" name="display_name" id="display_name" maxlength="<?= (int) fate_member_display_name_max_chars() ?>"
                           value="<?= htmlspecialchars($stickyDisplay, ENT_QUOTES, 'UTF-8') ?>">
                    <label for="email" style="margin-top:0.75rem;">Email（選填）</label>
                    <input type="email" name="email" id="email" maxlength="254" autocomplete="email">
                    <label for="password" style="margin-top:0.75rem;">密碼</label>
                    <div class="pw-field">
                        <input type="password" name="password" id="password" required minlength="8" autocomplete="new-password" data-pw>
                        <button type="button" class="pw-toggle" data-pw-toggle aria-label="顯示或隱藏密碼">顯示</button>
                    </div>
                    <div class="pw-strength" data-pw-strength hidden>
                        <span class="pw-strength-bar"><span data-pw-bar></span></span>
                        <span class="pw-strength-text" data-pw-text></span>
                    </div>
                    <p class="field-hint">至少 8 字元，建議混合大小寫、數字與符號。</p>
                    <label for="password_confirm" style="margin-top:0.75rem;">確認密碼</label>
                    <input type="password" name="password_confirm" id="password_confirm" required minlength="8" autocomplete="new-password" data-pw-confirm>
                    <p class="field-hint" data-pw-match hidden></p>
                    <div class="install-actions">
                        <button type="submit" data-submit-btn data-loading-text="建立中…">建立管理員並進入後台</button>
                    </div>
                </form>
            </div>
        <?php endif; ?>
    <?php endif; ?>

        <p class="sub install-foot">亦可手動匯入 <code>sql/install.sql</code> 後，若已有 admin 帳號請直接 <a href="<?= htmlspecialchars($loginUrl, ENT_QUOTES, 'UTF-8') ?>">登入後台</a>。</p>
    <?php endif; /* showWelcome */ ?>
    </main>
</div>
<script>
(function () {
    document.querySelectorAll('[data-pw-toggle]').forEach(function (btn) {
        btn.addEventListener('click', function () {
            var field = btn.closest('.pw-field');
            var input = field ? field.querySelector('[data-pw]') : null;
            if (!input) { return; }
            var show = input.type === 'password';
            input.type = show ? 'text' : 'password';
            btn.textContent = show ? '隱藏' : '顯示';
        });
    });

    var pw = document.querySelector('[data-pw]');
    var strengthBox = document.querySelector('[data-pw-strength]');
    var bar = document.querySelector('[data-pw-bar]');
    var text = document.querySelector('[data-pw-text]');
    function pwScore(v) {
        var s = 0;
        if (v.length >= 8) { s++; }
        if (v.length >= 12) { s++; }
        if (/[a-z]/.test(v) && /[A-Z]/.test(v)) { s++; }
        if (/\d/.test(v)) { s++; }
        if (/[^A-Za-z0-9]/.test(v)) { s++; }
        return s;
    }
    if (pw && strengthBox && bar && text) {
        pw.addEventListener('input', function () {
            var v = pw.value;
            if (!v) { strengthBox.hidden = true; return; }
            strengthBox.hidden = false;
            var s = pwScore(v);
            var level = s <= 2 ? 'weak' : (s === 3 ? 'fair' : (s === 4 ? 'good' : 'strong'));
            var labels = { weak: '偏弱', fair: '普通', good: '良好', strong: '很強' };
            bar.style.width = Math.min(100, s * 20) + '%';
            strengthBox.setAttribute('data-level', level);
            text.textContent = '強度：' + labels[level];
        });
    }

    var pwc = document.querySelector('[data-pw-confirm]');
    var matchEl = document.querySelector('[data-pw-match]');
    function checkMatch() {
        if (!pw || !pwc || !matchEl) { return; }
        if (!pwc.value) { matchEl.hidden = true; return; }
        matchEl.hidden = false;
        var ok = pw.value === pwc.value;
        matchEl.textContent = ok ? '兩次密碼一致' : '兩次密碼不一致';
        matchEl.className = 'field-hint ' + (ok ? 'is-ok' : 'is-bad');
    }
    if (pwc) {
        pwc.addEventListener('input', checkMatch);
        if (pw) { pw.addEventListener('input', checkMatch); }
    }

    document.querySelectorAll('form[data-install-form]').forEach(function (form) {
        form.addEventListener('submit', function () {
            var btn = form.querySelector('[data-submit-btn]');
            if (!btn) { return; }
            btn.disabled = true;
            btn.classList.add('is-loading');
            var t = btn.getAttribute('data-loading-text');
            if (t) { btn.textContent = t; }
        });
    });

    var adminStep = document.getElementById('install-step-admin');
    if (adminStep) {
        adminStep.scrollIntoView({ behavior: 'smooth', block: 'start' });
        var userInput = adminStep.querySelector('#username');
        if (userInput) { userInput.focus(); }
    }
})();
</script>
</body>
</html>
