<?php
/**
 * 2026企业CMS - 一键安装脚本
 * 访问：https://www.yourdomain.com/install.php
 * 安装完成后请立即删除此文件！
 */

// 防止重复安装
if (file_exists(__DIR__ . '/config/database.php')) {
    $content = file_get_contents(__DIR__ . '/config/database.php');
    if (strpos($content, 'DB_NAME') !== false && filesize(__DIR__ . '/config/database.php') > 500) {
        die('系统已安装！如需重新安装，请先删除 config/database.php 中的数据库配置内容，然后重新访问此页面。');
    }
}

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

// 处理安装
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['do_install'])) {
    $dbHost   = trim($_POST['db_host'] ?? 'localhost');
    $dbPort   = trim($_POST['db_port'] ?? '3306');
    $dbName   = trim($_POST['db_name'] ?? 'cms2026');
    $dbUser   = trim($_POST['db_user'] ?? '');
    $dbPass   = $_POST['db_pass'] ?? '';
    $siteUrl  = trim($_POST['site_url'] ?? '');
    $adminUser = trim($_POST['admin_user'] ?? 'admin');
    $adminPass = $_POST['admin_pass'] ?? '';

    if (!$dbUser || !$dbPass || !$siteUrl || !$adminPass) {
        $error = '请填写所有必填项！';
    } else {
        try {
            // 测试数据库连接
            $dsn = "mysql:host={$dbHost};port={$dbPort};charset=utf8mb4";
            $pdo = new PDO($dsn, $dbUser, $dbPass, [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
            ]);

            // 创建数据库
            $pdo->exec("CREATE DATABASE IF NOT EXISTS `{$dbName}` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
            $pdo->exec("USE `{$dbName}`");

            // 导入SQL
            $sql = file_get_contents(__DIR__ . '/database/cms.sql');
            // 移除注释
            $sql = preg_replace('/--[^\n]*/m', '', $sql);
            $sql = preg_replace('/\/\*.*?\*\//s', '', $sql);
            $statements = explode(';', $sql);
            foreach ($statements as $stmt) {
                $stmt = trim($stmt);
                if ($stmt && strpos($stmt, 'CREATE DATABASE') === false && strpos($stmt, 'USE ') === false) {
                    try {
                        $pdo->exec($stmt);
                    } catch (Exception $e) {
                        // 忽略已存在的表等错误
                    }
                }
            }

            // 更新管理员密码
            $hash = password_hash($adminPass, PASSWORD_DEFAULT);
            $pdo->exec("UPDATE `admins` SET `password`='{$hash}' WHERE `id`=1");

            // 写入数据库配置
            $dbConfig = file_get_contents(__DIR__ . '/config/database.php');
            $dbConfig = preg_replace("/define\('DB_HOST'.*?\);/", "define('DB_HOST', '{$dbHost}');", $dbConfig);
            $dbConfig = preg_replace("/define\('DB_PORT'.*?\);/", "define('DB_PORT', '{$dbPort}');", $dbConfig);
            $dbConfig = preg_replace("/define\('DB_NAME'.*?\);/", "define('DB_NAME', '{$dbName}');", $dbConfig);
            $dbConfig = preg_replace("/define\('DB_USER'.*?\);/", "define('DB_USER', '{$dbUser}');", $dbConfig);
            $dbConfig = preg_replace("/define\('DB_PASS'.*?\);/", "define('DB_PASS', '{$dbPass}');", $dbConfig);
            file_put_contents(__DIR__ . '/config/database.php', $dbConfig);

            // 写入网站URL配置
            $configFile = __DIR__ . '/config/config.php';
            $config = file_get_contents($configFile);
            $config = preg_replace("/define\('SITE_URL'.*?\);/", "define('SITE_URL', '{$siteUrl}');", $config);
            file_put_contents($configFile, $config);

            $success = '安装成功！<br><br>';
            $success .= '管理员账号：<strong>' . htmlspecialchars($adminUser) . '</strong><br>';
            $success .= '管理员密码：<strong>' . htmlspecialchars($adminPass) . '</strong><br><br>';
            $success .= '<strong style="color:#e74c3c;">请立即删除 install.php 文件！</strong>';

        } 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>2026企业CMS - 安装向导</title>
    <style>
        * { margin:0; padding:0; box-sizing:border-box; }
        body { font-family:'Microsoft YaHei',Arial,sans-serif; background:#f0f2f5; display:flex; align-items:center; justify-content:center; min-height:100vh; }
        .install-box { width:600px; background:#fff; border-radius:8px; box-shadow:0 2px 20px rgba(0,0,0,0.1); padding:40px; }
        h1 { font-size:24px; color:#2c82e0; margin-bottom:10px; }
        .step { color:#999; margin-bottom:30px; }
        .form-group { margin-bottom:20px; }
        .form-group label { display:block; margin-bottom:8px; font-weight:bold; color:#333; }
        .form-group input { width:100%; padding:10px 15px; border:1px solid #ddd; border-radius:4px; font-size:14px; }
        .form-group input:focus { outline:none; border-color:#2c82e0; }
        .btn { display:block; width:100%; padding:12px; background:#2c82e0; color:#fff; border:none; border-radius:4px; font-size:16px; cursor:pointer; }
        .btn:hover { background:#1a6bc4; }
        .error { background:#f8d7da; color:#721c24; padding:12px; border-radius:4px; margin-bottom:20px; }
        .success { background:#d4edda; color:#155724; padding:20px; border-radius:4px; margin-bottom:20px; line-height:2; }
        .hint { color:#999; font-size:12px; margin-top:5px; }
        code { background:#f5f5f5; padding:2px 5px; border-radius:3px; font-size:12px; }
    </style>
</head>
<body>
    <div class="install-box">
        <h1>2026企业CMS</h1>
        <div class="step">安装向导 - 步骤 1/2</div>

        <?php if ($error): ?><div class="error"><?php echo $error; ?></div><?php endif; ?>
        <?php if ($success): ?>
        <div class="success"><?php echo $success; ?><br><br><a href="/admin/login.php" style="color:#2c82e0;font-weight:bold;font-size:16px;">点击这里进入后台 →</a></div>
        <?php exit; endif; ?>

        <form method="post" action="">
            <h3 style="margin-bottom:20px;font-size:16px;color:#333;">数据库配置</h3>

            <div class="form-group">
                <label>数据库主机</label>
                <input type="text" name="db_host" value="localhost" required>
                <div class="hint">通常是 localhost</div>
            </div>

            <div class="form-group">
                <label>数据库端口</label>
                <input type="text" name="db_port" value="3306" required>
            </div>

            <div class="form-group">
                <label>数据库名称</label>
                <input type="text" name="db_name" value="cms2026" required>
            </div>

            <div class="form-group">
                <label>数据库用户名</label>
                <input type="text" name="db_user" value="" required>
            </div>

            <div class="form-group">
                <label>数据库密码</label>
                <input type="password" name="db_pass" value="" required>
            </div>

            <hr style="margin:30px 0;border:none;border-top:1px solid #eee;">

            <h3 style="margin-bottom:20px;font-size:16px;color:#333;">网站配置</h3>

            <div class="form-group">
                <label>网站URL（务必修改为实际域名）</label>
                <input type="url" name="site_url" value="https://barju.cn" required>
                <div class="hint">如：https://www.yourdomain.com</div>
            </div>

            <hr style="margin:30px 0;border:none;border-top:1px solid #eee;">

            <h3 style="margin-bottom:20px;font-size:16px;color:#333;">管理员账号</h3>

            <div class="form-group">
                <label>管理员用户名</label>
                <input type="text" name="admin_user" value="admin" required>
            </div>

            <div class="form-group">
                <label>管理员密码</label>
                <input type="password" name="admin_pass" value="" required>
                <div class="hint">安装后请妥善保管此密码</div>
            </div>

            <button type="submit" name="do_install" class="btn">开始安装</button>
        </form>

        <div style="margin-top:20px;color:#999;font-size:12px;text-align:center;">
            © 2026 2026企业CMS | PHP + MySQL 企业内容管理系统
        </div>
    </div>
</body>
</html>
