<?php

function cmsGlobalSearchNormalizeQuery($query)
{
    $query=trim(preg_replace('/\s+/u',' ',(string)$query));
    if(function_exists('mb_substr'))$query=mb_substr($query,0,60,'UTF-8');else$query=substr($query,0,60);
    return $query;
}

function cmsGlobalSearchCommands()
{
    return [
        ['module'=>'dashboard','title'=>'后台概况','keywords'=>'首页 仪表盘 dashboard','url'=>'/admin/main.php?act=dashboard','icon'=>'fa-home'],
        ['module'=>'article','title'=>'文章管理','keywords'=>'文章 内容 发布 审核','url'=>'/admin/main.php?act=article','icon'=>'fa-newspaper-o'],
        ['module'=>'product','title'=>'产品管理','keywords'=>'产品 商品 内容','url'=>'/admin/main.php?act=product','icon'=>'fa-cubes'],
        ['module'=>'content_quality','title'=>'内容质量','keywords'=>'SEO 封面 摘要 重复标题 链接','url'=>'/admin/main.php?act=content_quality','icon'=>'fa-check-square-o'],
        ['module'=>'media','title'=>'媒体资源','keywords'=>'图片 附件 上传 文件','url'=>'/admin/main.php?act=media','icon'=>'fa-picture-o'],
        ['module'=>'channel','title'=>'栏目管理','keywords'=>'栏目 导航 分类','url'=>'/admin/main.php?act=channel','icon'=>'fa-sitemap'],
        ['module'=>'member','title'=>'会员管理','keywords'=>'会员 用户 客户','url'=>'/admin/main.php?act=member','icon'=>'fa-user'],
        ['module'=>'builder','title'=>'页面装修','keywords'=>'建站 拖拽 页面 装修','url'=>'/admin/main.php?act=builder','icon'=>'fa-columns'],
        ['module'=>'notification','title'=>'通知中心','keywords'=>'提醒 待办 异常 风险','url'=>'/admin/main.php?act=notification','icon'=>'fa-bell-o'],
        ['module'=>'task_center','title'=>'后台任务','keywords'=>'任务 调度 定时发布 备份 扫描 运行记录','url'=>'/admin/main.php?act=task_center','icon'=>'fa-tasks'],
        ['module'=>'redirect','title'=>'404 与跳转','keywords'=>'301 302 重定向 失效链接','url'=>'/admin/main.php?act=redirect','icon'=>'fa-random'],
        ['module'=>'system_status','title'=>'系统状态','keywords'=>'环境 PHP MySQL 磁盘 任务','url'=>'/admin/main.php?act=system_status','icon'=>'fa-heartbeat'],
        ['module'=>'log','title'=>'审计日志','keywords'=>'操作 日志 安全 风险','url'=>'/admin/main.php?act=log','icon'=>'fa-shield'],
        ['module'=>'site','title'=>'网站设置','keywords'=>'站点 配置 域名 SEO','url'=>'/admin/main.php?act=site','icon'=>'fa-cogs'],
    ];
}

function cmsGlobalSearchCan(array $access,$module)
{
    return !function_exists('cmsAdminCan')||cmsAdminCan($access,$module,'view');
}

function cmsGlobalSearch($db,array $access,$query,$limit=30)
{
    $query=cmsGlobalSearchNormalizeQuery($query);$length=function_exists('mb_strlen')?mb_strlen($query,'UTF-8'):strlen($query);if($length<2)return[];$limit=max(5,min(50,intval($limit)));$results=[];$needle=function_exists('mb_strtolower')?mb_strtolower($query,'UTF-8'):strtolower($query);
    foreach(cmsGlobalSearchCommands() as$command){if(!cmsGlobalSearchCan($access,$command['module']))continue;$haystack=$command['title'].' '.$command['keywords'];$normalized=function_exists('mb_strtolower')?mb_strtolower($haystack,'UTF-8'):strtolower($haystack);if(strpos($normalized,$needle)!==false)$results[]=['type'=>'command','type_label'=>'后台功能','title'=>$command['title'],'description'=>'打开后台功能','url'=>$command['url'],'icon'=>$command['icon']];}
    $sources=[
        ['module'=>'article','table'=>'article','title'=>'title','extras'=>['tags'],'label'=>'文章','where'=>'deleted_at=0','url'=>'/admin/main.php?act=article&action=edit&id='],
        ['module'=>'product','table'=>'product','title'=>'title','extras'=>['product_code'],'label'=>'产品','where'=>'deleted_at=0','url'=>'/admin/main.php?act=product&action=edit&id='],
        ['module'=>'channel','table'=>'channel','title'=>'channel_name','extras'=>['channel_dir'],'label'=>'栏目','where'=>'1=1','url'=>'/admin/main.php?act=channel&action=edit&id='],
        ['module'=>'page','table'=>'page','title'=>'page_title','extras'=>['seo_title'],'label'=>'单页','where'=>'deleted_at=0','url'=>'/admin/main.php?act=page&action=edit&id='],
        ['module'=>'member','table'=>'member','title'=>'username','extras'=>['nickname','email','phone'],'label'=>'会员','where'=>'1=1','url'=>'/admin/main.php?act=member&action=edit&id='],
    ];
    foreach($sources as$source){if(count($results)>=$limit||!cmsGlobalSearchCan($access,$source['module']))continue;try{$columns=array_column($db->fetchAll('SHOW COLUMNS FROM '.$db->table($source['table'])),'Field');if(!in_array($source['title'],$columns,true))continue;$extras=array_values(array_intersect($source['extras'],$columns));if(!$extras)$extras=[$source['title']];$extraSql="CONCAT_WS(' · ',`".implode('`,`',$extras)."`)";$where=$source['where'];if(strpos($where,'deleted_at')!==false&&!in_array('deleted_at',$columns,true))$where='1=1';$remaining=$limit-count($results);$conditions=array_merge([$source['title']],$extras);$conditionSql=implode(' OR ',array_map(function($field){return'`'.$field.'` LIKE ?';},$conditions));$params=array_fill(0,count($conditions),'%'.$query.'%');$rows=$db->fetchAll("SELECT id,`{$source['title']}` title,{$extraSql} extra FROM {$db->table($source['table'])} WHERE {$where} AND ({$conditionSql}) ORDER BY id DESC LIMIT {$remaining}",$params);foreach($rows as$row){$description=trim((string)($row['extra']??''));if($description===(string)$row['title'])$description='';$results[]=['type'=>$source['module'],'type_label'=>$source['label'],'title'=>(string)$row['title'],'description'=>$description,'url'=>$source['url'].intval($row['id']),'icon'=>'fa-search'];}}catch(Throwable$e){continue;}}
    return array_slice($results,0,$limit);
}
