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

$configFile = app_config_file_path();
$installLockFile = app_install_lock_file_path();
$appDir = __DIR__ . '/app';
$runtimeDir = __DIR__ . '/runtime';

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

// ---------------- helpers ----------------
function installer_environment_checks($configFile, $appDir, $runtimeDir)
{
    $checks = array();
    $checks[] = array(
        'label' => 'PHP 版本 >= 7.4',
        'ok' => version_compare(PHP_VERSION, '7.4.0', '>='),
        'message' => '当前版本：' . PHP_VERSION
    );
    $checks[] = array(
        'label' => 'PDO 扩展',
        'ok' => extension_loaded('pdo'),
        'message' => extension_loaded('pdo') ? '已启用' : '未启用'
    );
    $checks[] = array(
        'label' => 'PDO MySQL 扩展',
        'ok' => extension_loaded('pdo_mysql'),
        'message' => extension_loaded('pdo_mysql') ? '已启用' : '未启用'
    );
    $checks[] = array(
        'label' => 'GD 扩展',
        'ok' => extension_loaded('gd'),
        'message' => extension_loaded('gd') ? '已启用（验证码/封面图依赖）' : '未启用（登录验证码会无法生成）'
    );
    $checks[] = array(
        'label' => 'cURL 扩展',
        'ok' => extension_loaded('curl'),
        'message' => extension_loaded('curl') ? '已启用（AI 模型请求依赖）' : '未启用（AI 生成、一键建站将无法使用）'
    );
    $checks[] = array(
        'label' => 'fileinfo 扩展',
        'ok' => extension_loaded('fileinfo'),
        'message' => extension_loaded('fileinfo') ? '已启用（图片 MIME 校验依赖）' : '未启用（将回退 getimagesize 校验）'
    );
    $uploadsDir = dirname($appDir) . '/uploads';
    $checks[] = array(
        'label' => 'uploads 目录可写',
        'ok' => is_dir($uploadsDir) ? is_writable($uploadsDir) : is_writable(dirname($uploadsDir)),
        'message' => $uploadsDir . (is_dir($uploadsDir) ? '' : '（首次安装会自动创建）')
    );
    $checks[] = array(
        'label' => 'Session 支持',
        'ok' => function_exists('session_start'),
        'message' => '用于向导步骤间传递数据'
    );
    $checks[] = array(
        'label' => 'app 目录可写',
        'ok' => is_dir($appDir) && is_writable($appDir),
        'message' => $appDir
    );
    $checks[] = array(
        'label' => 'runtime 目录可写',
        'ok' => is_dir($runtimeDir) ? is_writable($runtimeDir) : is_writable(dirname($runtimeDir)),
        'message' => $runtimeDir
    );
    $checks[] = array(
        'label' => '配置文件可创建',
        'ok' => file_exists($configFile) ? is_writable($configFile) : is_writable(dirname($configFile)),
        'message' => $configFile
    );
    $templatesDir = dirname($appDir) . '/templates';
    $checks[] = array(
        'label' => 'templates 目录可写',
        'ok' => is_dir($templatesDir) ? is_writable($templatesDir) : is_writable(dirname($templatesDir)),
        'message' => $templatesDir . (is_dir($templatesDir) ? '' : '（首次安装会自动创建）')
    );
    return $checks;
}

function installer_all_checks_pass($checks)
{
    foreach ($checks as $check) {
        if (empty($check['ok'])) {
            return false;
        }
    }
    return true;
}

function install_write_config_file($configFile, $db)
{
    $config = array(
        'db' => array(
            'host' => $db['host'],
            'port' => $db['port'],
            'name' => $db['name'],
            'user' => $db['user'],
            'pass' => $db['pass'],
            'charset' => $db['charset']
        )
    );
    if (file_exists($configFile)) {
        $existing = @include $configFile;
        if (is_array($existing)) {
            if (isset($existing['encryption_key']) && $existing['encryption_key'] !== '') {
                $config['encryption_key'] = $existing['encryption_key'];
            }
            foreach ($existing as $k => $v) {
                if (strpos($k, 'license') === 0 && is_array($v) && !empty($v)) {
                    $config[$k] = $v;
                }
            }
        }
    }
    $content = "<?php\nreturn " . var_export($config, true) . ";\n";
    return file_put_contents($configFile, $content, LOCK_EX) !== false;
}

function wizard_data()
{
    if (!isset($_SESSION['install_wizard']) || !is_array($_SESSION['install_wizard'])) {
        $_SESSION['install_wizard'] = array();
    }
    return $_SESSION['install_wizard'];
}

function wizard_save($patch)
{
    $data = wizard_data();
    foreach ($patch as $k => $v) {
        $data[$k] = $v;
    }
    $_SESSION['install_wizard'] = $data;
}

function wizard_emit($line)
{
    echo json_encode($line, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n";
    @ob_flush();
    @flush();
}

// ---------------- already installed guard ----------------
if (app_is_installed()) {
    ?>
    <!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>
        <style>
        *{margin:0;padding:0;box-sizing:border-box}
        body{min-height:100vh;display:flex;align-items:center;justify-content:center;background:#0f172a;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif;overflow:hidden}
        body::before{content:'';position:fixed;inset:0;background:radial-gradient(ellipse 80% 60% at 50% 0%,rgba(99,102,241,.15) 0%,transparent 60%),radial-gradient(ellipse 60% 50% at 80% 100%,rgba(168,85,247,.1) 0%,transparent 50%)}
        .card{position:relative;background:rgba(255,255,255,.04);backdrop-filter:blur(40px);-webkit-backdrop-filter:blur(40px);border:1px solid rgba(255,255,255,.08);border-radius:32px;padding:56px 52px 48px;max-width:520px;width:calc(100% - 40px);text-align:center;overflow:hidden}
        .orb{position:absolute;border-radius:50%;filter:blur(80px);pointer-events:none;opacity:.6}
        .orb-1{width:260px;height:260px;background:rgba(99,102,241,.3);top:-100px;right:-80px}
        .orb-2{width:200px;height:200px;background:rgba(168,85,247,.2);bottom:-60px;left:-60px}
        .badge-success{width:56px;height:56px;border-radius:50%;background:linear-gradient(135deg,#22c55e,#16a34a);display:flex;align-items:center;justify-content:center;margin:0 auto 20px;box-shadow:0 8px 30px rgba(34,197,94,.35);animation:pop .5s cubic-bezier(.34,1.56,.64,1)}
        @keyframes pop{0%{transform:scale(0);opacity:0}100%{transform:scale(1);opacity:1}}
        .logo{width:80px;height:80px;margin:0 auto 16px;display:block;object-fit:contain;filter:drop-shadow(0 8px 24px rgba(0,0,0,.35))}
        .brand{font-size:14px;font-weight:600;color:rgba(165,180,252,.9);letter-spacing:2px;text-transform:uppercase;margin-bottom:28px}
        h1{font-size:28px;font-weight:800;color:#fff;margin-bottom:14px;letter-spacing:-.5px}
        .lead{color:rgba(203,213,225,.8);font-size:15px;line-height:1.8;margin-bottom:32px}
        .btn{display:inline-flex;align-items:center;gap:10px;padding:16px 40px;background:linear-gradient(135deg,#6366f1,#8b5cf6);color:#fff;font-size:16px;font-weight:700;border-radius:16px;text-decoration:none;transition:all .3s;box-shadow:0 12px 36px rgba(99,102,241,.4);border:1px solid rgba(255,255,255,.1)}
        .btn:hover{transform:translateY(-3px);box-shadow:0 16px 48px rgba(99,102,241,.5);background:linear-gradient(135deg,#818cf8,#a78bfa)}
        .btn:active{transform:translateY(-1px)}
        .hint{display:flex;align-items:center;gap:8px;justify-content:center;margin-top:28px;padding:14px 20px;border-radius:14px;background:rgba(255,255,255,.04);border:1px solid rgba(255,255,255,.06);font-size:13px;color:rgba(148,163,184,.7);line-height:1.6}
        .hint svg{flex-shrink:0;opacity:.5}
        .hint code{background:rgba(99,102,241,.15);color:#a5b4fc;padding:2px 7px;border-radius:6px;font-size:12px}
        .foot{margin-top:28px;font-size:13px;color:rgba(100,116,139,.5);letter-spacing:.5px}
        @media(max-width:560px){.card{padding:40px 28px 36px}h1{font-size:22px}.btn{padding:14px 32px;font-size:15px}}
        </style>
    </head>
    <body>
    <div class="card">
        <div class="orb orb-1"></div>
        <div class="orb orb-2"></div>
        <div class="badge-success">
            <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6L9 17l-5-5"/></svg>
        </div>
        <img class="logo" src="admin-bee.png" alt="<?php echo e(APP_NAME); ?>">
        <div class="brand"><?php echo e(APP_NAME); ?></div>
        <h1>部署成功，系统已就绪</h1>
        <p class="lead">恭喜！安装已完成，所有服务组件均已初始化。<br>您可以立即进入管理后台开始使用。</p>
        <a class="btn" href="login.php">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4"/><polyline points="10 17 15 12 10 7"/><line x1="15" y1="12" x2="3" y2="12"/></svg>
            进入管理后台
        </a>
        <div class="hint">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>
            如需重新安装，请删除 <code>runtime/install.lock</code> 与 <code>app/config.php</code>
        </div>
        <div class="foot"><?php echo e(APP_NAME); ?> · v<?php echo e(APP_VERSION); ?></div>
    </div>
    </body>
    </html>
    <?php
    exit;
}

// ---------------- step 6: streaming install endpoint ----------------
if (isset($_GET['step']) && (string)$_GET['step'] === '6' && isset($_GET['action']) && $_GET['action'] === 'run') {
    @set_time_limit(300);
    while (ob_get_level() > 0) { ob_end_clean(); }
    @ini_set('zlib.output_compression', '0');
    @ini_set('implicit_flush', '1');
    ob_implicit_flush(true);
    header('Content-Type: application/x-ndjson; charset=utf-8');
    header('Cache-Control: no-cache');
    header('X-Accel-Buffering: no');

    $data = wizard_data();
    if (empty($data['db']) || empty($data['admin'])) {
        wizard_emit(array('status' => 'error', 'message' => '向导数据丢失，请返回重新填写。'));
        exit;
    }

    $db = $data['db'];
    $admin = $data['admin'];

    $tasks = array(
        array('key' => 'db', 'label' => '连接 MySQL 并创建数据库'),
        array('key' => 'config', 'label' => '写入数据库配置文件'),
        array('key' => 'admin_table', 'label' => '初始化管理员表'),
        array('key' => 'template_table', 'label' => '初始化模板表'),
        array('key' => 'domain_table', 'label' => '初始化域名表'),
        array('key' => 'ai_model_table', 'label' => '初始化 AI 模型表'),
        array('key' => 'menu_table', 'label' => '初始化栏目菜单表'),
        array('key' => 'content_table', 'label' => '初始化内容表'),
        array('key' => 'publish_table', 'label' => '初始化发布日志表'),
        array('key' => 'site_task_table', 'label' => '初始化建站任务表'),
        array('key' => 'article_task_table', 'label' => '初始化文章任务表'),
        array('key' => 'ad_table', 'label' => '初始化广告表'),
        array('key' => 'template_packs', 'label' => '初始化模板套件目录'),
        array('key' => 'uploads_dir', 'label' => '创建图片上传目录'),
        array('key' => 'admin_user', 'label' => '创建管理员账号'),
        array('key' => 'lock', 'label' => '生成安装锁文件')
    );
    wizard_emit(array('status' => 'start', 'total' => count($tasks), 'tasks' => $tasks));

    try {
        // 1. connect + create db
        wizard_emit(array('status' => 'running', 'key' => 'db'));
        $collation = $db['charset'] === 'utf8mb4' ? 'utf8mb4_unicode_ci' : $db['charset'] . '_general_ci';
        $dsn = 'mysql:host=' . $db['host'] . ';port=' . $db['port'] . ';charset=' . $db['charset'];
        $pdo = new PDO($dsn, $db['user'], $db['pass'], array(
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES => false
        ));
        $pdo->exec('CREATE DATABASE IF NOT EXISTS `' . str_replace('`', '``', $db['name']) . '` DEFAULT CHARACTER SET ' . $db['charset'] . ' COLLATE ' . $collation);
        wizard_emit(array('status' => 'done', 'key' => 'db', 'message' => '数据库 ' . $db['name'] . ' 已就绪'));

        // 2. config file
        wizard_emit(array('status' => 'running', 'key' => 'config'));
        if (!install_write_config_file($GLOBALS['configFile'], $db)) {
            throw new Exception('配置文件写入失败，请检查 app 目录写权限。');
        }
        wizard_emit(array('status' => 'done', 'key' => 'config', 'message' => '配置文件已写入'));

        require_once __DIR__ . '/app/database.php';

        $steps = array(
            'admin_table' => 'ensure_admin_storage_ready',
            'template_table' => 'ensure_template_storage_ready',
            'domain_table' => 'ensure_domain_storage_ready',
            'ai_model_table' => 'ensure_ai_model_storage_ready',
            'menu_table' => 'ensure_menu_storage_ready',
            'content_table' => 'ensure_content_storage_ready',
            'publish_table' => 'ensure_publish_log_storage_ready',
            'site_task_table' => 'ensure_site_build_task_storage_ready',
            'article_task_table' => 'ensure_article_generation_task_storage_ready',
            'ad_table' => 'ensure_article_ad_storage_ready',
            'component_table' => 'ensure_component_storage_ready',
            'template_packs' => 'initialize_builtin_template_packs'
        );
        foreach ($steps as $k => $fn) {
            wizard_emit(array('status' => 'running', 'key' => $k));
            if (function_exists($fn)) {
                $fn();
            }
            wizard_emit(array('status' => 'done', 'key' => $k, 'message' => '完成'));
            usleep(120000);
        }

        // uploads 目录（管理端共享 fallback；各站点共享使用 site_root/uploads，会在首次上传时自动创建）
        wizard_emit(array('status' => 'running', 'key' => 'uploads_dir'));
        $uploadsDir = dirname($GLOBALS['appDir']) . '/uploads';
        if (!is_dir($uploadsDir)) {
            @mkdir($uploadsDir, 0777, true);
        }
        if (!is_dir($uploadsDir)) {
            throw new Exception('创建 uploads 目录失败，请检查根目录写权限。');
        }
        wizard_emit(array('status' => 'done', 'key' => 'uploads_dir', 'message' => $uploadsDir));

        // admin user（幂等：存在则重置密码与显示名，避免重复安装时旧密码残留）
        wizard_emit(array('status' => 'running', 'key' => 'admin_user'));
        $existingAdmin = find_admin_by_username($admin['username']);
        if (!$existingAdmin) {
            create_admin(array(
                'username' => $admin['username'],
                'display_name' => $admin['name'],
                'password' => $admin['password'],
                'status' => 'enabled',
                'role' => 'super_admin'
            ));
            $adminMsg = '账号 ' . $admin['username'] . ' 已创建';
        } else {
            $pdoReset = db_connection();
            $pdoReset->prepare('UPDATE admins SET display_name = :display_name, password = :password, status = :status, role = :role, updated_at = :updated_at WHERE id = :id LIMIT 1')->execute(array(
                ':display_name' => $admin['name'],
                ':password' => hash_admin_password($admin['password']),
                ':status' => 'enabled',
                ':role' => 'super_admin',
                ':updated_at' => date('Y-m-d H:i:s'),
                ':id' => (int)$existingAdmin['id']
            ));
            $adminMsg = '账号 ' . $admin['username'] . ' 已存在，密码与信息已重置';
        }
        wizard_emit(array('status' => 'done', 'key' => 'admin_user', 'message' => $adminMsg));

        // lock
        wizard_emit(array('status' => 'running', 'key' => 'lock'));
        $lockDir = dirname($GLOBALS['installLockFile']);
        if (!is_dir($lockDir)) {
            mkdir($lockDir, 0777, true);
        }
        file_put_contents($GLOBALS['installLockFile'], json_encode(array(
            'installed_at' => date('Y-m-d H:i:s'),
            'app_version' => APP_VERSION,
            'admin_username' => $admin['username']
        ), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
        wizard_emit(array('status' => 'done', 'key' => 'lock', 'message' => 'install.lock 已生成'));

        wizard_save(array(
            'completed' => true,
            'completed_at' => date('Y-m-d H:i:s'),
            'admin_username' => $admin['username'],
            'admin_name' => $admin['name']
        ));

        // 清除敏感数据
        $_SESSION['install_wizard']['db'] = null;
        $_SESSION['install_wizard']['admin'] = null;

        wizard_emit(array('status' => 'complete', 'message' => '全部安装步骤已完成', 'redirect' => 'install.php?step=7'));
    } catch (Exception $e) {
        wizard_emit(array('status' => 'error', 'message' => $e->getMessage()));
    }
    exit;
}

// ---------------- step routing ----------------
$step = isset($_GET['step']) ? (int)$_GET['step'] : 1;
if ($step < 1 || $step > 7) { $step = 1; }

$error = '';
$data = wizard_data();

$dbDefaults = array(
    'db_host' => '127.0.0.1',
    'db_port' => '3306',
    'db_name' => '',
    'db_user' => '',
    'db_pass' => '',
    'db_charset' => 'utf8mb4'
);
$adminDefaults = array(
    'admin_username' => 'admin',
    'admin_name' => '管理员',
    'admin_password' => '',
    'admin_password_confirm' => ''
);
$dbForm = $dbDefaults;
if (!empty($data['db'])) {
    $dbForm['db_host'] = $data['db']['host'];
    $dbForm['db_port'] = $data['db']['port'];
    $dbForm['db_name'] = $data['db']['name'];
    $dbForm['db_user'] = $data['db']['user'];
    $dbForm['db_pass'] = $data['db']['pass'];
    $dbForm['db_charset'] = $data['db']['charset'];
}
$adminForm = $adminDefaults;
if (!empty($data['admin'])) {
    $adminForm['admin_username'] = $data['admin']['username'];
    $adminForm['admin_name'] = $data['admin']['name'];
}

// Step 4 POST: db config
if ($step === 4 && $_SERVER['REQUEST_METHOD'] === 'POST') {
    foreach ($dbForm as $k => $v) {
        $dbForm[$k] = isset($_POST[$k]) ? trim((string)$_POST[$k]) : '';
    }
    if ($dbForm['db_charset'] === '') { $dbForm['db_charset'] = 'utf8mb4'; }

    if ($dbForm['db_host'] === '' || $dbForm['db_port'] === '' || $dbForm['db_name'] === '' || $dbForm['db_user'] === '') {
        $error = '请完整填写数据库主机、端口、名称与账号。';
    } else {
        try {
            $dsn = 'mysql:host=' . $dbForm['db_host'] . ';port=' . $dbForm['db_port'] . ';charset=' . $dbForm['db_charset'];
            new PDO($dsn, $dbForm['db_user'], $dbForm['db_pass'], array(
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_TIMEOUT => 5
            ));
            wizard_save(array('db' => array(
                'host' => $dbForm['db_host'],
                'port' => $dbForm['db_port'],
                'name' => $dbForm['db_name'],
                'user' => $dbForm['db_user'],
                'pass' => $dbForm['db_pass'],
                'charset' => $dbForm['db_charset']
            )));
            header('Location: install.php?step=5');
            exit;
        } catch (Exception $e) {
            $error = '数据库连接失败：' . $e->getMessage();
        }
    }
}

// Step 5 POST: admin info
if ($step === 5 && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $adminForm['admin_username'] = isset($_POST['admin_username']) ? trim((string)$_POST['admin_username']) : '';
    $adminForm['admin_name'] = isset($_POST['admin_name']) ? trim((string)$_POST['admin_name']) : '';
    $adminForm['admin_password'] = isset($_POST['admin_password']) ? (string)$_POST['admin_password'] : '';
    $adminForm['admin_password_confirm'] = isset($_POST['admin_password_confirm']) ? (string)$_POST['admin_password_confirm'] : '';

    if ($adminForm['admin_username'] === '' || $adminForm['admin_name'] === '' || $adminForm['admin_password'] === '') {
        $error = '请完整填写管理员账号、名称与密码。';
    } elseif (strlen($adminForm['admin_password']) < 6) {
        $error = '管理员密码长度至少为 6 位。';
    } elseif ($adminForm['admin_password'] !== $adminForm['admin_password_confirm']) {
        $error = '两次输入的密码不一致。';
    } else {
        wizard_save(array('admin' => array(
            'username' => $adminForm['admin_username'],
            'name' => $adminForm['admin_name'],
            'password' => $adminForm['admin_password']
        )));
        header('Location: install.php?step=6');
        exit;
    }
}

// Step guards
if ($step === 5 && empty($data['db'])) { header('Location: install.php?step=4'); exit; }
if ($step === 6 && (empty($data['db']) || empty($data['admin']))) {
    $missing = empty($data['db']) ? 4 : 5;
    header('Location: install.php?step=' . $missing);
    exit;
}

$checks = installer_environment_checks($configFile, $appDir, $runtimeDir);
$checksPass = installer_all_checks_pass($checks);

$stepsMeta = array(
    1 => array('title' => '合法使用承诺', 'desc' => '阅读并同意使用条款'),
    2 => array('title' => '欢迎使用', 'desc' => '了解本次安装将为你做的事'),
    3 => array('title' => '环境检测', 'desc' => '确认服务器运行环境已就绪'),
    4 => array('title' => '数据库配置', 'desc' => '填写并测试数据库连接'),
    5 => array('title' => '管理员账户', 'desc' => '创建首个后台管理员'),
    6 => array('title' => '执行安装', 'desc' => '写入配置、建表、初始化数据'),
    7 => array('title' => '完成', 'desc' => '进入后台开始使用')
);
?><!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); ?> - 安装向导 · 第 <?php echo $step; ?> 步</title>
    <link rel="stylesheet" href="assets/css/admin-ui.css">
</head>
<body>
<div class="install-shell">
    <div class="install-wrap">

        <header class="install-header">
            <div class="install-brand">
                <img src="admin-bee.png" alt="<?php echo e(APP_NAME); ?>" style="width:44px;height:44px;object-fit:contain;">
                <div>
                    <strong><?php echo e(APP_NAME); ?></strong>
                    <span>Installation Wizard · v<?php echo e(APP_VERSION); ?></span>
                </div>
            </div>
        </header>

        <?php if ($step > 1): ?>
        <ol class="install-stepper">
            <?php foreach ($stepsMeta as $n => $meta):
                $state = $n < $step ? 'done' : ($n === $step ? 'current' : 'pending');
            ?>
                <li class="install-step-item is-<?php echo $state; ?>">
                    <span class="install-step-index"><?php echo $state === 'done' ? '✓' : $n; ?></span>
                    <span class="install-step-label">
                        <strong><?php echo e($meta['title']); ?></strong>
                        <em><?php echo e($meta['desc']); ?></em>
                    </span>
                </li>
            <?php endforeach; ?>
        </ol>
        <?php endif; ?>

        <main class="install-card">

            <?php if ($error !== ''): ?>
                <div class="inline-alert is-error"><strong>操作未通过</strong><span><?php echo e($error); ?></span></div>
            <?php endif; ?>

            <?php if ($step === 1): ?>
                <h1 class="install-title">合法使用承诺</h1>
                <p class="install-lead">感谢您使用<?php echo e(APP_NAME); ?>。请在安装前仔细阅读以下条款，勾选同意后方可继续。</p>
                <div style="max-height:420px;overflow-y:auto;padding:20px 24px;background:rgba(255,255,255,.03);border:1px solid rgba(255,255,255,.08);border-radius:16px;font-size:13px;line-height:2;color:#1e293b;margin-bottom:20px;">
                    <p>本系统旨在为用户提供高效、智能的网站批量生成与管理工具，助力正当、合法的网络内容建设。为遵守国家法律法规、维护互联网健康秩序及保障各方合法权益，请您在使用本系统前仔细阅读本声明。</p>
                    <h3 style="font-size:14px;color:#0f172a;margin:16px 0 8px;">一、绝对禁止的违法与违规用途</h3>
                    <p>您在使用本系统过程中，<strong style="color:#f87171;">严禁</strong>将本系统（包括但不限于其生成的任何网站、页面、内容、子域名、数据接口）用于或变相用于以下任何非法或违规活动：</p>
                    <p><strong style="color:#0f172a;">1. 赌博及博彩类</strong><br>包括但不限于：搭建、运营、推广、宣传任何形式的线上赌博网站、赌球平台、彩票预测或非法博彩系统，提供赌资支付结算、赌客招募、赌博攻略、赌博技巧教学、虚假博彩信息发布等。</p>
                    <p><strong style="color:#0f172a;">2. 色情与淫秽内容</strong><br>包括但不限于：制作、复制、发布、传播、链接或推广任何形式的色情、淫秽、低俗、性暗示、性挑逗内容；提供色情直播、色情交友、淫秽影片或图片下载；组织、诱导或参与涉黄交易、招嫖信息发布等。</p>
                    <p><strong style="color:#0f172a;">3. 黑产与违法犯罪活动</strong><br>包括但不限于：实施诈骗（如虚假投资、刷单返利、冒充公检法、杀猪盘、贷款诈骗等）；传播计算机病毒、恶意软件、勒索程序、木马、后门、钓鱼链接；非法获取、贩卖或泄露公民个人信息；组织、教唆或实施暴力、恐怖主义、极端主义、仇恨犯罪、人身攻击、诽谤、敲诈勒索；销售国家明令禁止的管制物品、武器、毒品、假币、假证、走私物品等；提供或诱导网络攻击（DDoS、CC攻击、端口扫描、入侵他人系统等）；非法外汇、洗钱、信用卡套现、虚拟货币违规交易等金融违法犯罪活动。</p>
                    <p><strong style="color:#0f172a;">4. 其他违反中国法律、行政法规及公序良俗的行为</strong><br>包括但不限于：侵犯他人知识产权（商标、专利、著作权、商业秘密）、发布虚假广告或传销信息、恶意抢注域名用于非法导流、散布谣言扰乱社会秩序、攻击或诋毁党和国家制度、煽动民族仇恨、破坏民族团结等。</p>
                    <h3 style="font-size:14px;color:#0f172a;margin:16px 0 8px;">二、违规后果与法律责任</h3>
                    <p><strong style="color:#0f172a;">1. 立即中止服务</strong><br>本系统运营方有权通过自动化检测或人工审核发现违规行为。一经确认，我们有权在不提前通知的情况下立即暂停或永久终止您的账号使用权，并删除您通过本系统生成的全部或部分违法站点及数据。</p>
                    <p><strong style="color:#0f172a;">2. 证据保留与上报</strong><br>对于涉嫌赌博、色情、黑产、诈骗等严重违法犯罪活动的，我们有权将您的注册信息、使用日志、IP地址、网站内容、操作记录等数据依法固定并移交公安机关、网信部门或相关监管机构，并积极配合调查取证。</p>
                    <p><strong style="color:#0f172a;">3. 追究违约及侵权责任</strong><br>您的违规行为若给本系统运营方或任何第三方造成损失（包括但不限于行政处罚、法律赔偿、商誉损害、技术处置成本等），您应承担全部赔偿责任。我们保留通过民事诉讼、刑事诉讼等一切法律途径追究您责任的权利。</p>
                    <h3 style="font-size:14px;color:#0f172a;margin:16px 0 8px;">三、用户承诺与审核义务</h3>
                    <p>1. 您承诺在注册及使用本系统前已阅读并完全理解本声明，并保证不会从事上述任何禁止性行为。</p>
                    <p>2. 您应自行对所生成网站的内容真实性、合法性承担全部审核责任。本系统作为技术工具，不对您的内容进行事前实质性审查，但事后有权进行合规检查。</p>
                    <p>3. 您应确保您的所有网站均已按照法律法规要求取得必要的许可证（如ICP备案、公安联网备案、特殊行业许可等）。</p>
                    <h3 style="font-size:14px;color:#0f172a;margin:16px 0 8px;">四、免责与最终解释</h3>
                    <p>1. 本声明中列举的禁止用途并非穷尽性列举，其他现行法律或未来法律规定的违法行为同样适用。</p>
                    <p>2. 本系统运营方保留随时修订、更新本声明的权利，修订后的声明将在系统内发布，继续使用则视为接受修订内容。</p>
                    <p>3. 若本声明的任何条款被有权机关认定为无效或不可执行，不影响其他条款的效力。</p>
                    <p style="margin-top:16px;font-weight:700;color:#dc2626;">再次提醒：科技向善，守法为本。请勿将本系统用于任何非法目的，否则您将独自承担全部法律后果。</p>
                    <p style="margin-top:12px;color:#64748b;"><?php echo e(APP_NAME); ?><br><?php echo date('Y.n.j'); ?></p>
                </div>
                <label style="display:flex;align-items:center;gap:10px;cursor:pointer;font-size:14px;color:#1e293b;padding:12px 0;user-select:none;">
                    <input type="checkbox" id="agreeTerms" style="width:18px;height:18px;accent-color:#6366f1;cursor:pointer;">
                    <span>我已阅读、理解并同意遵守上述《合法使用承诺》的全部条款</span>
                </label>
                <div class="install-actions" style="justify-content:flex-end;">
                    <a class="btn-primary is-disabled" id="agreeNextBtn" href="install.php?step=2" style="pointer-events:none;opacity:.4;">同意并进入安装向导 →</a>
                </div>
                <script>
                (function(){
                    var cb = document.getElementById('agreeTerms');
                    var btn = document.getElementById('agreeNextBtn');
                    cb.addEventListener('change', function(){
                        if (cb.checked) {
                            btn.style.pointerEvents = '';
                            btn.style.opacity = '1';
                            btn.classList.remove('is-disabled');
                        } else {
                            btn.style.pointerEvents = 'none';
                            btn.style.opacity = '.4';
                            btn.classList.add('is-disabled');
                        }
                    });
                })();
                </script>

            <?php elseif ($step === 2): ?>
                <h1 class="install-title">欢迎使用 <?php echo e(APP_NAME); ?></h1>
                <p class="install-lead">本向导将引导你完成首次部署。整个过程只需 1–2 分钟。</p>
                <ul class="install-feature-list">
                    <li><span>1</span><div><strong>检测运行环境</strong><p>确认 PHP 版本、扩展、目录权限满足要求。</p></div></li>
                    <li><span>2</span><div><strong>配置数据库</strong><p>填写数据库连接信息并在线测试。</p></div></li>
                    <li><span>3</span><div><strong>创建管理员</strong><p>设置首个后台超级管理员账号。</p></div></li>
                    <li><span>4</span><div><strong>初始化系统</strong><p>写入配置文件、建表并导入默认模板。</p></div></li>
                </ul>
                <div class="install-actions">
                    <a class="btn-primary" href="install.php?step=3">开始安装 →</a>
                </div>

            <?php elseif ($step === 3): ?>
                <h1 class="install-title">环境检测</h1>
                <p class="install-lead">所有项目通过后方可继续。红色项目请先修复服务器配置。</p>
                <div class="install-check-grid">
                    <?php foreach ($checks as $check): ?>
                        <div class="install-check-item is-<?php echo !empty($check['ok']) ? 'ok' : 'fail'; ?>">
                            <span class="install-check-dot"><?php echo !empty($check['ok']) ? '✓' : '×'; ?></span>
                            <div>
                                <strong><?php echo e($check['label']); ?></strong>
                                <p><?php echo e($check['message']); ?></p>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
                <div class="install-actions">
                    <a class="btn-ghost" href="install.php?step=2">← 上一步</a>
                    <?php if ($checksPass): ?>
                        <a class="btn-primary" href="install.php?step=4">下一步：数据库 →</a>
                    <?php else: ?>
                        <a class="btn-primary is-disabled" href="install.php?step=3">请先修复环境</a>
                    <?php endif; ?>
                </div>

            <?php elseif ($step === 4): ?>
                <h1 class="install-title">数据库配置</h1>
                <p class="install-lead">请先在服务器上创建好数据库，然后填写连接信息。向导将实时测试连接是否正常。</p>
                <form method="post" action="install.php?step=4" class="install-form">
                    <div class="install-form-grid">
                        <div class="input-group"><span>数据库主机</span><input class="input" type="text" name="db_host" value="<?php echo e($dbForm['db_host']); ?>" required></div>
                        <div class="input-group"><span>数据库端口</span><input class="input" type="text" name="db_port" value="<?php echo e($dbForm['db_port']); ?>" required></div>
                        <div class="input-group"><span>数据库名称</span><input class="input" type="text" name="db_name" value="<?php echo e($dbForm['db_name']); ?>" placeholder="例如 beeai" required></div>
                        <div class="input-group"><span>字符集</span><input class="input" type="text" name="db_charset" value="<?php echo e($dbForm['db_charset']); ?>"></div>
                        <div class="input-group"><span>数据库账号</span><input class="input" type="text" name="db_user" value="<?php echo e($dbForm['db_user']); ?>" required></div>
                        <div class="input-group"><span>数据库密码</span><input class="input" type="password" name="db_pass" value="<?php echo e($dbForm['db_pass']); ?>"></div>
                    </div>
                    <div class="install-actions">
                        <a class="btn-ghost" href="install.php?step=3">← 上一步</a>
                        <button class="btn-primary" type="submit">测试连接并下一步 →</button>
                    </div>
                </form>

            <?php elseif ($step === 5): ?>
                <h1 class="install-title">管理员账户</h1>
                <p class="install-lead">该账号将作为首个后台超级管理员，请妥善保存。</p>
                <form method="post" action="install.php?step=5" class="install-form">
                    <div class="install-form-grid">
                        <div class="input-group"><span>管理员账号</span><input class="input" type="text" name="admin_username" value="<?php echo e($adminForm['admin_username']); ?>" required></div>
                        <div class="input-group"><span>显示名称</span><input class="input" type="text" name="admin_name" value="<?php echo e($adminForm['admin_name']); ?>" required></div>
                        <div class="input-group"><span>登录密码</span><input class="input" type="password" name="admin_password" minlength="6" placeholder="至少 6 位" required></div>
                        <div class="input-group"><span>确认密码</span><input class="input" type="password" name="admin_password_confirm" minlength="6" required></div>
                    </div>
                    <div class="install-actions">
                        <a class="btn-ghost" href="install.php?step=4">← 上一步</a>
                        <button class="btn-primary" type="submit">下一步：开始安装 →</button>
                    </div>
                </form>

            <?php elseif ($step === 6): ?>
                <h1 class="install-title">正在安装</h1>
                <p class="install-lead">请勿关闭页面，安装过程会实时显示进度。</p>
                <div class="install-progress">
                    <div class="install-progress-bar"><i id="installBar" style="width:0%"></i></div>
                    <div class="install-progress-meta"><span id="installPercent">0%</span><span id="installCount">准备中…</span></div>
                </div>
                <ul id="installTaskList" class="install-task-list"></ul>
                <div class="install-actions" id="installActions" style="display:none;">
                    <a class="btn-primary" href="install.php?step=7">进入下一步 →</a>
                </div>
                <script>
                (function() {
                    var list = document.getElementById('installTaskList');
                    var bar = document.getElementById('installBar');
                    var pct = document.getElementById('installPercent');
                    var cnt = document.getElementById('installCount');
                    var actions = document.getElementById('installActions');
                    var total = 0, done = 0, items = {};

                    function render(task, state, message) {
                        var el = items[task.key];
                        if (!el) {
                            el = document.createElement('li');
                            el.className = 'install-task';
                            el.innerHTML = '<span class="install-task-dot"></span><div class="install-task-body"><strong></strong><em></em></div>';
                            el.querySelector('strong').textContent = task.label;
                            list.appendChild(el);
                            items[task.key] = el;
                        }
                        el.className = 'install-task is-' + state;
                        if (message) el.querySelector('em').textContent = message;
                    }

                    function updateBar() {
                        var p = total ? Math.round(done / total * 100) : 0;
                        bar.style.width = p + '%';
                        pct.textContent = p + '%';
                        cnt.textContent = done + ' / ' + total;
                    }

                    fetch('install.php?step=6&action=run', { credentials: 'same-origin' }).then(function(resp) {
                        var reader = resp.body.getReader();
                        var dec = new TextDecoder();
                        var buf = '';
                        function read() {
                            return reader.read().then(function(r) {
                                if (r.done) return;
                                buf += dec.decode(r.value, { stream: true });
                                var lines = buf.split('\n');
                                buf = lines.pop();
                                lines.forEach(function(line) {
                                    if (!line.trim()) return;
                                    var ev;
                                    try { ev = JSON.parse(line); } catch (e) { return; }
                                    handle(ev);
                                });
                                return read();
                            });
                        }
                        return read();
                    }).catch(function(err) {
                        cnt.textContent = '连接中断：' + err.message;
                    });

                    var taskMap = {};
                    function handle(ev) {
                        if (ev.status === 'start') {
                            total = ev.total;
                            (ev.tasks || []).forEach(function(t) {
                                taskMap[t.key] = t;
                                render(t, 'pending', '等待中');
                            });
                            updateBar();
                        } else if (ev.status === 'running') {
                            render(taskMap[ev.key] || { key: ev.key, label: ev.key }, 'running', '处理中…');
                        } else if (ev.status === 'done') {
                            render(taskMap[ev.key] || { key: ev.key, label: ev.key }, 'done', ev.message || '完成');
                            done++;
                            updateBar();
                        } else if (ev.status === 'error') {
                            cnt.textContent = '安装失败';
                            var warn = document.createElement('div');
                            warn.className = 'inline-alert is-error';
                            warn.innerHTML = '<strong>安装失败</strong><span></span>';
                            warn.querySelector('span').textContent = ev.message || '未知错误';
                            list.parentNode.insertBefore(warn, list);
                        } else if (ev.status === 'complete') {
                            bar.style.width = '100%';
                            pct.textContent = '100%';
                            cnt.textContent = '安装完成';
                            actions.style.display = '';
                            setTimeout(function() { location.href = ev.redirect || 'install.php?step=7'; }, 1200);
                        }
                    }
                })();
                </script>

            <?php elseif ($step === 7): ?>
                <h1 class="install-title">🎉 安装完成</h1>
                <p class="install-lead">系统已就绪。请使用刚才创建的管理员账号登录后台。</p>
                <div class="install-summary">
                    <div><span>管理员账号</span><strong><?php echo e(isset($data['admin_username']) ? $data['admin_username'] : 'admin'); ?></strong></div>
                    <div><span>显示名称</span><strong><?php echo e(isset($data['admin_name']) ? $data['admin_name'] : '-'); ?></strong></div>
                    <div><span>完成时间</span><strong><?php echo e(isset($data['completed_at']) ? $data['completed_at'] : date('Y-m-d H:i:s')); ?></strong></div>
                    <div><span>系统版本</span><strong>v<?php echo e(APP_VERSION); ?></strong></div>
                </div>
                <div class="install-tips">
                    <strong>接下来你可以：</strong>
                    <ol>
                        <li>登录后台后在 <em>AI 模型</em> 中配置至少一个模型</li>
                        <li>在 <em>域名管理</em> 添加第一个站点并绑定模板</li>
                        <li>进入 <em>一键建站</em> 创建首个建站任务</li>
                        <li>遇到问题可随时查看 <em>使用帮助</em></li>
                    </ol>
                </div>
                <div class="install-actions">
                    <a class="btn-primary" href="login.php">前往登录 →</a>
                </div>
                <?php $_SESSION['install_wizard'] = array(); ?>
            <?php endif; ?>

        </main>

        <footer class="install-foot">© <?php echo e(date('Y')); ?> <?php echo e(APP_NAME); ?> · <?php echo e(APP_DEVELOPER); ?></footer>
    </div>
</div>
</body>
</html>
