<?php
/**
 * 中文注释：用户资料编辑页（统一 uc 布局）。
 * 说明：
 * - 复用站点头部/底部与主样式，保证与个人中心一致；
 * - 严格校验登录态与字段存在性，不做兜底逻辑；
 * - 仅允许编辑手机号、微信号、QQ号三个字段；
 * - 模块化：使用 includes/Database.php 进行数据库读写。
 */

declare(strict_types=1);

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

require_once __DIR__ . '/includes/Database.php';

// 登录校验
$userId = isset($_SESSION['user_id']) ? (int)$_SESSION['user_id'] : 0;
if ($userId <= 0) {
    http_response_code(403);
    echo '<!DOCTYPE html><html lang="zh-CN"><head><meta charset="utf-8"><title>权限不足</title></head><body>';
    echo '<div style="max-width:800px;margin:80px auto;font-size:16px;line-height:1.8;">错误：未检测到登录用户，请先登录后访问资料编辑。</div>';
    echo '</body></html>';
    exit;
}

$db = Database::getInstance();
$pdo = $db->pdo();

// 检测 users 表是否存在需要的列（mobile/wechat/qq）
$cols = [];
try {
    $rows = $pdo->query('SHOW COLUMNS FROM users')->fetchAll(PDO::FETCH_ASSOC);
    foreach ($rows as $c) { $cols[strtolower((string)$c['Field'])] = true; }
} catch (Throwable $e) {}
foreach (['mobile','wechat','qq'] as $need) {
    if (!isset($cols[$need])) {
        http_response_code(500);
        echo '错误：users 表缺少必需列 ' . htmlspecialchars($need, ENT_QUOTES) . '，请先修复数据库结构。';
        exit;
    }
}

// 读取当前资料
$stmt = $pdo->prepare('SELECT id, username, mobile, wechat, qq FROM users WHERE id = ? LIMIT 1');
$stmt->execute([$userId]);
$profile = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$profile) {
    http_response_code(404);
    echo '错误：未找到当前用户的资料。';
    exit;
}

$saved = false;
$errorMsg = '';

// 处理提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 严格读取并去除首尾空格
    $mobile = isset($_POST['mobile']) ? trim((string)$_POST['mobile']) : '';
    $wechat = isset($_POST['wechat']) ? trim((string)$_POST['wechat']) : '';
    $qq = isset($_POST['qq']) ? trim((string)$_POST['qq']) : '';

    // 简单的格式校验（开发阶段暴露错误，不做兜底）
    if ($mobile !== '' && !preg_match('/^\d{6,20}$/', $mobile)) {
        $errorMsg = '手机号格式不正确，必须为6-20位数字。';
    } elseif ($qq !== '' && !preg_match('/^\d{5,20}$/', $qq)) {
        $errorMsg = 'QQ号格式不正确，必须为5-20位数字。';
    } else {
        try {
            $stmt2 = $pdo->prepare('UPDATE users SET mobile = :m, wechat = :w, qq = :q WHERE id = :id');
            $stmt2->execute([':m' => $mobile, ':w' => $wechat, ':q' => $qq, ':id' => $userId]);
            $saved = true;
            // 重新读取最新数据
            $stmt->execute([$userId]);
            $profile = $stmt->fetch(PDO::FETCH_ASSOC) ?: $profile;
        } catch (Throwable $e) {
            $errorMsg = '保存失败：' . htmlspecialchars($e->getMessage(), ENT_QUOTES);
        }
    }
}

?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <title>修改信息</title>
    <link href="/fontawesome/css/all.min.css" rel="stylesheet" />
    <link rel="stylesheet" href="/css/main.css" />
    <link rel="stylesheet" href="/css/header.css" />
    <link rel="stylesheet" href="/css/footer.css" />
    <script src="/libs/jquery-3.7.1.min.js"></script>
    <script src="/js/header.js"></script>
    <style>
        /* 中文注释：少量表单样式微调，复用主样式 */
        .form-row { margin-bottom: 12px; }
        .form-row label { display:block; font-size:13px; color:#666; margin-bottom:6px; }
        .form-row input { width:100%; height:36px; border:1px solid #ddd; border-radius:6px; padding:0 10px; }
        .form-actions { display:flex; gap:10px; }
    </style>
    </head>
<body>
<?php require_once __DIR__ . '/includes/site-header.php'; ?>
<main class="user-center">
    <div class="container uc-layout">
        <!-- 左侧导航 -->
        <?php require_once __DIR__ . '/includes/uc-nav.php'; ?>

        <!-- 右侧内容 -->
        <section class="uc-content">
            <h2 class="uc-title">修改信息</h2>
            <p style="color:#666; margin-top:-6px;">请填写真实联系方式，便于顾问与您联系并提供服务。</p>

            <?php if ($saved): ?>
                <div class="uc-card" style="margin-top:12px; border-color:#c6f6d5; background:#f0fff4;">
                    <div style="color:#2f855a; font-size:13px;">保存成功！</div>
                </div>
            <?php endif; ?>

            <?php if ($errorMsg !== ''): ?>
                <div class="uc-card" style="margin-top:12px; border-color:#fed7d7; background:#fff5f5;">
                    <div style="color:#c53030; font-size:13px;"><?php echo $errorMsg; ?></div>
                </div>
            <?php endif; ?>

            <div class="uc-card" style="margin-top:12px;">
                <h3 class="uc-card-title">账户信息</h3>
                <div class="uc-grid">
                    <div class="uc-field">
                        <span class="uc-label">账号名</span>
                        <span class="uc-value"><?php echo htmlspecialchars((string)$profile['username'], ENT_QUOTES); ?></span>
                    </div>
                </div>
            </div>

            <div class="uc-card" style="margin-top:16px;">
                <h3 class="uc-card-title">联系方式</h3>
                <form method="post" action="/user-profile-edit.php">
                    <div class="form-row">
                        <label for="mobile">手机号</label>
                        <input type="text" id="mobile" name="mobile" value="<?php echo htmlspecialchars((string)($profile['mobile'] ?? ''), ENT_QUOTES); ?>" autocomplete="off" />
                    </div>
                    <div class="form-row">
                        <label for="wechat">微信号</label>
                        <input type="text" id="wechat" name="wechat" value="<?php echo htmlspecialchars((string)($profile['wechat'] ?? ''), ENT_QUOTES); ?>" autocomplete="off" />
                    </div>
                    <div class="form-row">
                        <label for="qq">QQ号</label>
                        <input type="text" id="qq" name="qq" value="<?php echo htmlspecialchars((string)($profile['qq'] ?? ''), ENT_QUOTES); ?>" autocomplete="off" />
                    </div>
                    <div class="form-actions" style="margin-top:12px;">
                        <button type="submit" class="btn-primary">保存</button>
                        <a class="btn-secondary" href="/user-center.php">返回个人中心</a>
                    </div>
                </form>
            </div>
        </section>
    </div>
    </main>
<?php require_once __DIR__ . '/includes/site-footer.php'; ?>
</body>
</html>
