<?php
require __DIR__ . '/app/bootstrap.php';
require __DIR__ . '/app/database.php';

if (!app_is_installed()) {
    redirect('install.php');
}

require_login(false);

$userId = current_user_id();
$adminName = isset($_SESSION['admin_name']) ? (string)$_SESSION['admin_name'] : 'Admin';

$pdo = db_connection();
$admin = find_admin_by_id($userId);
if ($admin && !empty($admin['initialized_at'])) {
    redirect('/admin/dashboard/index.php');
}

$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!csrf_verify()) {
        $error = '页面已过期，请刷新后重试。';
    } else {
        try {
            initialize_user_data($userId);
            $now = date('Y-m-d H:i:s');
            $firstAdmin = $pdo->query("SELECT id FROM admins ORDER BY id ASC LIMIT 1")->fetch(PDO::FETCH_ASSOC);
            $isFirst = ($firstAdmin && (int)$firstAdmin['id'] === $userId);
            $role = $isFirst ? 'super_admin' : null;
            if ($role) {
                $pdo->prepare("UPDATE admins SET initialized_at = :init_at, role = :role, updated_at = :upd_at WHERE id = :id")
                    ->execute(array(':init_at' => $now, ':role' => $role, ':upd_at' => $now, ':id' => $userId));
                $_SESSION['admin_role'] = $role;
            } else {
                $pdo->prepare("UPDATE admins SET initialized_at = :init_at, updated_at = :upd_at WHERE id = :id")
                    ->execute(array(':init_at' => $now, ':upd_at' => $now, ':id' => $userId));
            }
            $success = '数据初始化完成，即将进入后台...';
        } catch (Exception $e) {
            $error = '初始化失败：' . $e->getMessage();
        }
    }
}
?><!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo e(APP_NAME); ?> - 初始化</title>
    <link rel="stylesheet" href="assets/css/admin-ui.css">
    <style>
        .init-wrap { max-width: 520px; margin: 80px auto; padding: 0 20px; }
        .init-card { background: #fff; border-radius: 16px; box-shadow: 0 2px 24px rgba(0,0,0,0.07); padding: 40px 36px; text-align: center; }
        .init-card .brand-icon { width: 56px; height: 56px; border-radius: 14px; background: linear-gradient(135deg, #f59e0b 0%, #f97316 100%); color: #fff; font-size: 28px; display: flex; align-items: center; justify-content: center; margin: 0 auto 16px; }
        .init-card h1 { font-size: 22px; font-weight: 700; color: #111827; margin: 0 0 8px; }
        .init-card p { font-size: 14px; color: #6b7280; margin: 0 0 24px; line-height: 1.6; }
        .init-list { text-align: left; background: #f9fafb; border-radius: 10px; padding: 16px 20px; margin-bottom: 24px; font-size: 13px; color: #374151; line-height: 2; }
        .init-list strong { color: #111827; }
        .msg-box { padding: 12px 16px; border-radius: 8px; margin-bottom: 20px; font-size: 14px; }
        .msg-error { background: #fef2f2; color: #991b1b; border: 1px solid #fecaca; }
        .msg-success { background: #f0fdf4; color: #166534; border: 1px solid #bbf7d0; }
        .btn-init { width: 100%; padding: 13px; font-size: 16px; font-weight: 600; color: #fff; background: linear-gradient(135deg, #f59e0b 0%, #f97316 100%); border: none; border-radius: 10px; cursor: pointer; }
        .btn-init:hover { opacity: 0.9; }
    </style>
</head>
<body style="background: #f3f4f6; min-height: 100vh;">
<div class="init-wrap">
    <div class="init-card">
        <div class="brand-icon">蜂</div>
        <h1>欢迎使用 <?php echo e(APP_NAME); ?></h1>
        <p>您好，<strong><?php echo e($adminName); ?></strong>！这是您第一次登录，系统需要为您初始化基础数据。</p>

        <?php if ($error !== ''): ?>
            <div class="msg-box msg-error"><?php echo e($error); ?></div>
        <?php endif; ?>
        <?php if ($success !== ''): ?>
            <div class="msg-box msg-success"><?php echo e($success); ?></div>
            <script>setTimeout(function(){ window.location.href = '/admin/dashboard/index.php'; }, 1500);</script>
        <?php else: ?>
            <div class="init-list">
                <p>初始化将为您创建以下默认数据：</p>
                <p>• <strong>AI 模型配置</strong> — DeepSeek 和火山引擎（需自行填入 API Key）</p>
                <p>• <strong>示例模板</strong> — 基础首页模板和文章页模板</p>
            </div>
            <form method="post">
                <?php echo csrf_field(); ?>
                <button class="btn-init" type="submit">开始初始化</button>
            </form>
        <?php endif; ?>
    </div>
    <div style="text-align:center; margin-top:16px; font-size:12px; color:#9ca3af;">
        <?php echo e(APP_NAME); ?> v<?php echo e(APP_VERSION); ?>
    </div>
</div>
</body>
</html>
