<?php
/**
 * 芋头CMS（yutoucms）
 */

function installStep3BaseUrl()
{
    $https = (!empty($_SERVER['HTTPS']) && strtolower((string) $_SERVER['HTTPS']) !== 'off')
        || (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && strtolower((string) $_SERVER['HTTP_X_FORWARDED_PROTO']) === 'https')
        || ((string) ($_SERVER['SERVER_PORT'] ?? '') === '443');
    $scheme = $https ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
    $scriptDir = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '/install/index.php'));
    $basePath = trim(str_replace('/install', '', $scriptDir), '/');

    return $scheme . '://' . $host . ($basePath === '' ? '' : '/' . $basePath);
}

$error = '';
$success = false;
$isSnapshotInstall = !empty($_SESSION['install_import_snapshot']);
$siteName = '芋头CMS网站';
$siteUrl = installStep3BaseUrl() . '/';

if (file_exists(DATA_PATH . 'config.php')) {
    $config = require DATA_PATH . 'config.php';
    try {
        $dsn = sprintf(
            "mysql:host=%s;port=%s;dbname=%s;charset=%s",
            $config['host'],
            $config['port'],
            $config['database'],
            $config['charset']
        );
        $pdo = new PDO($dsn, $config['username'], $config['password']);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $currentSiteName = $pdo->query("SELECT config_value FROM `{$config['prefix']}config` WHERE config_key = 'site_name' LIMIT 1")->fetchColumn();
        $currentSiteUrl = $pdo->query("SELECT config_value FROM `{$config['prefix']}config` WHERE config_key = 'site_url' LIMIT 1")->fetchColumn();

        if ($currentSiteName) {
            $siteName = $currentSiteName;
        }
        if ($currentSiteUrl) {
            $siteUrl = $currentSiteUrl;
        }

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $siteName = trim($_POST['site_name'] ?? '');
            $siteUrl = trim($_POST['site_url'] ?? '');

            if ($siteName === '') {
                $error = '网站名称不能为空。';
            } elseif ($siteUrl === '') {
                $error = '网站地址不能为空。';
            } else {
                $stmt = $pdo->prepare("UPDATE `{$config['prefix']}config` SET config_value = ? WHERE config_key = 'site_name'");
                $stmt->execute([$siteName]);

                $stmt = $pdo->prepare("UPDATE `{$config['prefix']}config` SET config_value = ? WHERE config_key = 'site_url'");
                $stmt->execute([rtrim($siteUrl, '/') . '/']);

                $success = true;
            }
        }
    } catch (PDOException $e) {
        $error = '站点配置读取失败：' . $e->getMessage();
    }
} else {
    $error = '未找到数据库配置，请先完成上一步。';
}
?>
<div class="step-content">
    <div class="content-head">
        <h3>站点配置</h3>
        <p><?php echo $isSnapshotInstall ? '已导入测试快照，请确认站点名称和当前访问地址。' : '设置站点基础信息，安装完成后仍可在后台继续修改。'; ?></p>
    </div>

    <?php if ($isSnapshotInstall): ?>
    <div class="alert alert-warning">
        当前为示例数据恢复安装模式。系统已自动把本地测试地址切换为当前访问域名，建议再确认一次站点地址是否正确。
    </div>
    <?php endif; ?>

    <?php if ($error !== ''): ?>
    <div class="alert alert-error"><?php echo htmlspecialchars($error); ?></div>
    <?php endif; ?>

    <?php if ($success): ?>
    <div class="alert alert-success">站点配置已保存。</div>
    <div class="btn-box">
        <a href="?step=4" class="btn btn-primary">下一步</a>
    </div>
    <?php elseif ($error === '' || file_exists(DATA_PATH . 'config.php')): ?>
    <form method="post" class="form">
        <div class="form-group">
            <label>网站名称</label>
            <input type="text" name="site_name" value="<?php echo htmlspecialchars($siteName); ?>" required>
        </div>
        <div class="form-group">
            <label>网站地址</label>
            <input type="text" name="site_url" value="<?php echo htmlspecialchars(rtrim($siteUrl, '/')); ?>" required>
            <span class="hint">示例：https://www.example.com 或 https://www.example.com/subsite</span>
        </div>

        <div class="tip-box">
            <strong>说明</strong>
            <p>这里保存的是系统生成链接时使用的站点基础地址。若后续更换域名，可在后台重新修改。</p>
        </div>

        <div class="btn-box">
            <a href="?step=2" class="btn btn-default">上一步</a>
            <button type="submit" class="btn btn-primary">保存配置</button>
        </div>
    </form>
    <?php endif; ?>
</div>
