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

if (!fate_admin_ip_access_allowed()) {
    http_response_code(403);
    header('Content-Type: text/html; charset=UTF-8');
    echo '<!DOCTYPE html><html lang="zh-Hant"><head><meta charset="UTF-8"><title>403 Forbidden</title></head><body>';
    echo '<p>此管理後台僅允許指定 IP 存取。</p></body></html>';
    exit;
}

$reason = isset($_GET['reason']) ? (string) $_GET['reason'] : '';

$err = isset($_GET['err']) ? (string) $_GET['err'] : '';

$stickyUsername = '';

$dbErrDetail = '';

$next = fate_admin_safe_next(isset($_GET['next']) ? (string) $_GET['next'] : null);

if (fate_admin_is_logged_in()) {

    header('Location: ' . $next, true, 302);

    exit;

}

$installProbe = fate_install_probe($dbErrDetail);
if (!$installProbe['complete'] && in_array($installProbe['phase'], ['schema_missing', 'no_admin', 'no_db_config', 'db_unreachable', 'bad_config'], true)) {
    header('Location: ' . fate_install_to_absolute(fate_install_web_path('install/') . '?from=login.php'), true, 302);
    exit;
}



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

if (fate_member_bridge_try_restore_admin_from_site()) {

    header('Location: ' . $next, true, 302);

    exit;

}



fate_admin_reset_login_session_if_needed($reason);

if ($_SERVER['REQUEST_METHOD'] !== 'POST' && fate_admin_member_auth_ready()) {
    $probePdo = fate_admin_get_pdo($dbErrDetail);
    if (!$probePdo instanceof PDO) {
        $err = 'db';
    }
}

$formAction = 'login.php';

if (!empty($_SERVER['QUERY_STRING'])) {

    $formAction .= '?' . (string) $_SERVER['QUERY_STRING'];

}



if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    if (!fate_admin_member_auth_ready()) {

        header('Location: login.php?reason=badconfig', true, 302);

        exit;

    }

    $pdo = fate_admin_get_pdo($dbErrDetail);

    if (!$pdo instanceof PDO) {

        $err = 'db';

    }



    if ($err !== 'db' && $pdo instanceof PDO) {

        $un = isset($_POST['username']) && is_string($_POST['username']) ? trim($_POST['username']) : '';

        $pw = isset($_POST['password']) && is_string($_POST['password']) ? $_POST['password'] : '';

        $stickyUsername = $un;

        $nextPost = fate_admin_safe_next(isset($_POST['next']) ? (string) $_POST['next'] : null);



        $auth = fate_admin_member_authenticate($pdo, $un, $pw);

        if ($auth['ok']) {

            $remember = !empty($_POST['remember']);

            fate_admin_complete_login($auth['member'], $remember);

            header('Location: ' . $nextPost, true, 303);

            exit;

        }

        $ae = $auth['err'] ?? '';

        if ($ae === 'missing_table') {

            $err = 'missing_table';

        } elseif ($ae === 'bad_column') {

            $err = 'bad_column';

        } elseif ($ae === 'forbidden') {

            $err = 'forbidden';

        } else {

            $err = 'bad';

        }

        $next = $nextPost;

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

    }

}



fate_admin_layout_start(['page' => '登入', 'bare' => true]);

?>

        <header class="page-head">

            <h1 class="page-title">登入</h1>

            <p class="sub">

                與<strong>前台會員</strong>相同資料表

                <code><?= htmlspecialchars(FATE_MEMBER_DATABASE . '.' . FATE_MEMBER_TABLE, ENT_QUOTES, 'UTF-8') ?></code>（須 <code>role = admin</code>）。

                若已於前台登入同一 admin 帳號，進入後台頁面會自動帶入，無須再登入一次。

                亦可在此單獨登入；登入後前台亦會同步登入。

            </p>

        </header>



        <?php if ($reason === 'session'): ?>

            <div class="msg warn">工作階段已過期或尚未登入，請重新登入<?= $next !== 'index.php' ? '（登入後將返回原頁面）' : '' ?>。</div>

        <?php endif; ?>



        <?php if ($reason === 'badconfig'): ?>

            <div class="msg warn">後台設定錯誤：<code>FATE_MEMBER_DATABASE</code> 與 <code>FATE_MEMBER_TABLE</code> 須為英數與底線組成的識別名。</div>

        <?php endif; ?>



        <?php if ($err === 'db'):
            require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_db_connect.php';
            $dbSummary = fate_db_config_summary();
            $dbSource = (string) ($dbSummary['source'] ?? 'missing');
        ?>

            <div class="msg bad">
                無法連線 MySQL，無法驗證帳號。
                <?php if ($dbErrDetail !== ''): ?>
                    <br><span class="sub" style="display:block;margin-top:.35rem;"><?= htmlspecialchars($dbErrDetail, ENT_QUOTES, 'UTF-8') ?></span>
                <?php endif; ?>
                <?php if ($dbSource === 'missing'): ?>
                    <br>請將 <code>fate/config/db.example.php</code> 複製為 <code>fate/config/db.php</code> 並填入連線資訊。
                <?php elseif ($dbSource === 'env'): ?>
                    <br>目前使用環境變數 <code>FATE_DB_*</code>（優先於 <code>config/db.php</code>）。主機 <code><?= htmlspecialchars((string) ($dbSummary['host'] ?? ''), ENT_QUOTES, 'UTF-8') ?></code>、資料庫 <code><?= htmlspecialchars((string) ($dbSummary['name'] ?? 'fate'), ENT_QUOTES, 'UTF-8') ?></code>。
                <?php elseif ($dbSource === 'file'): ?>
                    <br>設定檔 <code>fate/config/db.php</code> · 主機 <code><?= htmlspecialchars((string) ($dbSummary['host'] ?? ''), ENT_QUOTES, 'UTF-8') ?></code>、資料庫 <code><?= htmlspecialchars((string) ($dbSummary['name'] ?? 'fate'), ENT_QUOTES, 'UTF-8') ?></code>、帳號 <code><?= htmlspecialchars((string) ($dbSummary['user'] ?? ''), ENT_QUOTES, 'UTF-8') ?></code>。
                <?php endif; ?>
            </div>

        <?php endif; ?>



        <?php if ($err === 'missing_table'): ?>

            <div class="msg bad">

                找不到會員資料表 <code><?= htmlspecialchars(FATE_MEMBER_DATABASE . '.' . FATE_MEMBER_TABLE, ENT_QUOTES, 'UTF-8') ?></code>。

                請以環境變數設定 <code>FATE_MEMBER_DATABASE</code>、<code>FATE_MEMBER_TABLE</code>（預設已改為 <code>fate.members</code>）。

            </div>

        <?php endif; ?>



        <?php if ($err === 'bad_column'): ?>

            <div class="msg bad">

                會員表缺少或無法讀取啟用欄位 <code><?= htmlspecialchars(FATE_MEMBER_ACTIVE_COLUMN, ENT_QUOTES, 'UTF-8') ?></code>。

                請以環境變數 <code>FATE_MEMBER_ACTIVE_COLUMN</code> 對應實際欄位名。

            </div>

        <?php endif; ?>



        <?php if ($err === 'forbidden'): ?>

            <div class="msg bad">此帳號非管理員（<code>role</code> 須為 <code>admin</code>）。一般會員請使用站台前台登入。</div>

        <?php endif; ?>



        <?php if ($err === 'bad'): ?>

            <div class="msg bad">帳號或密碼不正確，或帳號未啟用。</div>

        <?php endif; ?>



        <?php if (!fate_admin_member_auth_ready()): ?>

            <div class="msg warn">請修正 <code>FATE_MEMBER_DATABASE</code>、<code>FATE_MEMBER_TABLE</code> 環境變數或預設值。</div>

        <?php else: ?>

            <div class="card card--narrow">

                <form method="post" action="<?= htmlspecialchars($formAction, ENT_QUOTES, 'UTF-8') ?>" autocomplete="username">

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

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

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

                    <?php endif; ?>

                    <label for="username">帳號</label>

                    <input type="text" name="username" id="username" required autofocus autocomplete="username" maxlength="80"

                           value="<?= htmlspecialchars($stickyUsername, ENT_QUOTES, 'UTF-8') ?>">

                    <label for="password" style="margin-top:0.75rem;">密碼</label>

                    <input type="password" name="password" id="password" required autocomplete="current-password">

                    <label class="sub" style="display:flex;align-items:center;gap:.45rem;margin:.65rem 0 0;cursor:pointer;">

                        <input type="checkbox" name="remember" value="1" checked>

                        保持登入（約 30 天，建議勾選）

                    </label>

                    <div style="margin-top:1rem;">

                        <button type="submit">登入</button>

                    </div>

                </form>

            </div>

        <?php endif; ?>

<?php

fate_admin_layout_end();


