<?php
declare(strict_types=1);

/**
 * 已登入管理員：在目前 USE 的 fate 資料庫內建立 spa_store_snapshots。
 */
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 . 'spa_store_snapshots_ddl.php';

fate_admin_require_login();

$pdo = 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) {
    fate_admin_layout_start(['page' => '建立資料表', 'active' => 'home']);
    echo '<div class="msg bad">無法連線資料庫：' . htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8') . '</div>';
    fate_admin_layout_end();
    exit;
}

if (!$pdo instanceof PDO) {
    fate_admin_layout_start(['page' => '建立資料表', 'active' => 'home']);
    echo '<div class="msg bad">未取得 PDO。</div>';
    fate_admin_layout_end();
    exit;
}

$error = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $csrf = isset($_POST['csrf']) && is_string($_POST['csrf']) ? $_POST['csrf'] : '';
    if (!fate_admin_csrf_check($csrf)) {
        $error = '工作階段逾期或驗證失敗，請重新整理後再試。';
    } else {
        try {
            $pdo->exec(fate_spa_store_snapshots_create_ddl());
            header('Location: index.php?setup=ok', true, 302);
            exit;
        } catch (Throwable $e) {
            $error = $e->getMessage();
        }
    }
}

$csrf = fate_admin_csrf_token();

fate_admin_layout_start(['page' => '建立資料表', 'active' => 'home']);
?>
        <header class="page-head">
            <h1 class="page-title">建立 <code>spa_store_snapshots</code></h1>
            <p class="sub">
                在目前連線所選定的 fate 資料庫內執行 <code>CREATE TABLE IF NOT EXISTS</code>。
                亦可直接匯入 <code>fate/sql/install.sql</code> 一次建立資料庫與全部資料表。
            </p>
        </header>

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

        <div class="card">
            <form method="post" action="setup_snapshots_table.php">
                <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8') ?>">
                <button type="submit">建立資料表</button>
            </form>
        </div>
        <div class="page-actions"><a class="btn" href="index.php">返回概覽</a></div>
<?php
fate_admin_layout_end();
