<?php
/**
 * 一键部署：填写数据库信息与管理员密码后自动建库建表、创建管理员
 * 部署成功后请立即删除本文件
 */
header('Content-Type: text/html; charset=utf-8');

$baseDir = __DIR__;
$configFile = $baseDir . '/auth/config.php';
$installSqlFile = $baseDir . '/auth/install.sql';

// 已安装检测：config 存在且能连上库且 admin_users 有表
$alreadyInstalled = false;
if (file_exists($configFile)) {
    $cfg = @include $configFile;
    if (is_array($cfg)) {
        try {
            $dsn = sprintf('mysql:host=%s;port=%s;dbname=%s;charset=%s',
                $cfg['db_host'], $cfg['db_port'], $cfg['db_name'], $cfg['db_charset'] ?? 'utf8mb4');
            $pdo = new PDO($dsn, $cfg['db_user'], $cfg['db_password'], [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
            $pdo->query("SELECT 1 FROM admin_users LIMIT 1");
            $alreadyInstalled = true;
        } catch (Exception $e) { /* 未安装或配置错误 */ }
    }
}

if ($alreadyInstalled) {
    echo '<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>已安装</title></head><body style="font-family:Microsoft YaHei,sans-serif;background:#1a1f3a;color:#e0e0e0;min-height:100vh;display:flex;align-items:center;justify-content:center;margin:0;">';
    echo '<div style="text-align:center;padding:40px;">';
    echo '<p style="color:#51cf66;font-size:18px;">系统已安装，请删除 <strong>install.php</strong> 以保证安全。</p>';
    echo '<p style="margin-top:24px;"><a href="admin/" style="color:#4a9eff;">进入管理后台</a></p>';
    echo '</div></body></html>';
    exit;
}

$error = '';
$success = false;
$authDir = $baseDir . DIRECTORY_SEPARATOR . 'auth';
$authWritable = is_dir($authDir) && is_writable($authDir);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $host = trim($_POST['db_host'] ?? '127.0.0.1');
    $port = (int) ($_POST['db_port'] ?? 3306);
    $dbname = trim($_POST['db_name'] ?? 'auth_system');
    $rootUser = trim($_POST['db_root_user'] ?? '');
    $rootPass = (string) ($_POST['db_root_password'] ?? '');
    $dbuser = trim($_POST['db_user'] ?? '');
    $dbpass = (string) ($_POST['db_password'] ?? '');
    $adminPass = (string) ($_POST['admin_password'] ?? '123456');
    $sessionName = trim($_POST['session_name'] ?? 'AUTH_SESS');
    $resetKey = trim($_POST['reset_admin_key'] ?? '123456');

    if ($rootUser === '') {
        $error = '请填写 MySQL 管理员账号（如 root）';
    } elseif ($dbuser === '') {
        $error = '请填写要创建的数据库用户名';
    } elseif (strlen($adminPass) < 4) {
        $error = '管理员密码至少 4 位';
    } elseif (!file_exists($installSqlFile)) {
        $error = '未找到 auth/install.sql，请确认项目文件完整';
    } elseif (!$authWritable) {
        $error = 'auth 目录不可写，无法创建 config.php。请将 auth 目录设为可写后再试（见下方说明）。';
    } else {
        try {
            // 1. 使用 root/管理员账号连接 MySQL（不选库）
            $dsnNoDb = sprintf('mysql:host=%s;port=%s;charset=utf8mb4', $host, $port);
            $pdo = new PDO($dsnNoDb, $rootUser, $rootPass, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);

            // 2. 创建数据库（若不存在）
            $dbnameEsc = '`' . str_replace('`', '``', $dbname) . '`';
            $pdo->exec("CREATE DATABASE IF NOT EXISTS $dbnameEsc DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");

            // 3. 创建数据库用户并授权（避免 ALTER USER 报“用户不存在”）
            $userEsc = "'" . str_replace(["'", "\\"], ["''", "\\\\"], $dbuser) . "'@'localhost'";
            $passQuoted = $pdo->quote($dbpass);
            try {
                $pdo->exec("CREATE USER IF NOT EXISTS $userEsc IDENTIFIED BY $passQuoted");
            } catch (PDOException $e) {
                if ($e->getCode() == '42000' || strpos($e->getMessage(), '1396') !== false || strpos($e->getMessage(), 'already exists') !== false) {
                    $pdo->exec("ALTER USER $userEsc IDENTIFIED BY $passQuoted");
                } else {
                    throw $e;
                }
            }
            $pdo->exec("GRANT ALL PRIVILEGES ON $dbnameEsc.* TO $userEsc");
            $pdo->exec("FLUSH PRIVILEGES");

            // 4. 切换到目标库并执行 install.sql
            $pdo->exec("USE $dbnameEsc");
            $sql = file_get_contents($installSqlFile);
            $sql = str_replace('`auth_system`', $dbnameEsc, $sql);
            $sql = preg_replace('/--[^\n]*/s', '', $sql);
            $statements = array_filter(array_map('trim', explode(';', $sql)));
            foreach ($statements as $stmt) {
                if ($stmt === '') continue;
                $pdo->exec($stmt);
            }

            // 5. 创建管理员
            $hash = password_hash($adminPass, PASSWORD_DEFAULT);
            $pdo->prepare('INSERT INTO admin_users (username, password) VALUES (?, ?) ON DUPLICATE KEY UPDATE password = VALUES(password)')
                ->execute(['admin', $hash]);

            // 6. 写入 config.php（使用刚创建的数据库用户，供程序日常使用）
            $configContent = '<?php
/**
 * 网页验证系统 - 数据库配置（一键安装生成）
 */
return [
    \'db_host\'     => ' . var_export($host, true) . ',
    \'db_port\'     => ' . $port . ',
    \'db_name\'     => ' . var_export($dbname, true) . ',
    \'db_user\'     => ' . var_export($dbuser, true) . ',
    \'db_password\' => ' . var_export($dbpass, true) . ',
    \'db_charset\'  => \'utf8mb4\',
    \'session_name\' => ' . var_export($sessionName, true) . ',
    \'reset_admin_key\' => ' . var_export($resetKey, true) . ',
];
';
            if (file_put_contents($configFile, $configContent) === false) {
                $permHint = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN')
                    ? '（Windows：请给 auth 文件夹赋予“写入”权限，或右键 auth → 属性 → 安全 → 编辑）'
                    : '（Linux/宝塔：在站点目录执行 chmod 755 auth 或 chmod 775 auth）';
                throw new Exception('无法写入 auth/config.php，请检查目录权限。' . $permHint);
            }

            $success = true;
        } catch (PDOException $e) {
            $msg = $e->getMessage();
            if (strpos($msg, '1045') !== false || stripos($msg, 'Access denied') !== false) {
                $error = 'MySQL 管理员账号连接被拒绝（请检查 root 用户名与密码）。';
            } else {
                $error = '数据库执行失败：' . $msg;
            }
        } catch (Exception $e) {
            $error = $e->getMessage();
        }
    }
}

if ($success) {
    echo '<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>安装成功</title></head><body style="font-family:Microsoft YaHei,sans-serif;background:linear-gradient(135deg,#1a1f3a 0%,#0a0e27 100%);color:#e0e0e0;min-height:100vh;display:flex;align-items:center;justify-content:center;margin:0;">';
    echo '<div style="background:rgba(47,54,60,0.95);border:1px solid rgba(74,158,255,0.3);border-radius:16px;padding:40px;max-width:420px;width:100%;">';
    echo '<h1 style="color:#51cf66;font-size:22px;text-align:center;margin-bottom:20px;">安装成功</h1>';
    echo '<p style="margin-bottom:12px;">数据库与表已创建，管理员账号已就绪。</p>';
    echo '<p style="margin-bottom:8px;"><strong>用户名：</strong> admin</p>';
    echo '<p style="margin-bottom:20px;"><strong>密码：</strong> 您刚才设置的密码</p>';
    echo '<p style="color:#ff922b;font-size:14px;margin-bottom:24px;">请立即删除 <strong>install.php</strong> 以保证安全。</p>';
    echo '<p style="text-align:center;"><a href="admin/" style="display:inline-block;padding:12px 24px;background:linear-gradient(135deg,#4a9eff,#258DF2);color:#fff;text-decoration:none;border-radius:8px;">进入管理后台</a></p>';
    echo '</div></body></html>';
    exit;
}

// 读取现有 config 用于预填
$prefill = [
    'db_host' => '127.0.0.1',
    'db_port' => 3306,
    'db_name' => 'auth_system',
    'db_root_user' => 'root',
    'db_root_password' => '',
    'db_user' => 'auth_system',
    'db_password' => '',
    'admin_password' => '123456',
    'session_name' => 'AUTH_SESS',
    'reset_admin_key' => '123456',
];
if (file_exists($configFile)) {
    $c = @include $configFile;
    if (is_array($c)) {
        $prefill['db_host'] = $c['db_host'] ?? $prefill['db_host'];
        $prefill['db_port'] = $c['db_port'] ?? $prefill['db_port'];
        $prefill['db_name'] = $c['db_name'] ?? $prefill['db_name'];
        $prefill['db_user'] = $c['db_user'] ?? $prefill['db_user'];
        $prefill['db_password'] = $c['db_password'] ?? '';
        $prefill['session_name'] = $c['session_name'] ?? $prefill['session_name'];
        $prefill['reset_admin_key'] = $c['reset_admin_key'] ?? $prefill['reset_admin_key'];
    }
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>一键部署 - 验证系统</title>
    <style>
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body { font-family: "Microsoft YaHei", sans-serif; background: linear-gradient(135deg, #1a1f3a 0%, #0a0e27 100%); min-height: 100vh; color: #e0e0e0; padding: 20px; display: flex; align-items: center; justify-content: center; }
        .box { background: rgba(47,54,60,0.95); border: 1px solid rgba(74,158,255,0.3); border-radius: 16px; padding: 40px; max-width: 480px; width: 100%; }
        h1 { font-size: 22px; color: #4a9eff; text-align: center; margin-bottom: 24px; }
        .form-group { margin-bottom: 16px; }
        label { display: block; margin-bottom: 6px; font-size: 14px; color: #aaa; }
        input { width: 100%; padding: 10px 12px; border: 1px solid rgba(74,158,255,0.3); border-radius: 8px; background: rgba(26,31,36,0.8); color: #fff; font-size: 14px; }
        input:focus { outline: none; border-color: #4a9eff; }
        .row2 { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
        .btn { width: 100%; padding: 12px; border: none; border-radius: 8px; background: linear-gradient(135deg, #4a9eff 0%, #258DF2 100%); color: #fff; font-size: 15px; cursor: pointer; margin-top: 8px; }
        .btn:hover { opacity: 0.9; }
        .msg { margin-top: 12px; font-size: 14px; text-align: center; }
        .msg.err { color: #ff6b6b; }
        .hint { font-size: 12px; color: #666; margin-top: 20px; }
    </style>
</head>
<body>
    <div class="box">
        <h1>一键部署</h1>
        <p style="font-size:14px;color:#888;margin-bottom:20px;">使用 MySQL 管理员账号连接，将自动创建数据库、数据库用户、建表并创建后台管理员。无需登录 phpMyAdmin。</p>
        <?php if (!$authWritable): ?>
        <div style="background:rgba(255,193,7,0.15);border:1px solid rgba(255,193,7,0.5);border-radius:8px;padding:12px 16px;margin-bottom:16px;font-size:13px;">
            <strong>auth 目录当前不可写</strong>，安装时需要在此目录创建 config.php。请先设置权限后再点「执行安装」：<br>
            <strong>Linux / 宝塔：</strong>在项目根目录执行 <code style="background:#1a1f3a;padding:2px 6px;">chmod 755 auth</code> 或 <code style="background:#1a1f3a;padding:2px 6px;">chmod 775 auth</code><br>
            <strong>Windows：</strong>右键 <code>auth</code> 文件夹 → 属性 → 安全 → 编辑 → 为当前用户勾选「写入」
        </div>
        <?php endif; ?>
        <?php if ($error !== ''): ?><p class="msg err"><?php echo htmlspecialchars($error); ?></p><?php endif; ?>
        <form method="post">
            <div class="form-group">
                <label>数据库主机</label>
                <input type="text" name="db_host" value="<?php echo htmlspecialchars($prefill['db_host']); ?>" placeholder="127.0.0.1">
            </div>
            <div class="row2">
                <div class="form-group">
                    <label>端口</label>
                    <input type="number" name="db_port" value="<?php echo (int)$prefill['db_port']; ?>">
                </div>
                <div class="form-group">
                    <label>数据库名</label>
                    <input type="text" name="db_name" value="<?php echo htmlspecialchars($prefill['db_name']); ?>" placeholder="auth_system">
                </div>
            </div>
            <div class="form-group">
                <label>MySQL 管理员账号（如 root）</label>
                <input type="text" name="db_root_user" value="<?php echo htmlspecialchars($prefill['db_root_user']); ?>" placeholder="root" autocomplete="username">
            </div>
            <div class="form-group">
                <label>MySQL 管理员密码</label>
                <input type="password" name="db_root_password" value="<?php echo htmlspecialchars($prefill['db_root_password']); ?>" placeholder="root 的密码" autocomplete="current-password">
            </div>
            <div class="form-group">
                <label>要创建的数据库用户名</label>
                <input type="text" name="db_user" value="<?php echo htmlspecialchars($prefill['db_user']); ?>" placeholder="如 auth_system">
            </div>
            <div class="form-group">
                <label>要创建的数据库密码</label>
                <input type="password" name="db_password" value="<?php echo htmlspecialchars($prefill['db_password']); ?>" placeholder="为该用户设置的密码" autocomplete="new-password">
            </div>
            <div class="form-group">
                <label>管理员初始密码（至少 4 位）</label>
                <input type="password" name="admin_password" value="<?php echo htmlspecialchars($prefill['admin_password']); ?>" placeholder="默认 123456" minlength="4">
            </div>
            <div class="row2">
                <div class="form-group">
                    <label>Session 名称</label>
                    <input type="text" name="session_name" value="<?php echo htmlspecialchars($prefill['session_name']); ?>">
                </div>
                <div class="form-group">
                    <label>重置密码密钥</label>
                    <input type="text" name="reset_admin_key" value="<?php echo htmlspecialchars($prefill['reset_admin_key']); ?>">
                </div>
            </div>
            <button type="submit" class="btn">执行安装</button>
        </form>
        <p class="hint">安装将用管理员账号创建数据库、自动创建数据库用户并授权，然后建表及后台管理员。安装成功后请删除本文件 install.php。</p>
    </div>
</body>
</html>
