<?php
/**
 * 小黑屋：处罚记录、处罚中列表与到期释放列表。
 */

function blackroom_ensure_schema()
{
    static $done = false;
    if ($done) {
        return;
    }
    $done = true;
    try {
        $sql = DB::$driver === 'sqlite'
            ? 'CREATE TABLE IF NOT EXISTS ' . DB::table('punishments') . " (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                user_id INT DEFAULT 0,
                type VARCHAR(20) DEFAULT '',
                reason VARCHAR(255) DEFAULT '',
                start_at VARCHAR(20) DEFAULT '',
                end_at VARCHAR(20) DEFAULT '',
                status VARCHAR(20) DEFAULT 'active',
                created_by INT DEFAULT 0,
                released_at VARCHAR(20) DEFAULT '',
                created_at VARCHAR(20) DEFAULT ''
            )"
            : 'CREATE TABLE IF NOT EXISTS ' . DB::table('punishments') . " (
                id INT AUTO_INCREMENT PRIMARY KEY,
                user_id INT DEFAULT 0,
                type VARCHAR(20) DEFAULT '',
                reason VARCHAR(255) DEFAULT '',
                start_at VARCHAR(20) DEFAULT '',
                end_at VARCHAR(20) DEFAULT '',
                status VARCHAR(20) DEFAULT 'active',
                created_by INT DEFAULT 0,
                released_at VARCHAR(20) DEFAULT '',
                created_at VARCHAR(20) DEFAULT '',
                KEY user_status (user_id, status)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";
        DB::run($sql);
    } catch (Throwable $e) {
        // 表已存在或无权限时忽略，页面会按空数据处理
    }
}

function punishment_type_label($type)
{
    return $type === 'ban' ? '封禁' : ($type === 'site_mute' ? '全站禁言' : '禁言');
}

function punishment_reason_default($type)
{
    return $type === 'ban' ? '违反站点规定' : '违反社区发言规范';
}

function punishment_mark_released($userId, $type = '')
{
    blackroom_ensure_schema();
    $sql = 'UPDATE ' . DB::table('punishments') . " SET status = 'released', released_at = ? WHERE user_id = ? AND status = 'active'";
    $params = [now(), (int) $userId];
    if ($type !== '') {
        $sql .= ' AND type = ?';
        $params[] = (string) $type;
    }
    try {
        DB::run($sql, $params);
    } catch (Throwable $e) {
    }
}

function punishment_record($userId, $type, $reason, $startAt, $endAt, $createdBy = 0)
{
    blackroom_ensure_schema();
    $type = in_array($type, ['ban', 'mute', 'site_mute'], true) ? $type : 'mute';
    $reason = mb_substr(trim((string) $reason), 0, 255);
    if ($reason === '') {
        $reason = punishment_reason_default($type);
    }
    punishment_mark_released((int) $userId, $type);
    try {
        DB::insert('punishments', [
            'user_id'    => (int) $userId,
            'type'       => $type,
            'reason'     => $reason,
            'start_at'   => $startAt !== '' ? $startAt : now(),
            'end_at'     => $endAt !== '' ? $endAt : '9999-12-31 23:59:59',
            'status'     => 'active',
            'created_by' => (int) $createdBy,
            'created_at' => now(),
        ]);
    } catch (Throwable $e) {
    }
}

function blackroom_time_text($value, $permanentText = '永久')
{
    $value = trim((string) $value);
    if ($value === '') {
        return '—';
    }
    if (strpos($value, '9999-') === 0) {
        return $permanentText;
    }
    $ts = strtotime($value);
    return $ts > 0 ? date('Y-m-d H:i', $ts) : $value;
}

function blackroom_latest_punishment($userId, $type)
{
    blackroom_ensure_schema();
    try {
        return DB::one(
            'SELECT * FROM ' . DB::table('punishments') . ' WHERE user_id = ? AND type = ? ORDER BY id DESC LIMIT 1',
            [(int) $userId, (string) $type]
        );
    } catch (Throwable $e) {
        return null;
    }
}

function blackroom_active_rows()
{
    blackroom_ensure_schema();
    $now = now();
    try {
        $rows = DB::all(
            'SELECT * FROM ' . DB::table('users') . " WHERE
                (status = 0 AND ban_until <> '' AND ban_until > ?)
                OR (site_mute_until <> '' AND site_mute_until > ?)
                OR (mute_until <> '' AND mute_until > ?)
             ORDER BY id DESC LIMIT 200",
            [$now, $now, $now]
        );
    } catch (Throwable $e) {
        return [];
    }
    $out = [];
    foreach ($rows as $u) {
        $type = '';
        $endAt = '';
        if ((int) ($u['status'] ?? 1) === 0 && trim((string) ($u['ban_until'] ?? '')) !== '') {
            $type = 'ban';
            $endAt = (string) $u['ban_until'];
        } elseif (trim((string) ($u['site_mute_until'] ?? '')) !== '') {
            $type = 'site_mute';
            $endAt = (string) $u['site_mute_until'];
        } elseif (trim((string) ($u['mute_until'] ?? '')) !== '') {
            $type = 'mute';
            $endAt = (string) $u['mute_until'];
        }
        if ($type === '') {
            continue;
        }
        if (strpos($endAt, '9999-') !== 0 && strtotime($endAt) <= time()) {
            continue;
        }
        $record = blackroom_latest_punishment((int) $u['id'], $type);
        $fallbackReason = $type === 'site_mute' ? (string) ($u['site_mute_reason'] ?? '') : '';
        $reason = trim((string) ($record['reason'] ?? ''));
        if ($reason === '') {
            $reason = $fallbackReason !== '' ? $fallbackReason : punishment_reason_default($type);
        }
        $out[] = [
            'user'     => $u,
            'type'     => $type,
            'typeText' => punishment_type_label($type),
            'reason'   => $reason,
            'start_at' => (string) ($record['start_at'] ?? ''),
            'end_at'   => $endAt,
            'permanent'=> strpos($endAt, '9999-') === 0,
        ];
    }
    return $out;
}

function blackroom_released_rows()
{
    blackroom_ensure_schema();
    $now = now();
    try {
        return DB::all(
            'SELECT p.*, u.username, u.nickname, u.avatar, u.role FROM ' . DB::table('punishments') . ' p
             LEFT JOIN ' . DB::table('users') . " u ON u.id = p.user_id
             WHERE (p.status = 'released' OR (p.status = 'active' AND p.end_at <= ? AND p.end_at NOT LIKE '9999-%'))
             ORDER BY p.id DESC LIMIT 200",
            [$now]
        );
    } catch (Throwable $e) {
        return [];
    }
}
