<?php
/**
 * 用户主页
 */
$uid = (int) input('id');
$user = user_by_id($uid);
$me = current_user();
$adminCanViewBanned = $me && is_admin($me) && $user;
if (!$user || ((int) $user['status'] !== 1 && !$adminCanViewBanned)) {
    $GLOBALS['PAGE'] = 'user';
    render_header('用户不存在');
    empty_state('没有找到这位茶客', '也许他已离开茶室');
    render_footer();
    return;
}
$isOfficialTarget = is_official_account($user);
$isSelfProfile = $me && (int) $me['id'] === (int) $user['id'];
$visitorCount = (int) ($user['profile_visitor_count'] ?? 0);
// 只有登录用户访问他人主页才计入访客量；本人的访问和后台操作不回写。
if ($_SERVER['REQUEST_METHOD'] !== 'POST' && $me && !$isSelfProfile && (int) $user['status'] === 1) {
    if (profile_visit_record((int) $user['id'], (int) $me['id'])) {
        $visitorCount = profile_visitor_count_value((int) $user['id']);
    }
}

// 官方通知账号只用于系统通知，不开放关注、拉黑、好友、私信和转账等个人互动。
if ($isOfficialTarget && $_SERVER['REQUEST_METHOD'] === 'POST' && in_array(input('act'), ['follow', 'block', 'add_friend', 'accept_friend_request', 'save_friend_remark', 'transfer_to'], true)) {
    require_login();
    check_csrf();
    flash('官方通知账号仅用于系统通知，不支持该操作', 'err');
    redirect(page_url('user', ['id' => $uid]));
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && input('act') === 'checkin') {
    require_login();
    check_csrf();
    if ((int) $me['id'] !== (int) $uid) {
        flash('只能在自己的个人主页签到', 'err');
    } else {
        feature_guard('checkin');
        list($ok, $msg) = perform_checkin($me);
        flash($msg, $ok ? 'ok' : 'err');
    }
    redirect(page_url('user', ['id' => $uid]));
}

$userOnline = online_is_online((int) $user['id']);
$level = level_of((int) ($user['exp'] ?? $user['points']));
$canSeeAuthorOnly = $me ? post_privileged_can_view(['user_id' => $uid], $me) : false;
$authorOnlyWhere = $canSeeAuthorOnly ? '1=1' : 'author_only = 0';
$postCount = DB::count('posts', "user_id = ? AND status = 1 AND $authorOnlyWhere", [$uid]);
$commentCount = DB::count('comments', 'user_id = ?', [$uid]);
$likeReceived = (int) DB::val('SELECT COUNT(*) FROM ' . DB::table('likes') . ' l
                               LEFT JOIN ' . DB::table('posts') . ' p ON p.id = l.post_id
                               WHERE p.user_id = ?', [$uid], 0);
$posts = DB::all('SELECT p.*, c.name AS cat_name FROM ' . DB::table('posts') . ' p
                  LEFT JOIN ' . DB::table('categories') . ' c ON c.id = p.cat_id
                  WHERE p.user_id = ? AND p.status = 1 AND ' . ($canSeeAuthorOnly ? '1=1' : 'p.author_only = 0') . ' ORDER BY p.id DESC LIMIT 20', [$uid]);
$momentCount = DB::count('moments', 'user_id = ? AND status = 1', [$uid]);
$userCheckedToday = (string) ($user['last_checkin'] ?? '') === date('Y-m-d');
$userStreak = (int) ($user['streak'] ?? 0);
$isFriend = $me && friend_is($me['id'], $uid);
$targetRejectsStranger = !$isFriend && (int) ($user['friend_reject_stranger_messages'] ?? 0) === 1;
$friendRemarkOf = $isFriend ? friend_remark_of($me['id'], $uid) : '';
$rawDisplayName = $user['nickname'] !== '' ? $user['nickname'] : username_visible($user);
$outgoingReq = $me ? friend_request_status($me['id'], $uid) : '';
$incomingReq = $me ? friend_request_status($uid, $me['id']) : '';
$view = input('view') === 'comments' ? 'comments' : 'posts';
$commentPosts = DB::all('SELECT p.*, c.id AS comment_id, c.content AS comment_content, c.created_at AS comment_at
                         FROM ' . DB::table('comments') . ' c
                         INNER JOIN ' . DB::table('posts') . ' p ON p.id = c.post_id
                         WHERE c.user_id = ? AND c.status = 1 AND p.status = 1 AND ' . ($canSeeAuthorOnly ? '1=1' : 'p.author_only = 0') . '
                         ORDER BY c.id DESC LIMIT 20', [$uid]);

if ($_SERVER['REQUEST_METHOD'] === 'POST' && input('act') === 'add_friend') {
    check_csrf();
    if (!$me) {
        redirect(page_url('login', ['next' => page_url('user', ['id' => $uid])]));
    }
    $result = friend_request_send($me['id'], $uid);
    flash($result['msg'], $result['ok'] ? '' : 'err');
    redirect(page_url('user', ['id' => $uid]));
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && input('act') === 'accept_friend_request') {
    check_csrf();
    if (!$me) {
        redirect(page_url('login', ['next' => page_url('user', ['id' => $uid])]));
    }
    $req = friend_request_get($uid, $me['id']);
    if ($req && friend_request_accept((int) $req['id'], $me['id'])) {
        flash('已同意好友申请');
    } else {
        flash('好友申请不存在或已处理', 'err');
    }
    redirect(page_url('user', ['id' => $uid]));
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && input('act') === 'save_friend_remark') {
    check_csrf();
    if (!$me) {
        redirect(page_url('login', ['next' => page_url('user', ['id' => $uid])]));
    }
    if (!friend_is($me['id'], $uid)) {
        flash('请先添加好友', 'err');
    } else {
        friend_set_remark($me['id'], $uid, (string) ($_POST['remark'] ?? ''));
        flash('好友备注已保存');
    }
    redirect(page_url('user', ['id' => $uid]));
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && input('act') === 'transfer_to') {
    check_csrf();
    if (!$me) {
        redirect(page_url('login', ['next' => page_url('user', ['id' => $uid])]));
    }
    $amount = (int) ($_POST['amount'] ?? 0);
    $note = trim((string) ($_POST['note'] ?? ''));
    try {
        transfer_points($me['id'], $uid, $amount, $note);
        flash('已向 ' . display_name($user) . ' 转账 ' . $amount . ' 积分');
    } catch (Exception $e) {
        flash('转账失败：' . $e->getMessage(), 'err');
    }
    redirect(page_url('user', ['id' => $uid]));
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && input('act') === 'report_user') {
    require_login();
    check_csrf();
    if ((int) $me['id'] === (int) $uid) {
        flash('不能举报自己', 'err');
        redirect(page_url('user', ['id' => $uid]));
    }
    $reason = mb_substr(trim((string) ($_POST['reason'] ?? '')), 0, 255);
    if ($reason === '' || mb_strlen($reason) < 2) {
        flash('请填写举报理由（至少 2 个字）', 'err');
        redirect(page_url('user', ['id' => $uid]) . '#report');
    }
    $recent = DB::val('SELECT COUNT(*) FROM ' . DB::table('reports') . " WHERE target_type = 'user' AND target_id = ? AND user_id = ? AND created_at >= ?", [$uid, (int) $me['id'], date('Y-m-d H:i:s', time() - 3600)], 0);
    if ((int) $recent > 0) {
        flash('你刚举报过这位用户，请等待管理员处理，不要重复提交', 'err');
        redirect(page_url('user', ['id' => $uid]));
    }
    DB::insert('reports', [
        'target_type' => 'user',
        'target_id' => $uid,
        'user_id' => (int) $me['id'],
        'reason' => $reason,
        'status' => 0,
        'created_at' => now(),
    ]);
    notify_admins_report((int) $me['id'], 'user', $uid, $reason, display_name($user));
    notify((int) $me['id'], 0, 'report_result', (int) $uid, '你的举报已提交，管理员处理后会在这里回信。');
    flash('举报已提交，管理员处理后会通过通知中心回信');
    redirect(page_url('user', ['id' => $uid]));
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && in_array(input('act'), ['admin_mute', 'admin_unmute', 'admin_ban', 'admin_unban', 'admin_delete_user'], true)) {
    require_login();
    check_csrf();
    if (!is_admin($me)) {
        flash('只有管理员或超级管理员可以执行该操作', 'err');
        redirect(page_url('user', ['id' => $uid]));
    }
    $act = input('act');
    if ((int) $me['id'] === (int) $uid) {
        flash('不能对自己执行该操作', 'err');
        redirect(page_url('user', ['id' => $uid]));
    }
    if (!admin_can_delete_owner($user)) {
        flash('管理员不能操作超级管理员或其他管理员账号', 'err');
        redirect(page_url('user', ['id' => $uid]));
    }
    $days = max(0, (int) input('days', 0));
    if ($act === 'admin_mute') {
        $until = $days > 0 ? date('Y-m-d H:i:s', time() + $days * 86400) : '9999-12-31 23:59:59';
        $reason = mb_substr(trim((string) input('reason', '')), 0, 255);
        DB::run('UPDATE ' . DB::table('users') . ' SET site_mute_until = ?, site_mute_reason = ? WHERE id = ?', [$until, $reason, $uid]);
        notify($uid, (int) $me['id'], 'admin_action', (int) $me['id'],
            '你已被管理员禁言' . ($days > 0 ? ' ' . $days . ' 天' : '（永久）') . ($reason !== '' ? '，原因：' . $reason : ''));
        audit_log('site_mute', 'UID ' . $uid . ' 至 ' . $until . ' 操作者 ' . $me['username']);
        flash($days > 0 ? '已禁言该用户 ' . $days . ' 天' : '已永久禁言该用户');
    } elseif ($act === 'admin_unmute') {
        DB::run('UPDATE ' . DB::table('users') . ' SET site_mute_until = ?, site_mute_reason = ? WHERE id = ?', ['', '', $uid]);
        notify($uid, (int) $me['id'], 'admin_action', (int) $me['id'], '管理员已解除对你的禁言');
        flash('已解除该用户的禁言');
    } elseif ($act === 'admin_ban') {
        $until = $days > 0 ? date('Y-m-d H:i:s', time() + $days * 86400) : '9999-12-31 23:59:59';
        $reason = mb_substr(trim((string) input('reason', '')), 0, 255);
        if ($days <= 0) {
            list($codeOk, $codeMsg) = account_delete_code_check($me, input('ban_email_code'), 'admin_ban_account');
            if (!$codeOk) {
                flash('永久封禁需要验证当前管理员绑定邮箱：' . $codeMsg, 'err');
                redirect(page_url('user', ['id' => $uid]) . '#pcAdminOps');
            }
        }
        DB::run('UPDATE ' . DB::table('users') . ' SET status = 0, ban_until = ?, mute_until = ? WHERE id = ?', [$until, '', $uid]);
        punishment_record($uid, 'ban', $reason, now(), $until, (int) $me['id']);
        notify($uid, (int) $me['id'], 'admin_action', (int) $me['id'],
            '你的账号已被管理员封禁' . ($days > 0 ? ' ' . $days . ' 天' : '（永久）') . ($reason !== '' ? '，原因：' . $reason : ''));
        audit_log('user_ban', 'UID ' . $uid . ' 至 ' . $until . ' 操作者 ' . $me['username']);
        if ($days <= 0) {
            $guardParts = account_ban_link_guard($uid, $reason, (int) $me['id'], $user);
            flash('已永久封禁该用户' . ($guardParts ? '，并同步封禁：' . implode('、', $guardParts) : '；暂无可联动的 IP / 设备记录'));
        } else {
            flash('已封禁该用户 ' . $days . ' 天');
        }
    } elseif ($act === 'admin_unban') {
        DB::run('UPDATE ' . DB::table('users') . ' SET status = 1, ban_until = ? WHERE id = ?', ['', $uid]);
        punishment_mark_released($uid, 'ban');
        $guardReleased = guard_ban_release_account($uid);
        notify($uid, (int) $me['id'], 'admin_action', (int) $me['id'], '你的账号已解除封禁');
        audit_log('user_unban', 'UID ' . $uid . ' 自动解除 IP/设备封禁 ' . (int) $guardReleased['total'] . ' 项 操作者 ' . $me['username']);
        flash('已解除该用户的封禁' . ((int) $guardReleased['total'] > 0 ? '，并自动解除关联 IP/设备封禁 ' . (int) $guardReleased['total'] . ' 项' : ''));
    } elseif ($act === 'admin_delete_user') {
        list($codeOk, $codeMsg) = account_delete_code_check($me, input('delete_email_code'), 'admin_delete_account');
        if (!$codeOk) {
            flash($codeMsg, 'err');
            redirect(page_url('user', ['id' => $uid]) . '#pcAdminOps');
        }
        user_delete_account($uid, (int) $me['id']);
        audit_log('user_delete', 'UID ' . $uid . ' 操作者 ' . $me['username']);
        flash('该用户账号及其内容已删除，资料已进入「被删除账号恢复」存档');
        redirect(page_url('admin', ['s' => 'users']));
    }
    redirect(page_url('user', ['id' => $uid]));
}

$GLOBALS['PAGE'] = 'user';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && input('act') === 'block') {
    require_login();
    check_csrf();
    if ((int) $me['id'] === $uid) { flash('不能拉黑自己', 'err'); }
    else {
        $blocked = users_blocked_between((int) $me['id'], $uid);
        if ($blocked) { DB::delete('blocked_users', 'blocker_id = ? AND blocked_id = ?', [(int) $me['id'], $uid]); flash('已取消拉黑'); }
        else { DB::insert('blocked_users', ['blocker_id' => (int) $me['id'], 'blocked_id' => $uid, 'created_at' => now()]); audit_log('user_block', 'UID ' . $uid); flash('已拉黑，双方不再互相显示帖子与评论'); }
    }
    redirect(page_url('user', ['id' => $uid]));
}
$blockedBetween = $me ? users_blocked_between((int) $me['id'], $uid) : false;
$uBg = trim((string) ($user['profile_bg'] ?? ''));
$uVideo = trim((string) ($user['profile_bg_video'] ?? ''));
$uHasBg = $uBg !== '' || $uVideo !== '';
$uBlur = max(0, min(20, (int) ($user['profile_bg_blur'] ?? 0)));
$uFrame = profile_frame_of($user);
render_header(display_name($user));
?>
<section class="pc-card<?= $uHasBg ? ' has-bg' : '' ?><?= $uFrame !== '' ? ' has-frame' : '' ?>" id="pcCard">
  <?= profile_visitor_stat_html($user, $isSelfProfile, $visitorCount) ?>
  <?= profile_frame_html($uFrame) ?>
  <?php if ($uHasBg): ?>
    <div class="pc-bg" style="<?= $uBg !== '' && $uVideo === '' ? 'background-image:url(\'' . e(upload_url($uBg)) . '\');' : '' ?>filter:blur(<?= (int) $uBlur ?>px)">
      <?php if ($uVideo !== ''): ?>
        <video class="pc-bg-video" id="pcBgVideo" src="<?= e(upload_url($uVideo)) ?>" autoplay muted loop playsinline preload="auto" data-card-bg-video></video>
      <?php endif; ?>
    </div>
  <?php endif; ?>
  <?php if ($uVideo !== ''): ?>
    <button class="pc-bg-sound" id="pcBgSound" type="button" title="开启背景声音" aria-label="开启背景声音">🔕</button>
  <?php endif; ?>
  <?php if ((int) $user['status'] !== 1): ?>
    <div class="banned-user-banner">该账号当前处于封禁状态<?= trim((string) ($user['ban_until'] ?? '')) !== '' && strtotime($user['ban_until']) < strtotime('9999-01-01') ? '，至 ' . e($user['ban_until']) : '（永久）' ?>。管理员可在下方解除封禁。</div>
  <?php endif; ?>
  <div class="pc-avatar-wrap">
    <?= avatar_html($user, 'pc-avatar') ?>
    <?php if ((int) $user['verified'] === 1): ?><span class="avatar-v v-<?= verify_style_of($user) ?>">V</span><?php endif; ?>
  </div>
  <div class="pc-main">
    <h1 class="pc-name"><?= e(display_name($user)) ?><?= verify_badge($user) ?></h1>
    <?php $visibleUsername = username_visible($user); ?>
    <p class="pc-user"><button type="button" class="pc-username" data-copy="<?= $visibleUsername === '已隐藏' ? '' : e($visibleUsername) ?>" title="<?= $visibleUsername === '已隐藏' ? '用户名已隐藏' : '点击复制用户名' ?>"><?= e($visibleUsername) ?></button><span class="pc-uid">ID <?= (int) $user['id'] ?></span></p>
    <div class="pc-tags">
      <span class="pc-tag"><?= e(gender_text($user['gender'])) ?></span>
      <?php if ($user['role'] !== 'user'): ?><span class="pc-tag gold"><?= e(role_label($user['role'])) ?></span><?php endif; ?>
      <span class="pc-tag">Lv.<?= (int) $level['level'] ?> <?= e($level['name']) ?></span>
    </div>
    <p class="pu-profile-presence <?= $userOnline ? 'on' : 'off' ?>"><i></i><?= $userOnline ? '实时在线' : '当前离线' ?></p>
    <?php if ($friendRemarkOf !== ''): ?>
    <p class="pc-remark"><span class="pc-remark-label">备注名</span><strong><?= e($friendRemarkOf) ?></strong><span class="pc-remark-origin">原名：<?= e($rawDisplayName) ?></span></p>
    <?php endif; ?>
    <p class="pc-meta">注册时间 <strong><?= e(substr($user['created_at'], 0, 16)) ?></strong></p>
    <?php $isOfficialProfile = is_official_account($user); ?>
    <?php if (!$isOfficialProfile): ?>
    <div class="pc-checkin-row">
      <?php if ($me && (int) $me['id'] === (int) $user['id'] && !$userCheckedToday && user_feature_enabled($me, 'checkin')): ?>
        <form method="post" class="pc-checkin-form">
          <?= csrf_field() ?><input type="hidden" name="act" value="checkin">
          <button class="pc-checkin-status off pc-checkin-action" type="submit" title="点击立即签到">今日未签到 · 点击签到</button>
        </form>
      <?php else: ?>
        <span class="pc-checkin-status <?= $userCheckedToday ? 'on' : 'off' ?>"><?= $userCheckedToday ? '今日已签到' : '今日未签到' ?></span>
      <?php endif; ?>
      <span class="pc-checkin-streak">连续签到 <b><?= $userStreak ?></b> 天</span>
      <span class="pc-checkin-points">积分 <b><?= e(points_text($user)) ?></b></span>
    </div>
    <?php endif; ?>
    <?php
      $isSelf = $me && (int) $me['id'] === (int) $user['id'];
      $isAdminViewer = $me && is_admin($me);
      $pendingCount = post_review_pending_count((int) $user['id']);
      $locMode = profile_location_mode($user);
      $canSeeLoc = $locMode > 0;
      $canSeeIp = $isAdminViewer || $isSelf || (int) ($user['show_ip'] ?? 1) === 1;
      $viewLoc = $canSeeLoc ? profile_location_public_text($user) : '';
      $targetIp = trim((string) ($user['last_ip'] ?? ''));
    ?>
    <div class="pc-location">
      <?php if ($canSeeLoc && $viewLoc !== '' && $viewLoc !== '未设置所在地'): ?><span class="pc-addr">📍 <?= e($viewLoc) ?></span><?php endif; ?>
      <?php if ($canSeeIp && $targetIp !== ''): ?><span class="pc-ip"><?= $isSelf ? '我的 IP' : 'IP' ?>：<?= e(($isSelf || $isAdminViewer) ? $targetIp : mask_ip_profile($targetIp)) ?></span><?php endif; ?>
      <?php if ($canSeeIp && !$isOfficialProfile): ?><span class="pc-ip-note">完整 IP 仅对本人可见</span><?php endif; ?>
      <?php if ($isAdminViewer && $targetIp !== ''): ?>
        <span class="pc-geo-line">实时 IP 属地：<?= e(ip_location_detail_text($targetIp)) ?></span>
      <?php endif; ?>
    </div>
    <?php if ((int) $user['verified'] === 1): ?>
      <div class="pc-verify"><span class="pc-verify-v"><?= verify_badge($user) ?></span><span><?= e(verify_title_of($user)) ?></span></div>
    <?php endif; ?>
    <p class="pc-bio"><?= e($user['bio'] !== '' ? $user['bio'] : '这位茶客还没有写下自我介绍。') ?></p>
    <div class="pc-actions">
      <?php if (($isSelf || $isAdminViewer) && $pendingCount > 0): ?>
        <a class="btn-review-pending block" href="<?= e(page_url('review', ['user' => $uid])) ?>">有帖子正在审核中 <b><?= $pendingCount ?></b></a>
      <?php endif; ?>
      <?php if ($me && (int) $me['id'] === $uid): ?>
        <a class="btn-primary block" href="<?= e(page_url('profile')) ?>">编辑个人资料</a>
      <?php elseif ($me && !$isOfficialTarget): ?>
        <div class="user-actions-row">
          <form method="post" class="inline-form" data-confirm="<?= $blockedBetween ? '取消拉黑？' : '拉黑后双方不再互相显示帖子与评论，确定？' ?>">
            <?= csrf_field() ?><input type="hidden" name="act" value="block">
            <button class="btn-ghost" type="submit"><?= $blockedBetween ? '已拉黑 · 取消' : '拉黑' ?></button>
          </form>
          <?php if ($isFriend): ?>
            <a class="btn-primary" href="<?= e(page_url('friends', ['to' => $uid])) ?>">发消息</a>
          <?php elseif ($incomingReq === 'pending'): ?>
            <form method="post" class="inline-form">
              <?= csrf_field() ?><input type="hidden" name="act" value="accept_friend_request">
              <button class="btn-primary" type="submit">同意好友申请</button>
            </form>
          <?php elseif ($outgoingReq === 'pending'): ?>
            <button class="btn-primary" type="button" disabled>好友申请已发送</button>
          <?php elseif ($outgoingReq === 'declined' || $incomingReq === 'declined'): ?>
            <button class="btn-primary" type="button" disabled>好友申请已被拒绝</button>
          <?php else: ?>
            <form method="post" class="inline-form">
              <?= csrf_field() ?><input type="hidden" name="act" value="add_friend">
              <button class="btn-primary" type="submit">＋ 加为好友</button>
            </form>
          <?php endif; ?>
          <?php if (!$isFriend && !$targetRejectsStranger): ?><a class="btn-primary" href="<?= e(page_url('friends', ['to' => $uid])) ?>">发消息</a><?php endif; ?>
          <a class="btn-primary" href="<?= e(page_url('world', ['user' => $uid])) ?>">TA 的世界圈</a>
        </div>
        <?php if ($isFriend): ?>
        <details class="friend-remark-box pc-remark-box">
          <summary class="btn-mini ghost">设置备注</summary>
          <form method="post">
            <?= csrf_field() ?><input type="hidden" name="act" value="save_friend_remark">
            <input type="text" name="remark" maxlength="32" value="<?= e($friendRemarkOf) ?>" placeholder="输入备注名">
            <button class="btn-primary" type="submit">确认</button>
          </form>
        </details>
        <?php endif; ?>
        <form method="post" class="transfer-inline">
          <?= csrf_field() ?><input type="hidden" name="act" value="transfer_to">
          <input type="number" name="amount" min="1" max="99999" placeholder="转账积分" required>
          <input type="text" name="note" maxlength="60" placeholder="转账备注（选填）">
          <button class="btn-ghost" type="submit">转账积分</button>
        </form>
        <p class="muted transfer-hint">你的余额：<?= e(points_text($me)) ?> 积分</p>
        <details class="report-user-box" id="report">
          <summary class="btn-ghost report-user-open">⚑ 举报该用户</summary>
          <form method="post" class="report-user-form">
            <?= csrf_field() ?><input type="hidden" name="act" value="report_user">
            <label>举报理由</label>
            <textarea name="reason" maxlength="255" rows="4" required placeholder="请说明该用户的具体违规行为，例如昵称、头像或发布内容"></textarea>
            <div class="report-user-actions">
              <button class="btn-primary" type="submit">提交举报</button>
              <span class="muted">提交后会通知管理员，并在通知中心回信</span>
            </div>
          </form>
        </details>
      <?php elseif (!$isOfficialTarget): ?>
        <a class="btn-primary block" href="<?= e(page_url('login', ['next' => page_url('user', ['id' => $uid])])) ?>">登录后私信</a>
      <?php endif; ?>
    </div>
  </div>
</section>

<?php if ($me && is_admin($me) && (int) $me['id'] !== $uid && admin_can_delete_owner($user)): ?>
<section class="panel pc-admin-panel" id="pcAdminOps" data-admin-ops>
  <div class="pc-admin-head">
    <strong>管理员操作</strong>
    <span class="muted">仅管理员可见</span>
  </div>
  <div class="pc-admin-actions">
    <button type="button" class="btn-mini" data-admin-op="mute" aria-expanded="false">禁言</button>
    <button type="button" class="btn-mini" data-admin-op="ban" aria-expanded="false">封禁</button>
    <button type="button" class="btn-mini danger" data-pc-delete-open data-name="<?= e(display_name($user)) ?>">删除用户</button>
  </div>
  <div class="pc-admin-form" data-admin-panel="mute" hidden>
    <form method="post">
      <?= csrf_field() ?><input type="hidden" name="act" value="admin_mute">
      <select name="days" aria-label="禁言时长">
        <option value="1">禁言 1 天</option>
        <option value="7">禁言 7 天</option>
        <option value="30">禁言 30 天</option>
        <option value="0">永久禁言</option>
      </select>
      <input type="text" name="reason" maxlength="255" placeholder="禁言原因（选填）">
      <button class="btn-primary" type="submit">确认禁言</button>
    </form>
  </div>
  <div class="pc-admin-form" data-admin-panel="ban" hidden>
    <form method="post">
      <?= csrf_field() ?><input type="hidden" name="act" value="admin_ban">
      <select name="days" id="pcBanDays" aria-label="封禁时长">
        <option value="1">封禁 1 天</option>
        <option value="7">封禁 7 天</option>
        <option value="30">封禁 30 天</option>
        <option value="0">永久封禁</option>
      </select>
      <input type="text" name="reason" maxlength="255" placeholder="封禁原因（选填）">
      <div class="pc-admin-code" id="pcBanCodeWrap" hidden>
        <p class="muted" id="pcBanCodeHint"><?php
          $adminEmail = trim((string) ($me['email'] ?? ''));
          if ($adminEmail === '' || !filter_var($adminEmail, FILTER_VALIDATE_EMAIL)) {
              echo '当前管理员尚未绑定有效邮箱，无法永久封禁';
          } elseif ((int) ($me['email_verified'] ?? 0) !== 1) {
              echo '当前管理员邮箱尚未验证，请先到认证中心完成验证';
          } else {
              echo '验证码将发送到 ' . e(email_mask($adminEmail)) . '，10 分钟内有效';
          }
        ?></p>
        <button type="button" class="btn-mini ghost" id="pcBanSendCode"<?= (trim((string) ($me['email'] ?? '')) === '' || !filter_var((string) ($me['email'] ?? ''), FILTER_VALIDATE_EMAIL) || (int) ($me['email_verified'] ?? 0) !== 1) ? ' disabled' : '' ?>>发送邮箱验证码</button>
        <label for="pcBanEmailCode">邮箱验证码</label>
        <input type="text" name="ban_email_code" id="pcBanEmailCode" inputmode="numeric" maxlength="6" pattern="\d{6}" autocomplete="one-time-code" placeholder="永久封禁需填 6 位验证码">
      </div>
      <button class="btn-primary" type="submit">确认封禁</button>
    </form>
  </div>
  <p class="pc-admin-note muted">删除账号与永久封禁必须先验证你本人绑定的邮箱，验证码 10 分钟内有效；永久封禁会同步封禁该账号最近使用的 IP 与设备。</p>
</section>
<?php endif; ?>

<?= profile_visitor_panel_html($uid, $visitorCount, $isSelfProfile) ?>

<section class="pc-stats">
  <a href="<?= e(page_url('user', ['id' => $uid, 'view' => 'posts'])) ?>"><b><?= $postCount ?></b><span>帖子</span></a>
  <a href="<?= e(page_url('user', ['id' => $uid, 'view' => 'comments'])) ?>#user-comments" title="查看 TA 评论过的帖子"><b><?= $commentCount ?></b><span>评论</span></a>
  <a href="<?= e(page_url('world', ['user' => $uid])) ?>"><b><?= $momentCount ?></b><span>世界圈</span></a>
  <a href="<?= e(page_url('followers', ['id' => $uid, 'tab' => 'followers'])) ?>"><b><?= follow_count('user', $uid) ?></b><span>关注 TA</span></a>
  <div><b><?= $likeReceived ?></b><span>获赞</span></div>
  <div><b><?= e(points_text($user)) ?></b><span>积分</span></div>
</section>

<?php if ($view === 'comments'): ?>
<section class="panel" id="user-comments">
  <div class="panel-head row">
    <h2 class="section-title">TA 的评论</h2>
    <a class="link-btn" href="<?= e(page_url('user', ['id' => $uid])) ?>">返回 TA 的帖子</a>
  </div>
  <?php if (!$commentPosts): ?>
    <?php empty_state('还没有评论过帖子'); ?>
  <?php else: ?>
    <div class="comment-post-list">
      <?php foreach ($commentPosts as $cp): ?>
        <?php
          $quote = trim((string) $cp['comment_content']);
          $quoteShort = mb_strlen($quote) > 140 ? mb_substr($quote, 0, 140) . '…' : $quote;
        ?>
        <article class="comment-post-card">
          <div class="comment-post-title-line">
            <?php if ($cp['password'] !== ''): ?><span class="tag lock" title="密码帖">🔒</span><?php endif; ?>
            <a href="<?= e(page_url('post', ['id' => $cp['id']])) ?>#comments"><?= e($cp['title']) ?></a>
          </div>
          <p class="comment-quote">“<?= nl2br(e($quoteShort)) ?>”</p>
          <div class="comment-post-meta">
            <span><?= e(time_ago($cp['comment_at'])) ?></span>
            <a href="<?= e(page_url('post', ['id' => $cp['id']])) ?>#comments">查看帖子 →</a>
          </div>
        </article>
      <?php endforeach; ?>
    </div>
  <?php endif; ?>
</section>
<?php else: ?>
<section class="panel">
  <h2 class="section-title">TA 的帖子</h2>
  <?php if (!$posts): ?>
    <?php empty_state('还没有发布帖子'); ?>
  <?php else: ?>
    <div class="post-list">
      <?php foreach ($posts as $p): ?>
        <?php $locked = $p['password'] !== ''; ?>
        <article class="post-card v2">
          <div class="post-meta v2">
            <a class="post-avatar-wrap" href="<?= e(page_url('user', ['id' => $uid])) ?>">
              <?= avatar_html($user) ?>
              <?php if ((int) $user['verified'] === 1): ?><span class="avatar-v v-<?= verify_style_of($user) ?>">V</span><?php endif; ?>
            </a>
            <a class="author" href="<?= e(page_url('user', ['id' => $uid])) ?>"><?= e(display_name($user)) ?></a><?= verify_badge($user) ?>
            <span class="dot">·</span>
            <span class="time"><?= e(date('Y/m/d H:i:s', strtotime($p['created_at']))) ?></span>
          </div>
          <div class="post-title-row">
            <span class="post-share-spacer"></span>
            <h2 class="post-title">
              <?php if ((int) $p['is_top'] === 1): ?><span class="tag top">置顶</span><?php endif; ?>
              <?php if ((int) $p['is_featured'] === 1): ?><span class="tag feat">精华</span><?php endif; ?>
              <?php if ($locked): ?><span class="tag lock" title="密码帖">密码帖子</span><?php endif; ?>
              <a href="<?= e(page_url('post', ['id' => $p['id']])) ?>"><?= e(post_display_title($p, 90)) ?></a>
        <?php if ((int) ($p['is_locked'] ?? 0) === 1): ?><span class="tag locked post-title-locked" title="帖子已锁定">🔒</span><?php endif; ?>
            </h2>
            <button class="post-share" type="button" title="分享帖子"
                    onclick="KM.sharePost('<?= e(page_url('post', ['id' => $p['id']])) ?>', '<?= e(post_display_title($p, 90)) ?>')">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6"><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><path d="M8.6 10.6l6.8-4M8.6 13.4l6.8 4"/></svg>
            </button>
          </div>
        </article>
      <?php endforeach; ?>
    </div>
  <?php endif; ?>
</section>
<?php endif; ?>

<script>
(function () {
  var sound = document.getElementById('pcBgSound');
  var video = document.getElementById('pcBgVideo');
  if (!sound || !video) return;
  sound.addEventListener('click', function () {
    video.muted = !video.muted;
    if (!video.muted && video.volume === 0) video.volume = 1;
    sound.textContent = video.muted ? '🔕' : '🔔';
    sound.title = video.muted ? '开启背景声音' : '关闭背景声音';
    sound.setAttribute('aria-label', sound.title);
    var p = video.play();
    if (p && p.catch) p.catch(function () {});
  });
})();
</script>
<script>
(function () {
  var root = document.querySelector('[data-admin-ops]');
  if (!root) return;
  var buttons = root.querySelectorAll('[data-admin-op]');
  var panels = root.querySelectorAll('[data-admin-panel]');
  function closeAll(except) {
    buttons.forEach(function (btn) {
      if (btn === except) return;
      btn.setAttribute('aria-expanded', 'false');
      btn.classList.remove('is-open');
    });
    panels.forEach(function (panel) {
      if (except && panel.getAttribute('data-admin-panel') === except.getAttribute('data-admin-op')) return;
      panel.hidden = true;
    });
  }
  buttons.forEach(function (btn) {
    btn.addEventListener('click', function () {
      var key = btn.getAttribute('data-admin-op');
      var panel = root.querySelector('[data-admin-panel="' + key + '"]');
      var wasOpen = btn.getAttribute('aria-expanded') === 'true';
      closeAll(null);
      if (wasOpen) return;
      btn.setAttribute('aria-expanded', 'true');
      btn.classList.add('is-open');
      if (panel) {
        panel.hidden = false;
        setTimeout(function () { try { panel.scrollIntoView({behavior: 'smooth', block: 'nearest'}); } catch (e) {} }, 40);
      }
    });
  });
})();
</script>
<script>
(function () {
  var days = document.getElementById('pcBanDays');
  var wrap = document.getElementById('pcBanCodeWrap');
  var code = document.getElementById('pcBanEmailCode');
  var send = document.getElementById('pcBanSendCode');
  var hint = document.getElementById('pcBanCodeHint');
  if (!days || !wrap || !code) return;
  var targetUid = <?= (int) $uid ?>;
  function syncPermanent() {
    var permanent = days.value === '0';
    wrap.hidden = !permanent;
    code.required = permanent;
    if (!permanent) code.value = '';
  }
  days.addEventListener('change', syncPermanent);
  syncPermanent();
  if (!send) return;
  send.addEventListener('click', function () {
    send.disabled = true;
    send.textContent = '发送中…';
    if (hint) hint.textContent = '正在发送验证码…';
    if (!window.KM || !KM.api) {
      if (hint) hint.textContent = '页面脚本未加载，请刷新后重试';
      send.disabled = false;
      send.textContent = '发送邮箱验证码';
      return;
    }
    KM.api('admin_ban_send_code', { uid: targetUid }).then(function (res) {
      if (res && res.ok) {
        if (hint) hint.textContent = '验证码已发送到 ' + (res.email_mask || '你的绑定邮箱') + '，10 分钟内有效';
      } else {
        if (hint) hint.textContent = (res && res.msg) ? res.msg : '发送失败，请稍后重试';
      }
      send.disabled = false;
      send.textContent = '重新发送验证码';
    }).catch(function () {
      if (hint) hint.textContent = '网络异常，请稍后重试';
      send.disabled = false;
      send.textContent = '重新发送验证码';
    });
  });
})();
</script>
<script>
(function () {
  var toggle = document.querySelector('[data-visitor-toggle]');
  var panel = document.getElementById('pcVisitorPanel');
  if (!toggle || !panel) return;
  toggle.addEventListener('click', function () {
    var open = toggle.getAttribute('aria-expanded') === 'true';
    toggle.setAttribute('aria-expanded', open ? 'false' : 'true');
    panel.hidden = open;
    if (!open) {
      setTimeout(function () { try { panel.scrollIntoView({behavior: 'smooth', block: 'nearest'}); } catch (e) {} }, 30);
    }
  });
})();
</script>
<section class="modal delete-account-modal" id="pcDeleteUserModal" hidden>
  <div class="modal-mask" data-pc-delete-close></div>
  <div class="modal-card">
    <div class="sa-lock-modal-head">
      <h3 id="pcDeleteUserTitle">删除账号</h3>
      <button type="button" class="readers-close" data-pc-delete-close>×</button>
    </div>
    <p class="muted">删除会清空该账号的帖子、评论、网盘与图床内容，删除前会完整归档以便恢复。必须先用你本人绑定的管理员邮箱接收并输入 6 位验证码。</p>
    <p class="muted" id="pcDeleteUserEmailHint">验证码将发送到：<?= e(trim((string) ($me['email'] ?? '')) !== '' ? email_mask((string) $me['email']) : '当前管理员尚未绑定邮箱，无法删除') ?></p>
    <button type="button" class="btn-mini ghost" id="pcDeleteUserSendCode">发送邮箱验证码</button>
    <form method="post" class="auth-form" id="pcDeleteUserForm" onsubmit="return confirm('确认删除该账号？账号资料会进入恢复存档，已清理的内容不会恢复。');">
      <?= csrf_field() ?>
      <input type="hidden" name="act" value="admin_delete_user">
      <label for="pcDeleteUserCode">邮箱验证码</label>
      <input type="text" name="delete_email_code" id="pcDeleteUserCode" inputmode="numeric" maxlength="6" pattern="\d{6}" autocomplete="one-time-code" placeholder="6 位验证码" required>
      <div class="modal-actions">
        <button type="button" class="btn-mini ghost" data-pc-delete-close>取消</button>
        <button type="submit" class="btn-mini danger">确认删除</button>
      </div>
    </form>
  </div>
</section>

<script>
(function () {
  var modal = document.getElementById('pcDeleteUserModal');
  if (!modal) return;
  var title = document.getElementById('pcDeleteUserTitle');
  var hint = document.getElementById('pcDeleteUserEmailHint');
  var sendBtn = document.getElementById('pcDeleteUserSendCode');
  var codeInput = document.getElementById('pcDeleteUserCode');
  var targetUid = <?= (int) $uid ?>;

  function close() {
    modal.hidden = true;
    document.body.classList.remove('crop-open');
  }
  document.querySelectorAll('[data-pc-delete-close]').forEach(function (el) {
    el.addEventListener('click', close);
  });
  document.addEventListener('keydown', function (e) {
    if (e.key === 'Escape' && !modal.hidden) close();
  });
  document.addEventListener('click', function (e) {
    var btn = e.target.closest('[data-pc-delete-open]');
    if (!btn) return;
    var name = btn.getAttribute('data-name') || '该用户';
    title.textContent = '删除账号 · ' + name;
    hint.textContent = '验证码将发送到你的绑定邮箱。';
    codeInput.value = '';
    sendBtn.disabled = false;
    sendBtn.textContent = '发送邮箱验证码';
    modal.hidden = false;
    document.body.classList.add('crop-open');
    codeInput.focus();
  });

  sendBtn.addEventListener('click', function () {
    sendBtn.disabled = true;
    sendBtn.textContent = '发送中…';
    hint.textContent = '正在发送验证码…';
    if (!window.KM || !KM.api) {
      hint.textContent = '页面脚本未加载，请刷新后重试';
      sendBtn.disabled = false;
      sendBtn.textContent = '发送邮箱验证码';
      return;
    }
    KM.api('admin_delete_send_code', { uid: targetUid }).then(function (res) {
      if (res && res.ok) {
        hint.textContent = '验证码已发送到 ' + (res.email_mask || '你的绑定邮箱') + '，10 分钟内有效';
        sendBtn.textContent = '重新发送验证码';
      } else {
        hint.textContent = (res && res.msg) ? res.msg : '发送失败，请稍后重试';
        sendBtn.textContent = '重新发送验证码';
      }
      sendBtn.disabled = false;
    }).catch(function () {
      hint.textContent = '网络异常，请稍后重试';
      sendBtn.disabled = false;
      sendBtn.textContent = '重新发送验证码';
    });
  });
})();
</script>
<?php render_footer(); ?>