<?php

function cmsAuditClassify($action, $module = '', $content = '')
{
    $text = strtolower(trim((string) $action) . ' ' . trim((string) $module) . ' ' . trim((string) $content));
    $category = 'content';
    if (preg_match('/登录|login|密码|账号|管理员|角色|权限|授权/u', $text)) { $category = 'security'; }
    elseif (preg_match('/数据库|备份|恢复|修复|优化/u', $text)) { $category = 'system'; }
    elseif (preg_match('/审核|发布|驳回|回收|恢复|删除/u', $text)) { $category = 'workflow'; }
    elseif (preg_match('/设置|配置|模板|装修|导入|导出/u', $text)) { $category = 'configuration'; }

    $risk = 'low';
    if (preg_match('/永久删除|删除管理员|删除角色|恢复数据库|重置|登录锁定|登录失败|禁用|权限/u', $text)) { $risk = 'high'; }
    elseif (preg_match('/删除|回收|导入|恢复|发布|审核|驳回|备份|修改管理员|修改角色/u', $text)) { $risk = 'medium'; }
    return ['category' => $category, 'risk' => $risk];
}

function cmsAuditCategoryLabel($category)
{
    $labels = ['security'=>'安全事件','system'=>'系统运维','workflow'=>'内容流程','configuration'=>'配置变更','content'=>'内容操作'];
    return $labels[$category] ?? '内容操作';
}

function cmsAuditRiskLabel($risk)
{
    return ['low'=>'常规','medium'=>'关注','high'=>'高风险'][$risk] ?? '常规';
}

function cmsAuditMatches(array $log, $category = '', $risk = '')
{
    $meta = cmsAuditClassify($log['action'] ?? '', $log['module'] ?? '', $log['content'] ?? '');
    return ($category === '' || $meta['category'] === $category) && ($risk === '' || $meta['risk'] === $risk);
}

function cmsAuditCsvCell($value)
{
    $value = str_replace(["\r\n", "\r", "\n"], ' ', (string) $value);
    if (preg_match('/^[=+\-@]/', $value)) { $value = "'" . $value; }
    return $value;
}

function cmsAuditFilterRows(array $rows, $category = '', $risk = '')
{
    if ($category === '' && $risk === '') { return $rows; }
    return array_values(array_filter($rows, function ($row) use ($category, $risk) { return cmsAuditMatches($row, $category, $risk); }));
}
